Bug Summary

File:clang/lib/Sema/SemaExpr.cpp
Warning:line 6065, column 27
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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 "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/EvaluatedExprVisitor.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExprOpenMP.h"
26#include "clang/AST/RecursiveASTVisitor.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/Basic/Builtins.h"
29#include "clang/Basic/FixedPoint.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/SourceManager.h"
32#include "clang/Basic/TargetInfo.h"
33#include "clang/Lex/LiteralSupport.h"
34#include "clang/Lex/Preprocessor.h"
35#include "clang/Sema/AnalysisBasedWarnings.h"
36#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/DelayedDiagnostic.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Initialization.h"
40#include "clang/Sema/Lookup.h"
41#include "clang/Sema/Overload.h"
42#include "clang/Sema/ParsedTemplate.h"
43#include "clang/Sema/Scope.h"
44#include "clang/Sema/ScopeInfo.h"
45#include "clang/Sema/SemaFixItUtils.h"
46#include "clang/Sema/SemaInternal.h"
47#include "clang/Sema/Template.h"
48#include "llvm/Support/ConvertUTF.h"
49#include "llvm/Support/SaveAndRestore.h"
50using namespace clang;
51using namespace sema;
52
53/// Determine whether the use of this declaration is valid, without
54/// emitting diagnostics.
55bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
56 // See if this is an auto-typed variable whose initializer we are parsing.
57 if (ParsingInitForAutoVars.count(D))
58 return false;
59
60 // See if this is a deleted function.
61 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
62 if (FD->isDeleted())
63 return false;
64
65 // If the function has a deduced return type, and we can't deduce it,
66 // then we can't use it either.
67 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
68 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
69 return false;
70
71 // See if this is an aligned allocation/deallocation function that is
72 // unavailable.
73 if (TreatUnavailableAsInvalid &&
74 isUnavailableAlignedAllocationFunction(*FD))
75 return false;
76 }
77
78 // See if this function is unavailable.
79 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
80 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
81 return false;
82
83 return true;
84}
85
86static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
87 // Warn if this is used but marked unused.
88 if (const auto *A = D->getAttr<UnusedAttr>()) {
89 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
90 // should diagnose them.
91 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
92 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
93 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
94 if (DC && !DC->hasAttr<UnusedAttr>())
95 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
96 }
97 }
98}
99
100/// Emit a note explaining that this function is deleted.
101void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
102 assert(Decl && Decl->isDeleted())((Decl && Decl->isDeleted()) ? static_cast<void
> (0) : __assert_fail ("Decl && Decl->isDeleted()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 102, __PRETTY_FUNCTION__))
;
103
104 if (Decl->isDefaulted()) {
105 // If the method was explicitly defaulted, point at that declaration.
106 if (!Decl->isImplicit())
107 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
108
109 // Try to diagnose why this special member function was implicitly
110 // deleted. This might fail, if that reason no longer applies.
111 DiagnoseDeletedDefaultedFunction(Decl);
112 return;
113 }
114
115 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
116 if (Ctor && Ctor->isInheritingConstructor())
117 return NoteDeletedInheritingConstructor(Ctor);
118
119 Diag(Decl->getLocation(), diag::note_availability_specified_here)
120 << Decl << 1;
121}
122
123/// Determine whether a FunctionDecl was ever declared with an
124/// explicit storage class.
125static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
126 for (auto I : D->redecls()) {
127 if (I->getStorageClass() != SC_None)
128 return true;
129 }
130 return false;
131}
132
133/// Check whether we're in an extern inline function and referring to a
134/// variable or function with internal linkage (C11 6.7.4p3).
135///
136/// This is only a warning because we used to silently accept this code, but
137/// in many cases it will not behave correctly. This is not enabled in C++ mode
138/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
139/// and so while there may still be user mistakes, most of the time we can't
140/// prove that there are errors.
141static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
142 const NamedDecl *D,
143 SourceLocation Loc) {
144 // This is disabled under C++; there are too many ways for this to fire in
145 // contexts where the warning is a false positive, or where it is technically
146 // correct but benign.
147 if (S.getLangOpts().CPlusPlus)
148 return;
149
150 // Check if this is an inlined function or method.
151 FunctionDecl *Current = S.getCurFunctionDecl();
152 if (!Current)
153 return;
154 if (!Current->isInlined())
155 return;
156 if (!Current->isExternallyVisible())
157 return;
158
159 // Check if the decl has internal linkage.
160 if (D->getFormalLinkage() != InternalLinkage)
161 return;
162
163 // Downgrade from ExtWarn to Extension if
164 // (1) the supposedly external inline function is in the main file,
165 // and probably won't be included anywhere else.
166 // (2) the thing we're referencing is a pure function.
167 // (3) the thing we're referencing is another inline function.
168 // This last can give us false negatives, but it's better than warning on
169 // wrappers for simple C library functions.
170 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
171 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
172 if (!DowngradeWarning && UsedFn)
173 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
174
175 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
176 : diag::ext_internal_in_extern_inline)
177 << /*IsVar=*/!UsedFn << D;
178
179 S.MaybeSuggestAddingStaticToDecl(Current);
180
181 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
182 << D;
183}
184
185void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
186 const FunctionDecl *First = Cur->getFirstDecl();
187
188 // Suggest "static" on the function, if possible.
189 if (!hasAnyExplicitStorageClass(First)) {
190 SourceLocation DeclBegin = First->getSourceRange().getBegin();
191 Diag(DeclBegin, diag::note_convert_inline_to_static)
192 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
193 }
194}
195
196/// Determine whether the use of this declaration is valid, and
197/// emit any corresponding diagnostics.
198///
199/// This routine diagnoses various problems with referencing
200/// declarations that can occur when using a declaration. For example,
201/// it might warn if a deprecated or unavailable declaration is being
202/// used, or produce an error (and return true) if a C++0x deleted
203/// function is being used.
204///
205/// \returns true if there was an error (this declaration cannot be
206/// referenced), false otherwise.
207///
208bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
209 const ObjCInterfaceDecl *UnknownObjCClass,
210 bool ObjCPropertyAccess,
211 bool AvoidPartialAvailabilityChecks,
212 ObjCInterfaceDecl *ClassReceiver) {
213 SourceLocation Loc = Locs.front();
214 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
215 // If there were any diagnostics suppressed by template argument deduction,
216 // emit them now.
217 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
218 if (Pos != SuppressedDiagnostics.end()) {
219 for (const PartialDiagnosticAt &Suppressed : Pos->second)
220 Diag(Suppressed.first, Suppressed.second);
221
222 // Clear out the list of suppressed diagnostics, so that we don't emit
223 // them again for this specialization. However, we don't obsolete this
224 // entry from the table, because we want to avoid ever emitting these
225 // diagnostics again.
226 Pos->second.clear();
227 }
228
229 // C++ [basic.start.main]p3:
230 // The function 'main' shall not be used within a program.
231 if (cast<FunctionDecl>(D)->isMain())
232 Diag(Loc, diag::ext_main_used);
233
234 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
235 }
236
237 // See if this is an auto-typed variable whose initializer we are parsing.
238 if (ParsingInitForAutoVars.count(D)) {
239 if (isa<BindingDecl>(D)) {
240 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
241 << D->getDeclName();
242 } else {
243 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
244 << D->getDeclName() << cast<VarDecl>(D)->getType();
245 }
246 return true;
247 }
248
249 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
250 // See if this is a deleted function.
251 if (FD->isDeleted()) {
252 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
253 if (Ctor && Ctor->isInheritingConstructor())
254 Diag(Loc, diag::err_deleted_inherited_ctor_use)
255 << Ctor->getParent()
256 << Ctor->getInheritedConstructor().getConstructor()->getParent();
257 else
258 Diag(Loc, diag::err_deleted_function_use);
259 NoteDeletedFunction(FD);
260 return true;
261 }
262
263 // [expr.prim.id]p4
264 // A program that refers explicitly or implicitly to a function with a
265 // trailing requires-clause whose constraint-expression is not satisfied,
266 // other than to declare it, is ill-formed. [...]
267 //
268 // See if this is a function with constraints that need to be satisfied.
269 // Check this before deducing the return type, as it might instantiate the
270 // definition.
271 if (FD->getTrailingRequiresClause()) {
272 ConstraintSatisfaction Satisfaction;
273 if (CheckFunctionConstraints(FD, Satisfaction, Loc))
274 // A diagnostic will have already been generated (non-constant
275 // constraint expression, for example)
276 return true;
277 if (!Satisfaction.IsSatisfied) {
278 Diag(Loc,
279 diag::err_reference_to_function_with_unsatisfied_constraints)
280 << D;
281 DiagnoseUnsatisfiedConstraint(Satisfaction);
282 return true;
283 }
284 }
285
286 // If the function has a deduced return type, and we can't deduce it,
287 // then we can't use it either.
288 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
289 DeduceReturnType(FD, Loc))
290 return true;
291
292 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
293 return true;
294 }
295
296 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
297 // Lambdas are only default-constructible or assignable in C++2a onwards.
298 if (MD->getParent()->isLambda() &&
299 ((isa<CXXConstructorDecl>(MD) &&
300 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
301 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
302 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
303 << !isa<CXXConstructorDecl>(MD);
304 }
305 }
306
307 auto getReferencedObjCProp = [](const NamedDecl *D) ->
308 const ObjCPropertyDecl * {
309 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
310 return MD->findPropertyDecl();
311 return nullptr;
312 };
313 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
314 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
315 return true;
316 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
317 return true;
318 }
319
320 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
321 // Only the variables omp_in and omp_out are allowed in the combiner.
322 // Only the variables omp_priv and omp_orig are allowed in the
323 // initializer-clause.
324 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
325 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
326 isa<VarDecl>(D)) {
327 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
328 << getCurFunction()->HasOMPDeclareReductionCombiner;
329 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
330 return true;
331 }
332
333 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
334 // List-items in map clauses on this construct may only refer to the declared
335 // variable var and entities that could be referenced by a procedure defined
336 // at the same location
337 auto *DMD = dyn_cast<OMPDeclareMapperDecl>(CurContext);
338 if (LangOpts.OpenMP && DMD && !CurContext->containsDecl(D) &&
339 isa<VarDecl>(D)) {
340 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
341 << DMD->getVarName().getAsString();
342 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
343 return true;
344 }
345
346 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
347 AvoidPartialAvailabilityChecks, ClassReceiver);
348
349 DiagnoseUnusedOfDecl(*this, D, Loc);
350
351 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
352
353 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
354 !isUnevaluatedContext()) {
355 // C++ [expr.prim.req.nested] p3
356 // A local parameter shall only appear as an unevaluated operand
357 // (Clause 8) within the constraint-expression.
358 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
359 << D;
360 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
361 return true;
362 }
363
364 return false;
365}
366
367/// DiagnoseSentinelCalls - This routine checks whether a call or
368/// message-send is to a declaration with the sentinel attribute, and
369/// if so, it checks that the requirements of the sentinel are
370/// satisfied.
371void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
372 ArrayRef<Expr *> Args) {
373 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
374 if (!attr)
375 return;
376
377 // The number of formal parameters of the declaration.
378 unsigned numFormalParams;
379
380 // The kind of declaration. This is also an index into a %select in
381 // the diagnostic.
382 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
383
384 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
385 numFormalParams = MD->param_size();
386 calleeType = CT_Method;
387 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
388 numFormalParams = FD->param_size();
389 calleeType = CT_Function;
390 } else if (isa<VarDecl>(D)) {
391 QualType type = cast<ValueDecl>(D)->getType();
392 const FunctionType *fn = nullptr;
393 if (const PointerType *ptr = type->getAs<PointerType>()) {
394 fn = ptr->getPointeeType()->getAs<FunctionType>();
395 if (!fn) return;
396 calleeType = CT_Function;
397 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
398 fn = ptr->getPointeeType()->castAs<FunctionType>();
399 calleeType = CT_Block;
400 } else {
401 return;
402 }
403
404 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
405 numFormalParams = proto->getNumParams();
406 } else {
407 numFormalParams = 0;
408 }
409 } else {
410 return;
411 }
412
413 // "nullPos" is the number of formal parameters at the end which
414 // effectively count as part of the variadic arguments. This is
415 // useful if you would prefer to not have *any* formal parameters,
416 // but the language forces you to have at least one.
417 unsigned nullPos = attr->getNullPos();
418 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel")(((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel"
) ? static_cast<void> (0) : __assert_fail ("(nullPos == 0 || nullPos == 1) && \"invalid null position on sentinel\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 418, __PRETTY_FUNCTION__))
;
419 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
420
421 // The number of arguments which should follow the sentinel.
422 unsigned numArgsAfterSentinel = attr->getSentinel();
423
424 // If there aren't enough arguments for all the formal parameters,
425 // the sentinel, and the args after the sentinel, complain.
426 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
427 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
428 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
429 return;
430 }
431
432 // Otherwise, find the sentinel expression.
433 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
434 if (!sentinelExpr) return;
435 if (sentinelExpr->isValueDependent()) return;
436 if (Context.isSentinelNullExpr(sentinelExpr)) return;
437
438 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
439 // or 'NULL' if those are actually defined in the context. Only use
440 // 'nil' for ObjC methods, where it's much more likely that the
441 // variadic arguments form a list of object pointers.
442 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
443 std::string NullValue;
444 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
445 NullValue = "nil";
446 else if (getLangOpts().CPlusPlus11)
447 NullValue = "nullptr";
448 else if (PP.isMacroDefined("NULL"))
449 NullValue = "NULL";
450 else
451 NullValue = "(void*) 0";
452
453 if (MissingNilLoc.isInvalid())
454 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
455 else
456 Diag(MissingNilLoc, diag::warn_missing_sentinel)
457 << int(calleeType)
458 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
459 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
460}
461
462SourceRange Sema::getExprRange(Expr *E) const {
463 return E ? E->getSourceRange() : SourceRange();
464}
465
466//===----------------------------------------------------------------------===//
467// Standard Promotions and Conversions
468//===----------------------------------------------------------------------===//
469
470/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
471ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
472 // Handle any placeholder expressions which made it here.
473 if (E->getType()->isPlaceholderType()) {
474 ExprResult result = CheckPlaceholderExpr(E);
475 if (result.isInvalid()) return ExprError();
476 E = result.get();
477 }
478
479 QualType Ty = E->getType();
480 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type")((!Ty.isNull() && "DefaultFunctionArrayConversion - missing type"
) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultFunctionArrayConversion - missing type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 480, __PRETTY_FUNCTION__))
;
481
482 if (Ty->isFunctionType()) {
483 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
484 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
485 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
486 return ExprError();
487
488 E = ImpCastExprToType(E, Context.getPointerType(Ty),
489 CK_FunctionToPointerDecay).get();
490 } else if (Ty->isArrayType()) {
491 // In C90 mode, arrays only promote to pointers if the array expression is
492 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
493 // type 'array of type' is converted to an expression that has type 'pointer
494 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
495 // that has type 'array of type' ...". The relevant change is "an lvalue"
496 // (C90) to "an expression" (C99).
497 //
498 // C++ 4.2p1:
499 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
500 // T" can be converted to an rvalue of type "pointer to T".
501 //
502 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
503 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
504 CK_ArrayToPointerDecay).get();
505 }
506 return E;
507}
508
509static void CheckForNullPointerDereference(Sema &S, Expr *E) {
510 // Check to see if we are dereferencing a null pointer. If so,
511 // and if not volatile-qualified, this is undefined behavior that the
512 // optimizer will delete, so warn about it. People sometimes try to use this
513 // to get a deterministic trap and are surprised by clang's behavior. This
514 // only handles the pattern "*null", which is a very syntactic check.
515 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
516 if (UO && UO->getOpcode() == UO_Deref &&
517 UO->getSubExpr()->getType()->isPointerType()) {
518 const LangAS AS =
519 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
520 if ((!isTargetAddressSpace(AS) ||
521 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
522 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
523 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
524 !UO->getType().isVolatileQualified()) {
525 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
526 S.PDiag(diag::warn_indirection_through_null)
527 << UO->getSubExpr()->getSourceRange());
528 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
529 S.PDiag(diag::note_indirection_through_null));
530 }
531 }
532}
533
534static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
535 SourceLocation AssignLoc,
536 const Expr* RHS) {
537 const ObjCIvarDecl *IV = OIRE->getDecl();
538 if (!IV)
539 return;
540
541 DeclarationName MemberName = IV->getDeclName();
542 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
543 if (!Member || !Member->isStr("isa"))
544 return;
545
546 const Expr *Base = OIRE->getBase();
547 QualType BaseType = Base->getType();
548 if (OIRE->isArrow())
549 BaseType = BaseType->getPointeeType();
550 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
551 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
552 ObjCInterfaceDecl *ClassDeclared = nullptr;
553 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
554 if (!ClassDeclared->getSuperClass()
555 && (*ClassDeclared->ivar_begin()) == IV) {
556 if (RHS) {
557 NamedDecl *ObjectSetClass =
558 S.LookupSingleName(S.TUScope,
559 &S.Context.Idents.get("object_setClass"),
560 SourceLocation(), S.LookupOrdinaryName);
561 if (ObjectSetClass) {
562 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
563 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
564 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
565 "object_setClass(")
566 << FixItHint::CreateReplacement(
567 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
568 << FixItHint::CreateInsertion(RHSLocEnd, ")");
569 }
570 else
571 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
572 } else {
573 NamedDecl *ObjectGetClass =
574 S.LookupSingleName(S.TUScope,
575 &S.Context.Idents.get("object_getClass"),
576 SourceLocation(), S.LookupOrdinaryName);
577 if (ObjectGetClass)
578 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
579 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
580 "object_getClass(")
581 << FixItHint::CreateReplacement(
582 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
583 else
584 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
585 }
586 S.Diag(IV->getLocation(), diag::note_ivar_decl);
587 }
588 }
589}
590
591ExprResult Sema::DefaultLvalueConversion(Expr *E) {
592 // Handle any placeholder expressions which made it here.
593 if (E->getType()->isPlaceholderType()) {
594 ExprResult result = CheckPlaceholderExpr(E);
595 if (result.isInvalid()) return ExprError();
596 E = result.get();
597 }
598
599 // C++ [conv.lval]p1:
600 // A glvalue of a non-function, non-array type T can be
601 // converted to a prvalue.
602 if (!E->isGLValue()) return E;
603
604 QualType T = E->getType();
605 assert(!T.isNull() && "r-value conversion on typeless expression?")((!T.isNull() && "r-value conversion on typeless expression?"
) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"r-value conversion on typeless expression?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 605, __PRETTY_FUNCTION__))
;
606
607 // We don't want to throw lvalue-to-rvalue casts on top of
608 // expressions of certain types in C++.
609 if (getLangOpts().CPlusPlus &&
610 (E->getType() == Context.OverloadTy ||
611 T->isDependentType() ||
612 T->isRecordType()))
613 return E;
614
615 // The C standard is actually really unclear on this point, and
616 // DR106 tells us what the result should be but not why. It's
617 // generally best to say that void types just doesn't undergo
618 // lvalue-to-rvalue at all. Note that expressions of unqualified
619 // 'void' type are never l-values, but qualified void can be.
620 if (T->isVoidType())
621 return E;
622
623 // OpenCL usually rejects direct accesses to values of 'half' type.
624 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
625 T->isHalfType()) {
626 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
627 << 0 << T;
628 return ExprError();
629 }
630
631 CheckForNullPointerDereference(*this, E);
632 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
633 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
634 &Context.Idents.get("object_getClass"),
635 SourceLocation(), LookupOrdinaryName);
636 if (ObjectGetClass)
637 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
638 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
639 << FixItHint::CreateReplacement(
640 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
641 else
642 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
643 }
644 else if (const ObjCIvarRefExpr *OIRE =
645 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
646 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
647
648 // C++ [conv.lval]p1:
649 // [...] If T is a non-class type, the type of the prvalue is the
650 // cv-unqualified version of T. Otherwise, the type of the
651 // rvalue is T.
652 //
653 // C99 6.3.2.1p2:
654 // If the lvalue has qualified type, the value has the unqualified
655 // version of the type of the lvalue; otherwise, the value has the
656 // type of the lvalue.
657 if (T.hasQualifiers())
658 T = T.getUnqualifiedType();
659
660 // Under the MS ABI, lock down the inheritance model now.
661 if (T->isMemberPointerType() &&
662 Context.getTargetInfo().getCXXABI().isMicrosoft())
663 (void)isCompleteType(E->getExprLoc(), T);
664
665 ExprResult Res = CheckLValueToRValueConversionOperand(E);
666 if (Res.isInvalid())
667 return Res;
668 E = Res.get();
669
670 // Loading a __weak object implicitly retains the value, so we need a cleanup to
671 // balance that.
672 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
673 Cleanup.setExprNeedsCleanups(true);
674
675 // C++ [conv.lval]p3:
676 // If T is cv std::nullptr_t, the result is a null pointer constant.
677 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
678 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue);
679
680 // C11 6.3.2.1p2:
681 // ... if the lvalue has atomic type, the value has the non-atomic version
682 // of the type of the lvalue ...
683 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
684 T = Atomic->getValueType().getUnqualifiedType();
685 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
686 nullptr, VK_RValue);
687 }
688
689 return Res;
690}
691
692ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
693 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
694 if (Res.isInvalid())
695 return ExprError();
696 Res = DefaultLvalueConversion(Res.get());
697 if (Res.isInvalid())
698 return ExprError();
699 return Res;
700}
701
702/// CallExprUnaryConversions - a special case of an unary conversion
703/// performed on a function designator of a call expression.
704ExprResult Sema::CallExprUnaryConversions(Expr *E) {
705 QualType Ty = E->getType();
706 ExprResult Res = E;
707 // Only do implicit cast for a function type, but not for a pointer
708 // to function type.
709 if (Ty->isFunctionType()) {
710 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
711 CK_FunctionToPointerDecay).get();
712 if (Res.isInvalid())
713 return ExprError();
714 }
715 Res = DefaultLvalueConversion(Res.get());
716 if (Res.isInvalid())
717 return ExprError();
718 return Res.get();
719}
720
721/// UsualUnaryConversions - Performs various conversions that are common to most
722/// operators (C99 6.3). The conversions of array and function types are
723/// sometimes suppressed. For example, the array->pointer conversion doesn't
724/// apply if the array is an argument to the sizeof or address (&) operators.
725/// In these instances, this routine should *not* be called.
726ExprResult Sema::UsualUnaryConversions(Expr *E) {
727 // First, convert to an r-value.
728 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
729 if (Res.isInvalid())
730 return ExprError();
731 E = Res.get();
732
733 QualType Ty = E->getType();
734 assert(!Ty.isNull() && "UsualUnaryConversions - missing type")((!Ty.isNull() && "UsualUnaryConversions - missing type"
) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"UsualUnaryConversions - missing type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 734, __PRETTY_FUNCTION__))
;
735
736 // Half FP have to be promoted to float unless it is natively supported
737 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
738 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
739
740 // Try to perform integral promotions if the object has a theoretically
741 // promotable type.
742 if (Ty->isIntegralOrUnscopedEnumerationType()) {
743 // C99 6.3.1.1p2:
744 //
745 // The following may be used in an expression wherever an int or
746 // unsigned int may be used:
747 // - an object or expression with an integer type whose integer
748 // conversion rank is less than or equal to the rank of int
749 // and unsigned int.
750 // - A bit-field of type _Bool, int, signed int, or unsigned int.
751 //
752 // If an int can represent all values of the original type, the
753 // value is converted to an int; otherwise, it is converted to an
754 // unsigned int. These are called the integer promotions. All
755 // other types are unchanged by the integer promotions.
756
757 QualType PTy = Context.isPromotableBitField(E);
758 if (!PTy.isNull()) {
759 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
760 return E;
761 }
762 if (Ty->isPromotableIntegerType()) {
763 QualType PT = Context.getPromotedIntegerType(Ty);
764 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
765 return E;
766 }
767 }
768 return E;
769}
770
771/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
772/// do not have a prototype. Arguments that have type float or __fp16
773/// are promoted to double. All other argument types are converted by
774/// UsualUnaryConversions().
775ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
776 QualType Ty = E->getType();
777 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type")((!Ty.isNull() && "DefaultArgumentPromotion - missing type"
) ? static_cast<void> (0) : __assert_fail ("!Ty.isNull() && \"DefaultArgumentPromotion - missing type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 777, __PRETTY_FUNCTION__))
;
778
779 ExprResult Res = UsualUnaryConversions(E);
780 if (Res.isInvalid())
781 return ExprError();
782 E = Res.get();
783
784 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
785 // promote to double.
786 // Note that default argument promotion applies only to float (and
787 // half/fp16); it does not apply to _Float16.
788 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
789 if (BTy && (BTy->getKind() == BuiltinType::Half ||
790 BTy->getKind() == BuiltinType::Float)) {
791 if (getLangOpts().OpenCL &&
792 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
793 if (BTy->getKind() == BuiltinType::Half) {
794 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
795 }
796 } else {
797 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
798 }
799 }
800
801 // C++ performs lvalue-to-rvalue conversion as a default argument
802 // promotion, even on class types, but note:
803 // C++11 [conv.lval]p2:
804 // When an lvalue-to-rvalue conversion occurs in an unevaluated
805 // operand or a subexpression thereof the value contained in the
806 // referenced object is not accessed. Otherwise, if the glvalue
807 // has a class type, the conversion copy-initializes a temporary
808 // of type T from the glvalue and the result of the conversion
809 // is a prvalue for the temporary.
810 // FIXME: add some way to gate this entire thing for correctness in
811 // potentially potentially evaluated contexts.
812 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
813 ExprResult Temp = PerformCopyInitialization(
814 InitializedEntity::InitializeTemporary(E->getType()),
815 E->getExprLoc(), E);
816 if (Temp.isInvalid())
817 return ExprError();
818 E = Temp.get();
819 }
820
821 return E;
822}
823
824/// Determine the degree of POD-ness for an expression.
825/// Incomplete types are considered POD, since this check can be performed
826/// when we're in an unevaluated context.
827Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
828 if (Ty->isIncompleteType()) {
829 // C++11 [expr.call]p7:
830 // After these conversions, if the argument does not have arithmetic,
831 // enumeration, pointer, pointer to member, or class type, the program
832 // is ill-formed.
833 //
834 // Since we've already performed array-to-pointer and function-to-pointer
835 // decay, the only such type in C++ is cv void. This also handles
836 // initializer lists as variadic arguments.
837 if (Ty->isVoidType())
838 return VAK_Invalid;
839
840 if (Ty->isObjCObjectType())
841 return VAK_Invalid;
842 return VAK_Valid;
843 }
844
845 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
846 return VAK_Invalid;
847
848 if (Ty.isCXX98PODType(Context))
849 return VAK_Valid;
850
851 // C++11 [expr.call]p7:
852 // Passing a potentially-evaluated argument of class type (Clause 9)
853 // having a non-trivial copy constructor, a non-trivial move constructor,
854 // or a non-trivial destructor, with no corresponding parameter,
855 // is conditionally-supported with implementation-defined semantics.
856 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
857 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
858 if (!Record->hasNonTrivialCopyConstructor() &&
859 !Record->hasNonTrivialMoveConstructor() &&
860 !Record->hasNonTrivialDestructor())
861 return VAK_ValidInCXX11;
862
863 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
864 return VAK_Valid;
865
866 if (Ty->isObjCObjectType())
867 return VAK_Invalid;
868
869 if (getLangOpts().MSVCCompat)
870 return VAK_MSVCUndefined;
871
872 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
873 // permitted to reject them. We should consider doing so.
874 return VAK_Undefined;
875}
876
877void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
878 // Don't allow one to pass an Objective-C interface to a vararg.
879 const QualType &Ty = E->getType();
880 VarArgKind VAK = isValidVarArgType(Ty);
881
882 // Complain about passing non-POD types through varargs.
883 switch (VAK) {
884 case VAK_ValidInCXX11:
885 DiagRuntimeBehavior(
886 E->getBeginLoc(), nullptr,
887 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
888 LLVM_FALLTHROUGH[[gnu::fallthrough]];
889 case VAK_Valid:
890 if (Ty->isRecordType()) {
891 // This is unlikely to be what the user intended. If the class has a
892 // 'c_str' member function, the user probably meant to call that.
893 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
894 PDiag(diag::warn_pass_class_arg_to_vararg)
895 << Ty << CT << hasCStrMethod(E) << ".c_str()");
896 }
897 break;
898
899 case VAK_Undefined:
900 case VAK_MSVCUndefined:
901 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
902 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
903 << getLangOpts().CPlusPlus11 << Ty << CT);
904 break;
905
906 case VAK_Invalid:
907 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
908 Diag(E->getBeginLoc(),
909 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
910 << Ty << CT;
911 else if (Ty->isObjCObjectType())
912 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
913 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
914 << Ty << CT);
915 else
916 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
917 << isa<InitListExpr>(E) << Ty << CT;
918 break;
919 }
920}
921
922/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
923/// will create a trap if the resulting type is not a POD type.
924ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
925 FunctionDecl *FDecl) {
926 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
927 // Strip the unbridged-cast placeholder expression off, if applicable.
928 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
929 (CT == VariadicMethod ||
930 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
931 E = stripARCUnbridgedCast(E);
932
933 // Otherwise, do normal placeholder checking.
934 } else {
935 ExprResult ExprRes = CheckPlaceholderExpr(E);
936 if (ExprRes.isInvalid())
937 return ExprError();
938 E = ExprRes.get();
939 }
940 }
941
942 ExprResult ExprRes = DefaultArgumentPromotion(E);
943 if (ExprRes.isInvalid())
944 return ExprError();
945 E = ExprRes.get();
946
947 // Diagnostics regarding non-POD argument types are
948 // emitted along with format string checking in Sema::CheckFunctionCall().
949 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
950 // Turn this into a trap.
951 CXXScopeSpec SS;
952 SourceLocation TemplateKWLoc;
953 UnqualifiedId Name;
954 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
955 E->getBeginLoc());
956 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
957 /*HasTrailingLParen=*/true,
958 /*IsAddressOfOperand=*/false);
959 if (TrapFn.isInvalid())
960 return ExprError();
961
962 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
963 None, E->getEndLoc());
964 if (Call.isInvalid())
965 return ExprError();
966
967 ExprResult Comma =
968 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
969 if (Comma.isInvalid())
970 return ExprError();
971 return Comma.get();
972 }
973
974 if (!getLangOpts().CPlusPlus &&
975 RequireCompleteType(E->getExprLoc(), E->getType(),
976 diag::err_call_incomplete_argument))
977 return ExprError();
978
979 return E;
980}
981
982/// Converts an integer to complex float type. Helper function of
983/// UsualArithmeticConversions()
984///
985/// \return false if the integer expression is an integer type and is
986/// successfully converted to the complex type.
987static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
988 ExprResult &ComplexExpr,
989 QualType IntTy,
990 QualType ComplexTy,
991 bool SkipCast) {
992 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
993 if (SkipCast) return false;
994 if (IntTy->isIntegerType()) {
995 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
996 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
997 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
998 CK_FloatingRealToComplex);
999 } else {
1000 assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void>
(0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1000, __PRETTY_FUNCTION__))
;
1001 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1002 CK_IntegralComplexToFloatingComplex);
1003 }
1004 return false;
1005}
1006
1007/// Handle arithmetic conversion with complex types. Helper function of
1008/// UsualArithmeticConversions()
1009static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1010 ExprResult &RHS, QualType LHSType,
1011 QualType RHSType,
1012 bool IsCompAssign) {
1013 // if we have an integer operand, the result is the complex type.
1014 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1015 /*skipCast*/false))
1016 return LHSType;
1017 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1018 /*skipCast*/IsCompAssign))
1019 return RHSType;
1020
1021 // This handles complex/complex, complex/float, or float/complex.
1022 // When both operands are complex, the shorter operand is converted to the
1023 // type of the longer, and that is the type of the result. This corresponds
1024 // to what is done when combining two real floating-point operands.
1025 // The fun begins when size promotion occur across type domains.
1026 // From H&S 6.3.4: When one operand is complex and the other is a real
1027 // floating-point type, the less precise type is converted, within it's
1028 // real or complex domain, to the precision of the other type. For example,
1029 // when combining a "long double" with a "double _Complex", the
1030 // "double _Complex" is promoted to "long double _Complex".
1031
1032 // Compute the rank of the two types, regardless of whether they are complex.
1033 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1034
1035 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1036 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1037 QualType LHSElementType =
1038 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1039 QualType RHSElementType =
1040 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1041
1042 QualType ResultType = S.Context.getComplexType(LHSElementType);
1043 if (Order < 0) {
1044 // Promote the precision of the LHS if not an assignment.
1045 ResultType = S.Context.getComplexType(RHSElementType);
1046 if (!IsCompAssign) {
1047 if (LHSComplexType)
1048 LHS =
1049 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1050 else
1051 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1052 }
1053 } else if (Order > 0) {
1054 // Promote the precision of the RHS.
1055 if (RHSComplexType)
1056 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1057 else
1058 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1059 }
1060 return ResultType;
1061}
1062
1063/// Handle arithmetic conversion from integer to float. Helper function
1064/// of UsualArithmeticConversions()
1065static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1066 ExprResult &IntExpr,
1067 QualType FloatTy, QualType IntTy,
1068 bool ConvertFloat, bool ConvertInt) {
1069 if (IntTy->isIntegerType()) {
1070 if (ConvertInt)
1071 // Convert intExpr to the lhs floating point type.
1072 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1073 CK_IntegralToFloating);
1074 return FloatTy;
1075 }
1076
1077 // Convert both sides to the appropriate complex float.
1078 assert(IntTy->isComplexIntegerType())((IntTy->isComplexIntegerType()) ? static_cast<void>
(0) : __assert_fail ("IntTy->isComplexIntegerType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1078, __PRETTY_FUNCTION__))
;
1079 QualType result = S.Context.getComplexType(FloatTy);
1080
1081 // _Complex int -> _Complex float
1082 if (ConvertInt)
1083 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1084 CK_IntegralComplexToFloatingComplex);
1085
1086 // float -> _Complex float
1087 if (ConvertFloat)
1088 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1089 CK_FloatingRealToComplex);
1090
1091 return result;
1092}
1093
1094/// Handle arithmethic conversion with floating point types. Helper
1095/// function of UsualArithmeticConversions()
1096static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1097 ExprResult &RHS, QualType LHSType,
1098 QualType RHSType, bool IsCompAssign) {
1099 bool LHSFloat = LHSType->isRealFloatingType();
1100 bool RHSFloat = RHSType->isRealFloatingType();
1101
1102 // If we have two real floating types, convert the smaller operand
1103 // to the bigger result.
1104 if (LHSFloat && RHSFloat) {
1105 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1106 if (order > 0) {
1107 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1108 return LHSType;
1109 }
1110
1111 assert(order < 0 && "illegal float comparison")((order < 0 && "illegal float comparison") ? static_cast
<void> (0) : __assert_fail ("order < 0 && \"illegal float comparison\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1111, __PRETTY_FUNCTION__))
;
1112 if (!IsCompAssign)
1113 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1114 return RHSType;
1115 }
1116
1117 if (LHSFloat) {
1118 // Half FP has to be promoted to float unless it is natively supported
1119 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1120 LHSType = S.Context.FloatTy;
1121
1122 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1123 /*ConvertFloat=*/!IsCompAssign,
1124 /*ConvertInt=*/ true);
1125 }
1126 assert(RHSFloat)((RHSFloat) ? static_cast<void> (0) : __assert_fail ("RHSFloat"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1126, __PRETTY_FUNCTION__))
;
1127 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1128 /*convertInt=*/ true,
1129 /*convertFloat=*/!IsCompAssign);
1130}
1131
1132/// Diagnose attempts to convert between __float128 and long double if
1133/// there is no support for such conversion. Helper function of
1134/// UsualArithmeticConversions().
1135static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1136 QualType RHSType) {
1137 /* No issue converting if at least one of the types is not a floating point
1138 type or the two types have the same rank.
1139 */
1140 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1141 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1142 return false;
1143
1144 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&((LHSType->isFloatingType() && RHSType->isFloatingType
() && "The remaining types must be floating point types."
) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1145, __PRETTY_FUNCTION__))
1145 "The remaining types must be floating point types.")((LHSType->isFloatingType() && RHSType->isFloatingType
() && "The remaining types must be floating point types."
) ? static_cast<void> (0) : __assert_fail ("LHSType->isFloatingType() && RHSType->isFloatingType() && \"The remaining types must be floating point types.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1145, __PRETTY_FUNCTION__))
;
1146
1147 auto *LHSComplex = LHSType->getAs<ComplexType>();
1148 auto *RHSComplex = RHSType->getAs<ComplexType>();
1149
1150 QualType LHSElemType = LHSComplex ?
1151 LHSComplex->getElementType() : LHSType;
1152 QualType RHSElemType = RHSComplex ?
1153 RHSComplex->getElementType() : RHSType;
1154
1155 // No issue if the two types have the same representation
1156 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1157 &S.Context.getFloatTypeSemantics(RHSElemType))
1158 return false;
1159
1160 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1161 RHSElemType == S.Context.LongDoubleTy);
1162 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1163 RHSElemType == S.Context.Float128Ty);
1164
1165 // We've handled the situation where __float128 and long double have the same
1166 // representation. We allow all conversions for all possible long double types
1167 // except PPC's double double.
1168 return Float128AndLongDouble &&
1169 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1170 &llvm::APFloat::PPCDoubleDouble());
1171}
1172
1173typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1174
1175namespace {
1176/// These helper callbacks are placed in an anonymous namespace to
1177/// permit their use as function template parameters.
1178ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1179 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1180}
1181
1182ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1183 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1184 CK_IntegralComplexCast);
1185}
1186}
1187
1188/// Handle integer arithmetic conversions. Helper function of
1189/// UsualArithmeticConversions()
1190template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1191static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1192 ExprResult &RHS, QualType LHSType,
1193 QualType RHSType, bool IsCompAssign) {
1194 // The rules for this case are in C99 6.3.1.8
1195 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1196 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1197 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1198 if (LHSSigned == RHSSigned) {
1199 // Same signedness; use the higher-ranked type
1200 if (order >= 0) {
1201 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1202 return LHSType;
1203 } else if (!IsCompAssign)
1204 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1205 return RHSType;
1206 } else if (order != (LHSSigned ? 1 : -1)) {
1207 // The unsigned type has greater than or equal rank to the
1208 // signed type, so use the unsigned type
1209 if (RHSSigned) {
1210 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1211 return LHSType;
1212 } else if (!IsCompAssign)
1213 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1214 return RHSType;
1215 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1216 // The two types are different widths; if we are here, that
1217 // means the signed type is larger than the unsigned type, so
1218 // use the signed type.
1219 if (LHSSigned) {
1220 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1221 return LHSType;
1222 } else if (!IsCompAssign)
1223 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1224 return RHSType;
1225 } else {
1226 // The signed type is higher-ranked than the unsigned type,
1227 // but isn't actually any bigger (like unsigned int and long
1228 // on most 32-bit systems). Use the unsigned type corresponding
1229 // to the signed type.
1230 QualType result =
1231 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1232 RHS = (*doRHSCast)(S, RHS.get(), result);
1233 if (!IsCompAssign)
1234 LHS = (*doLHSCast)(S, LHS.get(), result);
1235 return result;
1236 }
1237}
1238
1239/// Handle conversions with GCC complex int extension. Helper function
1240/// of UsualArithmeticConversions()
1241static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1242 ExprResult &RHS, QualType LHSType,
1243 QualType RHSType,
1244 bool IsCompAssign) {
1245 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1246 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1247
1248 if (LHSComplexInt && RHSComplexInt) {
1249 QualType LHSEltType = LHSComplexInt->getElementType();
1250 QualType RHSEltType = RHSComplexInt->getElementType();
1251 QualType ScalarType =
1252 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1253 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1254
1255 return S.Context.getComplexType(ScalarType);
1256 }
1257
1258 if (LHSComplexInt) {
1259 QualType LHSEltType = LHSComplexInt->getElementType();
1260 QualType ScalarType =
1261 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1262 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1263 QualType ComplexType = S.Context.getComplexType(ScalarType);
1264 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1265 CK_IntegralRealToComplex);
1266
1267 return ComplexType;
1268 }
1269
1270 assert(RHSComplexInt)((RHSComplexInt) ? static_cast<void> (0) : __assert_fail
("RHSComplexInt", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1270, __PRETTY_FUNCTION__))
;
1271
1272 QualType RHSEltType = RHSComplexInt->getElementType();
1273 QualType ScalarType =
1274 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1275 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1276 QualType ComplexType = S.Context.getComplexType(ScalarType);
1277
1278 if (!IsCompAssign)
1279 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1280 CK_IntegralRealToComplex);
1281 return ComplexType;
1282}
1283
1284/// Return the rank of a given fixed point or integer type. The value itself
1285/// doesn't matter, but the values must be increasing with proper increasing
1286/// rank as described in N1169 4.1.1.
1287static unsigned GetFixedPointRank(QualType Ty) {
1288 const auto *BTy = Ty->getAs<BuiltinType>();
1289 assert(BTy && "Expected a builtin type.")((BTy && "Expected a builtin type.") ? static_cast<
void> (0) : __assert_fail ("BTy && \"Expected a builtin type.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1289, __PRETTY_FUNCTION__))
;
1290
1291 switch (BTy->getKind()) {
1292 case BuiltinType::ShortFract:
1293 case BuiltinType::UShortFract:
1294 case BuiltinType::SatShortFract:
1295 case BuiltinType::SatUShortFract:
1296 return 1;
1297 case BuiltinType::Fract:
1298 case BuiltinType::UFract:
1299 case BuiltinType::SatFract:
1300 case BuiltinType::SatUFract:
1301 return 2;
1302 case BuiltinType::LongFract:
1303 case BuiltinType::ULongFract:
1304 case BuiltinType::SatLongFract:
1305 case BuiltinType::SatULongFract:
1306 return 3;
1307 case BuiltinType::ShortAccum:
1308 case BuiltinType::UShortAccum:
1309 case BuiltinType::SatShortAccum:
1310 case BuiltinType::SatUShortAccum:
1311 return 4;
1312 case BuiltinType::Accum:
1313 case BuiltinType::UAccum:
1314 case BuiltinType::SatAccum:
1315 case BuiltinType::SatUAccum:
1316 return 5;
1317 case BuiltinType::LongAccum:
1318 case BuiltinType::ULongAccum:
1319 case BuiltinType::SatLongAccum:
1320 case BuiltinType::SatULongAccum:
1321 return 6;
1322 default:
1323 if (BTy->isInteger())
1324 return 0;
1325 llvm_unreachable("Unexpected fixed point or integer type")::llvm::llvm_unreachable_internal("Unexpected fixed point or integer type"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1325)
;
1326 }
1327}
1328
1329/// handleFixedPointConversion - Fixed point operations between fixed
1330/// point types and integers or other fixed point types do not fall under
1331/// usual arithmetic conversion since these conversions could result in loss
1332/// of precsision (N1169 4.1.4). These operations should be calculated with
1333/// the full precision of their result type (N1169 4.1.6.2.1).
1334static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1335 QualType RHSTy) {
1336 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType
()) && "Expected at least one of the operands to be a fixed point type"
) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1337, __PRETTY_FUNCTION__))
1337 "Expected at least one of the operands to be a fixed point type")(((LHSTy->isFixedPointType() || RHSTy->isFixedPointType
()) && "Expected at least one of the operands to be a fixed point type"
) ? static_cast<void> (0) : __assert_fail ("(LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) && \"Expected at least one of the operands to be a fixed point type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1337, __PRETTY_FUNCTION__))
;
1338 assert((LHSTy->isFixedPointOrIntegerType() ||(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1341, __PRETTY_FUNCTION__))
1339 RHSTy->isFixedPointOrIntegerType()) &&(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1341, __PRETTY_FUNCTION__))
1340 "Special fixed point arithmetic operation conversions are only "(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1341, __PRETTY_FUNCTION__))
1341 "applied to ints or other fixed point types")(((LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType
()) && "Special fixed point arithmetic operation conversions are only "
"applied to ints or other fixed point types") ? static_cast<
void> (0) : __assert_fail ("(LHSTy->isFixedPointOrIntegerType() || RHSTy->isFixedPointOrIntegerType()) && \"Special fixed point arithmetic operation conversions are only \" \"applied to ints or other fixed point types\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1341, __PRETTY_FUNCTION__))
;
1342
1343 // If one operand has signed fixed-point type and the other operand has
1344 // unsigned fixed-point type, then the unsigned fixed-point operand is
1345 // converted to its corresponding signed fixed-point type and the resulting
1346 // type is the type of the converted operand.
1347 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1348 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1349 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1350 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1351
1352 // The result type is the type with the highest rank, whereby a fixed-point
1353 // conversion rank is always greater than an integer conversion rank; if the
1354 // type of either of the operands is a saturating fixedpoint type, the result
1355 // type shall be the saturating fixed-point type corresponding to the type
1356 // with the highest rank; the resulting value is converted (taking into
1357 // account rounding and overflow) to the precision of the resulting type.
1358 // Same ranks between signed and unsigned types are resolved earlier, so both
1359 // types are either signed or both unsigned at this point.
1360 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1361 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1362
1363 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1364
1365 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1366 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1367
1368 return ResultTy;
1369}
1370
1371/// Check that the usual arithmetic conversions can be performed on this pair of
1372/// expressions that might be of enumeration type.
1373static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1374 SourceLocation Loc,
1375 Sema::ArithConvKind ACK) {
1376 // C++2a [expr.arith.conv]p1:
1377 // If one operand is of enumeration type and the other operand is of a
1378 // different enumeration type or a floating-point type, this behavior is
1379 // deprecated ([depr.arith.conv.enum]).
1380 //
1381 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1382 // Eventually we will presumably reject these cases (in C++23 onwards?).
1383 QualType L = LHS->getType(), R = RHS->getType();
1384 bool LEnum = L->isUnscopedEnumerationType(),
1385 REnum = R->isUnscopedEnumerationType();
1386 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1387 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1388 (REnum && L->isFloatingType())) {
1389 S.Diag(Loc, S.getLangOpts().CPlusPlus2a
1390 ? diag::warn_arith_conv_enum_float_cxx2a
1391 : diag::warn_arith_conv_enum_float)
1392 << LHS->getSourceRange() << RHS->getSourceRange()
1393 << (int)ACK << LEnum << L << R;
1394 } else if (!IsCompAssign && LEnum && REnum &&
1395 !S.Context.hasSameUnqualifiedType(L, R)) {
1396 unsigned DiagID;
1397 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1398 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1399 // If either enumeration type is unnamed, it's less likely that the
1400 // user cares about this, but this situation is still deprecated in
1401 // C++2a. Use a different warning group.
1402 DiagID = S.getLangOpts().CPlusPlus2a
1403 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx2a
1404 : diag::warn_arith_conv_mixed_anon_enum_types;
1405 } else if (ACK == Sema::ACK_Conditional) {
1406 // Conditional expressions are separated out because they have
1407 // historically had a different warning flag.
1408 DiagID = S.getLangOpts().CPlusPlus2a
1409 ? diag::warn_conditional_mixed_enum_types_cxx2a
1410 : diag::warn_conditional_mixed_enum_types;
1411 } else if (ACK == Sema::ACK_Comparison) {
1412 // Comparison expressions are separated out because they have
1413 // historically had a different warning flag.
1414 DiagID = S.getLangOpts().CPlusPlus2a
1415 ? diag::warn_comparison_mixed_enum_types_cxx2a
1416 : diag::warn_comparison_mixed_enum_types;
1417 } else {
1418 DiagID = S.getLangOpts().CPlusPlus2a
1419 ? diag::warn_arith_conv_mixed_enum_types_cxx2a
1420 : diag::warn_arith_conv_mixed_enum_types;
1421 }
1422 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1423 << (int)ACK << L << R;
1424 }
1425}
1426
1427/// UsualArithmeticConversions - Performs various conversions that are common to
1428/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1429/// routine returns the first non-arithmetic type found. The client is
1430/// responsible for emitting appropriate error diagnostics.
1431QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1432 SourceLocation Loc,
1433 ArithConvKind ACK) {
1434 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1435
1436 if (ACK != ACK_CompAssign) {
1437 LHS = UsualUnaryConversions(LHS.get());
1438 if (LHS.isInvalid())
1439 return QualType();
1440 }
1441
1442 RHS = UsualUnaryConversions(RHS.get());
1443 if (RHS.isInvalid())
1444 return QualType();
1445
1446 // For conversion purposes, we ignore any qualifiers.
1447 // For example, "const float" and "float" are equivalent.
1448 QualType LHSType =
1449 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1450 QualType RHSType =
1451 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1452
1453 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1454 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1455 LHSType = AtomicLHS->getValueType();
1456
1457 // If both types are identical, no conversion is needed.
1458 if (LHSType == RHSType)
1459 return LHSType;
1460
1461 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1462 // The caller can deal with this (e.g. pointer + int).
1463 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1464 return QualType();
1465
1466 // Apply unary and bitfield promotions to the LHS's type.
1467 QualType LHSUnpromotedType = LHSType;
1468 if (LHSType->isPromotableIntegerType())
1469 LHSType = Context.getPromotedIntegerType(LHSType);
1470 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1471 if (!LHSBitfieldPromoteTy.isNull())
1472 LHSType = LHSBitfieldPromoteTy;
1473 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1474 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1475
1476 // If both types are identical, no conversion is needed.
1477 if (LHSType == RHSType)
1478 return LHSType;
1479
1480 // At this point, we have two different arithmetic types.
1481
1482 // Diagnose attempts to convert between __float128 and long double where
1483 // such conversions currently can't be handled.
1484 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1485 return QualType();
1486
1487 // Handle complex types first (C99 6.3.1.8p1).
1488 if (LHSType->isComplexType() || RHSType->isComplexType())
1489 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1490 ACK == ACK_CompAssign);
1491
1492 // Now handle "real" floating types (i.e. float, double, long double).
1493 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1494 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1495 ACK == ACK_CompAssign);
1496
1497 // Handle GCC complex int extension.
1498 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1499 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1500 ACK == ACK_CompAssign);
1501
1502 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1503 return handleFixedPointConversion(*this, LHSType, RHSType);
1504
1505 // Finally, we have two differing integer types.
1506 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1507 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1508}
1509
1510//===----------------------------------------------------------------------===//
1511// Semantic Analysis for various Expression Types
1512//===----------------------------------------------------------------------===//
1513
1514
1515ExprResult
1516Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1517 SourceLocation DefaultLoc,
1518 SourceLocation RParenLoc,
1519 Expr *ControllingExpr,
1520 ArrayRef<ParsedType> ArgTypes,
1521 ArrayRef<Expr *> ArgExprs) {
1522 unsigned NumAssocs = ArgTypes.size();
1523 assert(NumAssocs == ArgExprs.size())((NumAssocs == ArgExprs.size()) ? static_cast<void> (0)
: __assert_fail ("NumAssocs == ArgExprs.size()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1523, __PRETTY_FUNCTION__))
;
1524
1525 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1526 for (unsigned i = 0; i < NumAssocs; ++i) {
1527 if (ArgTypes[i])
1528 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1529 else
1530 Types[i] = nullptr;
1531 }
1532
1533 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1534 ControllingExpr,
1535 llvm::makeArrayRef(Types, NumAssocs),
1536 ArgExprs);
1537 delete [] Types;
1538 return ER;
1539}
1540
1541ExprResult
1542Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1543 SourceLocation DefaultLoc,
1544 SourceLocation RParenLoc,
1545 Expr *ControllingExpr,
1546 ArrayRef<TypeSourceInfo *> Types,
1547 ArrayRef<Expr *> Exprs) {
1548 unsigned NumAssocs = Types.size();
1549 assert(NumAssocs == Exprs.size())((NumAssocs == Exprs.size()) ? static_cast<void> (0) : __assert_fail
("NumAssocs == Exprs.size()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1549, __PRETTY_FUNCTION__))
;
1550
1551 // Decay and strip qualifiers for the controlling expression type, and handle
1552 // placeholder type replacement. See committee discussion from WG14 DR423.
1553 {
1554 EnterExpressionEvaluationContext Unevaluated(
1555 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1556 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1557 if (R.isInvalid())
1558 return ExprError();
1559 ControllingExpr = R.get();
1560 }
1561
1562 // The controlling expression is an unevaluated operand, so side effects are
1563 // likely unintended.
1564 if (!inTemplateInstantiation() &&
1565 ControllingExpr->HasSideEffects(Context, false))
1566 Diag(ControllingExpr->getExprLoc(),
1567 diag::warn_side_effects_unevaluated_context);
1568
1569 bool TypeErrorFound = false,
1570 IsResultDependent = ControllingExpr->isTypeDependent(),
1571 ContainsUnexpandedParameterPack
1572 = ControllingExpr->containsUnexpandedParameterPack();
1573
1574 for (unsigned i = 0; i < NumAssocs; ++i) {
1575 if (Exprs[i]->containsUnexpandedParameterPack())
1576 ContainsUnexpandedParameterPack = true;
1577
1578 if (Types[i]) {
1579 if (Types[i]->getType()->containsUnexpandedParameterPack())
1580 ContainsUnexpandedParameterPack = true;
1581
1582 if (Types[i]->getType()->isDependentType()) {
1583 IsResultDependent = true;
1584 } else {
1585 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1586 // complete object type other than a variably modified type."
1587 unsigned D = 0;
1588 if (Types[i]->getType()->isIncompleteType())
1589 D = diag::err_assoc_type_incomplete;
1590 else if (!Types[i]->getType()->isObjectType())
1591 D = diag::err_assoc_type_nonobject;
1592 else if (Types[i]->getType()->isVariablyModifiedType())
1593 D = diag::err_assoc_type_variably_modified;
1594
1595 if (D != 0) {
1596 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1597 << Types[i]->getTypeLoc().getSourceRange()
1598 << Types[i]->getType();
1599 TypeErrorFound = true;
1600 }
1601
1602 // C11 6.5.1.1p2 "No two generic associations in the same generic
1603 // selection shall specify compatible types."
1604 for (unsigned j = i+1; j < NumAssocs; ++j)
1605 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1606 Context.typesAreCompatible(Types[i]->getType(),
1607 Types[j]->getType())) {
1608 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1609 diag::err_assoc_compatible_types)
1610 << Types[j]->getTypeLoc().getSourceRange()
1611 << Types[j]->getType()
1612 << Types[i]->getType();
1613 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1614 diag::note_compat_assoc)
1615 << Types[i]->getTypeLoc().getSourceRange()
1616 << Types[i]->getType();
1617 TypeErrorFound = true;
1618 }
1619 }
1620 }
1621 }
1622 if (TypeErrorFound)
1623 return ExprError();
1624
1625 // If we determined that the generic selection is result-dependent, don't
1626 // try to compute the result expression.
1627 if (IsResultDependent)
1628 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1629 Exprs, DefaultLoc, RParenLoc,
1630 ContainsUnexpandedParameterPack);
1631
1632 SmallVector<unsigned, 1> CompatIndices;
1633 unsigned DefaultIndex = -1U;
1634 for (unsigned i = 0; i < NumAssocs; ++i) {
1635 if (!Types[i])
1636 DefaultIndex = i;
1637 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1638 Types[i]->getType()))
1639 CompatIndices.push_back(i);
1640 }
1641
1642 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1643 // type compatible with at most one of the types named in its generic
1644 // association list."
1645 if (CompatIndices.size() > 1) {
1646 // We strip parens here because the controlling expression is typically
1647 // parenthesized in macro definitions.
1648 ControllingExpr = ControllingExpr->IgnoreParens();
1649 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1650 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1651 << (unsigned)CompatIndices.size();
1652 for (unsigned I : CompatIndices) {
1653 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1654 diag::note_compat_assoc)
1655 << Types[I]->getTypeLoc().getSourceRange()
1656 << Types[I]->getType();
1657 }
1658 return ExprError();
1659 }
1660
1661 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1662 // its controlling expression shall have type compatible with exactly one of
1663 // the types named in its generic association list."
1664 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1665 // We strip parens here because the controlling expression is typically
1666 // parenthesized in macro definitions.
1667 ControllingExpr = ControllingExpr->IgnoreParens();
1668 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1669 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1670 return ExprError();
1671 }
1672
1673 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1674 // type name that is compatible with the type of the controlling expression,
1675 // then the result expression of the generic selection is the expression
1676 // in that generic association. Otherwise, the result expression of the
1677 // generic selection is the expression in the default generic association."
1678 unsigned ResultIndex =
1679 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1680
1681 return GenericSelectionExpr::Create(
1682 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1683 ContainsUnexpandedParameterPack, ResultIndex);
1684}
1685
1686/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1687/// location of the token and the offset of the ud-suffix within it.
1688static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1689 unsigned Offset) {
1690 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1691 S.getLangOpts());
1692}
1693
1694/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1695/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1696static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1697 IdentifierInfo *UDSuffix,
1698 SourceLocation UDSuffixLoc,
1699 ArrayRef<Expr*> Args,
1700 SourceLocation LitEndLoc) {
1701 assert(Args.size() <= 2 && "too many arguments for literal operator")((Args.size() <= 2 && "too many arguments for literal operator"
) ? static_cast<void> (0) : __assert_fail ("Args.size() <= 2 && \"too many arguments for literal operator\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1701, __PRETTY_FUNCTION__))
;
1702
1703 QualType ArgTy[2];
1704 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1705 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1706 if (ArgTy[ArgIdx]->isArrayType())
1707 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1708 }
1709
1710 DeclarationName OpName =
1711 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1712 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1713 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1714
1715 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1716 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1717 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1718 /*AllowStringTemplate*/ false,
1719 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1720 return ExprError();
1721
1722 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1723}
1724
1725/// ActOnStringLiteral - The specified tokens were lexed as pasted string
1726/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1727/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1728/// multiple tokens. However, the common case is that StringToks points to one
1729/// string.
1730///
1731ExprResult
1732Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1733 assert(!StringToks.empty() && "Must have at least one string!")((!StringToks.empty() && "Must have at least one string!"
) ? static_cast<void> (0) : __assert_fail ("!StringToks.empty() && \"Must have at least one string!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1733, __PRETTY_FUNCTION__))
;
1734
1735 StringLiteralParser Literal(StringToks, PP);
1736 if (Literal.hadError)
1737 return ExprError();
1738
1739 SmallVector<SourceLocation, 4> StringTokLocs;
1740 for (const Token &Tok : StringToks)
1741 StringTokLocs.push_back(Tok.getLocation());
1742
1743 QualType CharTy = Context.CharTy;
1744 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1745 if (Literal.isWide()) {
1746 CharTy = Context.getWideCharType();
1747 Kind = StringLiteral::Wide;
1748 } else if (Literal.isUTF8()) {
1749 if (getLangOpts().Char8)
1750 CharTy = Context.Char8Ty;
1751 Kind = StringLiteral::UTF8;
1752 } else if (Literal.isUTF16()) {
1753 CharTy = Context.Char16Ty;
1754 Kind = StringLiteral::UTF16;
1755 } else if (Literal.isUTF32()) {
1756 CharTy = Context.Char32Ty;
1757 Kind = StringLiteral::UTF32;
1758 } else if (Literal.isPascal()) {
1759 CharTy = Context.UnsignedCharTy;
1760 }
1761
1762 // Warn on initializing an array of char from a u8 string literal; this
1763 // becomes ill-formed in C++2a.
1764 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus2a &&
1765 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1766 Diag(StringTokLocs.front(), diag::warn_cxx2a_compat_utf8_string);
1767
1768 // Create removals for all 'u8' prefixes in the string literal(s). This
1769 // ensures C++2a compatibility (but may change the program behavior when
1770 // built by non-Clang compilers for which the execution character set is
1771 // not always UTF-8).
1772 auto RemovalDiag = PDiag(diag::note_cxx2a_compat_utf8_string_remove_u8);
1773 SourceLocation RemovalDiagLoc;
1774 for (const Token &Tok : StringToks) {
1775 if (Tok.getKind() == tok::utf8_string_literal) {
1776 if (RemovalDiagLoc.isInvalid())
1777 RemovalDiagLoc = Tok.getLocation();
1778 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1779 Tok.getLocation(),
1780 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1781 getSourceManager(), getLangOpts())));
1782 }
1783 }
1784 Diag(RemovalDiagLoc, RemovalDiag);
1785 }
1786
1787 QualType StrTy =
1788 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1789
1790 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1791 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1792 Kind, Literal.Pascal, StrTy,
1793 &StringTokLocs[0],
1794 StringTokLocs.size());
1795 if (Literal.getUDSuffix().empty())
1796 return Lit;
1797
1798 // We're building a user-defined literal.
1799 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1800 SourceLocation UDSuffixLoc =
1801 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1802 Literal.getUDSuffixOffset());
1803
1804 // Make sure we're allowed user-defined literals here.
1805 if (!UDLScope)
1806 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1807
1808 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1809 // operator "" X (str, len)
1810 QualType SizeType = Context.getSizeType();
1811
1812 DeclarationName OpName =
1813 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1814 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1815 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1816
1817 QualType ArgTy[] = {
1818 Context.getArrayDecayedType(StrTy), SizeType
1819 };
1820
1821 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1822 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1823 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1824 /*AllowStringTemplate*/ true,
1825 /*DiagnoseMissing*/ true)) {
1826
1827 case LOLR_Cooked: {
1828 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1829 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1830 StringTokLocs[0]);
1831 Expr *Args[] = { Lit, LenArg };
1832
1833 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1834 }
1835
1836 case LOLR_StringTemplate: {
1837 TemplateArgumentListInfo ExplicitArgs;
1838
1839 unsigned CharBits = Context.getIntWidth(CharTy);
1840 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1841 llvm::APSInt Value(CharBits, CharIsUnsigned);
1842
1843 TemplateArgument TypeArg(CharTy);
1844 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1845 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1846
1847 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1848 Value = Lit->getCodeUnit(I);
1849 TemplateArgument Arg(Context, Value, CharTy);
1850 TemplateArgumentLocInfo ArgInfo;
1851 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1852 }
1853 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1854 &ExplicitArgs);
1855 }
1856 case LOLR_Raw:
1857 case LOLR_Template:
1858 case LOLR_ErrorNoDiagnostic:
1859 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1859)
;
1860 case LOLR_Error:
1861 return ExprError();
1862 }
1863 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 1863)
;
1864}
1865
1866DeclRefExpr *
1867Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1868 SourceLocation Loc,
1869 const CXXScopeSpec *SS) {
1870 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1871 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1872}
1873
1874DeclRefExpr *
1875Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1876 const DeclarationNameInfo &NameInfo,
1877 const CXXScopeSpec *SS, NamedDecl *FoundD,
1878 SourceLocation TemplateKWLoc,
1879 const TemplateArgumentListInfo *TemplateArgs) {
1880 NestedNameSpecifierLoc NNS =
1881 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1882 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1883 TemplateArgs);
1884}
1885
1886NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1887 // A declaration named in an unevaluated operand never constitutes an odr-use.
1888 if (isUnevaluatedContext())
1889 return NOUR_Unevaluated;
1890
1891 // C++2a [basic.def.odr]p4:
1892 // A variable x whose name appears as a potentially-evaluated expression e
1893 // is odr-used by e unless [...] x is a reference that is usable in
1894 // constant expressions.
1895 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1896 if (VD->getType()->isReferenceType() &&
1897 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1898 VD->isUsableInConstantExpressions(Context))
1899 return NOUR_Constant;
1900 }
1901
1902 // All remaining non-variable cases constitute an odr-use. For variables, we
1903 // need to wait and see how the expression is used.
1904 return NOUR_None;
1905}
1906
1907/// BuildDeclRefExpr - Build an expression that references a
1908/// declaration that does not require a closure capture.
1909DeclRefExpr *
1910Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1911 const DeclarationNameInfo &NameInfo,
1912 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
1913 SourceLocation TemplateKWLoc,
1914 const TemplateArgumentListInfo *TemplateArgs) {
1915 bool RefersToCapturedVariable =
1916 isa<VarDecl>(D) &&
1917 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1918
1919 DeclRefExpr *E = DeclRefExpr::Create(
1920 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
1921 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
1922 MarkDeclRefReferenced(E);
1923
1924 // C++ [except.spec]p17:
1925 // An exception-specification is considered to be needed when:
1926 // - in an expression, the function is the unique lookup result or
1927 // the selected member of a set of overloaded functions.
1928 //
1929 // We delay doing this until after we've built the function reference and
1930 // marked it as used so that:
1931 // a) if the function is defaulted, we get errors from defining it before /
1932 // instead of errors from computing its exception specification, and
1933 // b) if the function is a defaulted comparison, we can use the body we
1934 // build when defining it as input to the exception specification
1935 // computation rather than computing a new body.
1936 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
1937 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
1938 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
1939 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
1940 }
1941 }
1942
1943 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1944 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1945 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
1946 getCurFunction()->recordUseOfWeak(E);
1947
1948 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1949 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1950 FD = IFD->getAnonField();
1951 if (FD) {
1952 UnusedPrivateFields.remove(FD);
1953 // Just in case we're building an illegal pointer-to-member.
1954 if (FD->isBitField())
1955 E->setObjectKind(OK_BitField);
1956 }
1957
1958 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1959 // designates a bit-field.
1960 if (auto *BD = dyn_cast<BindingDecl>(D))
1961 if (auto *BE = BD->getBinding())
1962 E->setObjectKind(BE->getObjectKind());
1963
1964 return E;
1965}
1966
1967/// Decomposes the given name into a DeclarationNameInfo, its location, and
1968/// possibly a list of template arguments.
1969///
1970/// If this produces template arguments, it is permitted to call
1971/// DecomposeTemplateName.
1972///
1973/// This actually loses a lot of source location information for
1974/// non-standard name kinds; we should consider preserving that in
1975/// some way.
1976void
1977Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1978 TemplateArgumentListInfo &Buffer,
1979 DeclarationNameInfo &NameInfo,
1980 const TemplateArgumentListInfo *&TemplateArgs) {
1981 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1982 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1983 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1984
1985 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1986 Id.TemplateId->NumArgs);
1987 translateTemplateArguments(TemplateArgsPtr, Buffer);
1988
1989 TemplateName TName = Id.TemplateId->Template.get();
1990 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1991 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1992 TemplateArgs = &Buffer;
1993 } else {
1994 NameInfo = GetNameFromUnqualifiedId(Id);
1995 TemplateArgs = nullptr;
1996 }
1997}
1998
1999static void emitEmptyLookupTypoDiagnostic(
2000 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2001 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2002 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2003 DeclContext *Ctx =
2004 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2005 if (!TC) {
2006 // Emit a special diagnostic for failed member lookups.
2007 // FIXME: computing the declaration context might fail here (?)
2008 if (Ctx)
2009 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2010 << SS.getRange();
2011 else
2012 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2013 return;
2014 }
2015
2016 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2017 bool DroppedSpecifier =
2018 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2019 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2020 ? diag::note_implicit_param_decl
2021 : diag::note_previous_decl;
2022 if (!Ctx)
2023 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2024 SemaRef.PDiag(NoteID));
2025 else
2026 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2027 << Typo << Ctx << DroppedSpecifier
2028 << SS.getRange(),
2029 SemaRef.PDiag(NoteID));
2030}
2031
2032/// Diagnose an empty lookup.
2033///
2034/// \return false if new lookup candidates were found
2035bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2036 CorrectionCandidateCallback &CCC,
2037 TemplateArgumentListInfo *ExplicitTemplateArgs,
2038 ArrayRef<Expr *> Args, TypoExpr **Out) {
2039 DeclarationName Name = R.getLookupName();
2040
2041 unsigned diagnostic = diag::err_undeclared_var_use;
2042 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2043 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2044 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2045 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2046 diagnostic = diag::err_undeclared_use;
2047 diagnostic_suggest = diag::err_undeclared_use_suggest;
2048 }
2049
2050 // If the original lookup was an unqualified lookup, fake an
2051 // unqualified lookup. This is useful when (for example) the
2052 // original lookup would not have found something because it was a
2053 // dependent name.
2054 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2055 while (DC) {
2056 if (isa<CXXRecordDecl>(DC)) {
2057 LookupQualifiedName(R, DC);
2058
2059 if (!R.empty()) {
2060 // Don't give errors about ambiguities in this lookup.
2061 R.suppressDiagnostics();
2062
2063 // During a default argument instantiation the CurContext points
2064 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2065 // function parameter list, hence add an explicit check.
2066 bool isDefaultArgument =
2067 !CodeSynthesisContexts.empty() &&
2068 CodeSynthesisContexts.back().Kind ==
2069 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2070 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2071 bool isInstance = CurMethod &&
2072 CurMethod->isInstance() &&
2073 DC == CurMethod->getParent() && !isDefaultArgument;
2074
2075 // Give a code modification hint to insert 'this->'.
2076 // TODO: fixit for inserting 'Base<T>::' in the other cases.
2077 // Actually quite difficult!
2078 if (getLangOpts().MSVCCompat)
2079 diagnostic = diag::ext_found_via_dependent_bases_lookup;
2080 if (isInstance) {
2081 Diag(R.getNameLoc(), diagnostic) << Name
2082 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2083 CheckCXXThisCapture(R.getNameLoc());
2084 } else {
2085 Diag(R.getNameLoc(), diagnostic) << Name;
2086 }
2087
2088 // Do we really want to note all of these?
2089 for (NamedDecl *D : R)
2090 Diag(D->getLocation(), diag::note_dependent_var_use);
2091
2092 // Return true if we are inside a default argument instantiation
2093 // and the found name refers to an instance member function, otherwise
2094 // the function calling DiagnoseEmptyLookup will try to create an
2095 // implicit member call and this is wrong for default argument.
2096 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2097 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2098 return true;
2099 }
2100
2101 // Tell the callee to try to recover.
2102 return false;
2103 }
2104
2105 R.clear();
2106 }
2107
2108 DC = DC->getLookupParent();
2109 }
2110
2111 // We didn't find anything, so try to correct for a typo.
2112 TypoCorrection Corrected;
2113 if (S && Out) {
2114 SourceLocation TypoLoc = R.getNameLoc();
2115 assert(!ExplicitTemplateArgs &&((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!"
) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2116, __PRETTY_FUNCTION__))
2116 "Diagnosing an empty lookup with explicit template args!")((!ExplicitTemplateArgs && "Diagnosing an empty lookup with explicit template args!"
) ? static_cast<void> (0) : __assert_fail ("!ExplicitTemplateArgs && \"Diagnosing an empty lookup with explicit template args!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2116, __PRETTY_FUNCTION__))
;
2117 *Out = CorrectTypoDelayed(
2118 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2119 [=](const TypoCorrection &TC) {
2120 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2121 diagnostic, diagnostic_suggest);
2122 },
2123 nullptr, CTK_ErrorRecovery);
2124 if (*Out)
2125 return true;
2126 } else if (S &&
2127 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2128 S, &SS, CCC, CTK_ErrorRecovery))) {
2129 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2130 bool DroppedSpecifier =
2131 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2132 R.setLookupName(Corrected.getCorrection());
2133
2134 bool AcceptableWithRecovery = false;
2135 bool AcceptableWithoutRecovery = false;
2136 NamedDecl *ND = Corrected.getFoundDecl();
2137 if (ND) {
2138 if (Corrected.isOverloaded()) {
2139 OverloadCandidateSet OCS(R.getNameLoc(),
2140 OverloadCandidateSet::CSK_Normal);
2141 OverloadCandidateSet::iterator Best;
2142 for (NamedDecl *CD : Corrected) {
2143 if (FunctionTemplateDecl *FTD =
2144 dyn_cast<FunctionTemplateDecl>(CD))
2145 AddTemplateOverloadCandidate(
2146 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2147 Args, OCS);
2148 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2149 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2150 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2151 Args, OCS);
2152 }
2153 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2154 case OR_Success:
2155 ND = Best->FoundDecl;
2156 Corrected.setCorrectionDecl(ND);
2157 break;
2158 default:
2159 // FIXME: Arbitrarily pick the first declaration for the note.
2160 Corrected.setCorrectionDecl(ND);
2161 break;
2162 }
2163 }
2164 R.addDecl(ND);
2165 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2166 CXXRecordDecl *Record = nullptr;
2167 if (Corrected.getCorrectionSpecifier()) {
2168 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2169 Record = Ty->getAsCXXRecordDecl();
2170 }
2171 if (!Record)
2172 Record = cast<CXXRecordDecl>(
2173 ND->getDeclContext()->getRedeclContext());
2174 R.setNamingClass(Record);
2175 }
2176
2177 auto *UnderlyingND = ND->getUnderlyingDecl();
2178 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2179 isa<FunctionTemplateDecl>(UnderlyingND);
2180 // FIXME: If we ended up with a typo for a type name or
2181 // Objective-C class name, we're in trouble because the parser
2182 // is in the wrong place to recover. Suggest the typo
2183 // correction, but don't make it a fix-it since we're not going
2184 // to recover well anyway.
2185 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2186 getAsTypeTemplateDecl(UnderlyingND) ||
2187 isa<ObjCInterfaceDecl>(UnderlyingND);
2188 } else {
2189 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2190 // because we aren't able to recover.
2191 AcceptableWithoutRecovery = true;
2192 }
2193
2194 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2195 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2196 ? diag::note_implicit_param_decl
2197 : diag::note_previous_decl;
2198 if (SS.isEmpty())
2199 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2200 PDiag(NoteID), AcceptableWithRecovery);
2201 else
2202 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2203 << Name << computeDeclContext(SS, false)
2204 << DroppedSpecifier << SS.getRange(),
2205 PDiag(NoteID), AcceptableWithRecovery);
2206
2207 // Tell the callee whether to try to recover.
2208 return !AcceptableWithRecovery;
2209 }
2210 }
2211 R.clear();
2212
2213 // Emit a special diagnostic for failed member lookups.
2214 // FIXME: computing the declaration context might fail here (?)
2215 if (!SS.isEmpty()) {
2216 Diag(R.getNameLoc(), diag::err_no_member)
2217 << Name << computeDeclContext(SS, false)
2218 << SS.getRange();
2219 return true;
2220 }
2221
2222 // Give up, we can't recover.
2223 Diag(R.getNameLoc(), diagnostic) << Name;
2224 return true;
2225}
2226
2227/// In Microsoft mode, if we are inside a template class whose parent class has
2228/// dependent base classes, and we can't resolve an unqualified identifier, then
2229/// assume the identifier is a member of a dependent base class. We can only
2230/// recover successfully in static methods, instance methods, and other contexts
2231/// where 'this' is available. This doesn't precisely match MSVC's
2232/// instantiation model, but it's close enough.
2233static Expr *
2234recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2235 DeclarationNameInfo &NameInfo,
2236 SourceLocation TemplateKWLoc,
2237 const TemplateArgumentListInfo *TemplateArgs) {
2238 // Only try to recover from lookup into dependent bases in static methods or
2239 // contexts where 'this' is available.
2240 QualType ThisType = S.getCurrentThisType();
2241 const CXXRecordDecl *RD = nullptr;
2242 if (!ThisType.isNull())
2243 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2244 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2245 RD = MD->getParent();
2246 if (!RD || !RD->hasAnyDependentBases())
2247 return nullptr;
2248
2249 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2250 // is available, suggest inserting 'this->' as a fixit.
2251 SourceLocation Loc = NameInfo.getLoc();
2252 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2253 DB << NameInfo.getName() << RD;
2254
2255 if (!ThisType.isNull()) {
2256 DB << FixItHint::CreateInsertion(Loc, "this->");
2257 return CXXDependentScopeMemberExpr::Create(
2258 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2259 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2260 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2261 }
2262
2263 // Synthesize a fake NNS that points to the derived class. This will
2264 // perform name lookup during template instantiation.
2265 CXXScopeSpec SS;
2266 auto *NNS =
2267 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2268 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2269 return DependentScopeDeclRefExpr::Create(
2270 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2271 TemplateArgs);
2272}
2273
2274ExprResult
2275Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2276 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2277 bool HasTrailingLParen, bool IsAddressOfOperand,
2278 CorrectionCandidateCallback *CCC,
2279 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2280 assert(!(IsAddressOfOperand && HasTrailingLParen) &&((!(IsAddressOfOperand && HasTrailingLParen) &&
"cannot be direct & operand and have a trailing lparen")
? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2281, __PRETTY_FUNCTION__))
2281 "cannot be direct & operand and have a trailing lparen")((!(IsAddressOfOperand && HasTrailingLParen) &&
"cannot be direct & operand and have a trailing lparen")
? static_cast<void> (0) : __assert_fail ("!(IsAddressOfOperand && HasTrailingLParen) && \"cannot be direct & operand and have a trailing lparen\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2281, __PRETTY_FUNCTION__))
;
2282 if (SS.isInvalid())
2283 return ExprError();
2284
2285 TemplateArgumentListInfo TemplateArgsBuffer;
2286
2287 // Decompose the UnqualifiedId into the following data.
2288 DeclarationNameInfo NameInfo;
2289 const TemplateArgumentListInfo *TemplateArgs;
2290 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2291
2292 DeclarationName Name = NameInfo.getName();
2293 IdentifierInfo *II = Name.getAsIdentifierInfo();
2294 SourceLocation NameLoc = NameInfo.getLoc();
2295
2296 if (II && II->isEditorPlaceholder()) {
2297 // FIXME: When typed placeholders are supported we can create a typed
2298 // placeholder expression node.
2299 return ExprError();
2300 }
2301
2302 // C++ [temp.dep.expr]p3:
2303 // An id-expression is type-dependent if it contains:
2304 // -- an identifier that was declared with a dependent type,
2305 // (note: handled after lookup)
2306 // -- a template-id that is dependent,
2307 // (note: handled in BuildTemplateIdExpr)
2308 // -- a conversion-function-id that specifies a dependent type,
2309 // -- a nested-name-specifier that contains a class-name that
2310 // names a dependent type.
2311 // Determine whether this is a member of an unknown specialization;
2312 // we need to handle these differently.
2313 bool DependentID = false;
2314 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2315 Name.getCXXNameType()->isDependentType()) {
2316 DependentID = true;
2317 } else if (SS.isSet()) {
2318 if (DeclContext *DC = computeDeclContext(SS, false)) {
2319 if (RequireCompleteDeclContext(SS, DC))
2320 return ExprError();
2321 } else {
2322 DependentID = true;
2323 }
2324 }
2325
2326 if (DependentID)
2327 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2328 IsAddressOfOperand, TemplateArgs);
2329
2330 // Perform the required lookup.
2331 LookupResult R(*this, NameInfo,
2332 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2333 ? LookupObjCImplicitSelfParam
2334 : LookupOrdinaryName);
2335 if (TemplateKWLoc.isValid() || TemplateArgs) {
2336 // Lookup the template name again to correctly establish the context in
2337 // which it was found. This is really unfortunate as we already did the
2338 // lookup to determine that it was a template name in the first place. If
2339 // this becomes a performance hit, we can work harder to preserve those
2340 // results until we get here but it's likely not worth it.
2341 bool MemberOfUnknownSpecialization;
2342 AssumedTemplateKind AssumedTemplate;
2343 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2344 MemberOfUnknownSpecialization, TemplateKWLoc,
2345 &AssumedTemplate))
2346 return ExprError();
2347
2348 if (MemberOfUnknownSpecialization ||
2349 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2350 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2351 IsAddressOfOperand, TemplateArgs);
2352 } else {
2353 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2354 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2355
2356 // If the result might be in a dependent base class, this is a dependent
2357 // id-expression.
2358 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2359 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2360 IsAddressOfOperand, TemplateArgs);
2361
2362 // If this reference is in an Objective-C method, then we need to do
2363 // some special Objective-C lookup, too.
2364 if (IvarLookupFollowUp) {
2365 ExprResult E(LookupInObjCMethod(R, S, II, true));
2366 if (E.isInvalid())
2367 return ExprError();
2368
2369 if (Expr *Ex = E.getAs<Expr>())
2370 return Ex;
2371 }
2372 }
2373
2374 if (R.isAmbiguous())
2375 return ExprError();
2376
2377 // This could be an implicitly declared function reference (legal in C90,
2378 // extension in C99, forbidden in C++).
2379 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2380 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2381 if (D) R.addDecl(D);
2382 }
2383
2384 // Determine whether this name might be a candidate for
2385 // argument-dependent lookup.
2386 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2387
2388 if (R.empty() && !ADL) {
2389 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2390 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2391 TemplateKWLoc, TemplateArgs))
2392 return E;
2393 }
2394
2395 // Don't diagnose an empty lookup for inline assembly.
2396 if (IsInlineAsmIdentifier)
2397 return ExprError();
2398
2399 // If this name wasn't predeclared and if this is not a function
2400 // call, diagnose the problem.
2401 TypoExpr *TE = nullptr;
2402 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2403 : nullptr);
2404 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2405 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
"Typo correction callback misconfigured") ? static_cast<void
> (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2406, __PRETTY_FUNCTION__))
2406 "Typo correction callback misconfigured")(((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
"Typo correction callback misconfigured") ? static_cast<void
> (0) : __assert_fail ("(!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) && \"Typo correction callback misconfigured\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2406, __PRETTY_FUNCTION__))
;
2407 if (CCC) {
2408 // Make sure the callback knows what the typo being diagnosed is.
2409 CCC->setTypoName(II);
2410 if (SS.isValid())
2411 CCC->setTypoNNS(SS.getScopeRep());
2412 }
2413 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2414 // a template name, but we happen to have always already looked up the name
2415 // before we get here if it must be a template name.
2416 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2417 None, &TE)) {
2418 if (TE && KeywordReplacement) {
2419 auto &State = getTypoExprState(TE);
2420 auto BestTC = State.Consumer->getNextCorrection();
2421 if (BestTC.isKeyword()) {
2422 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2423 if (State.DiagHandler)
2424 State.DiagHandler(BestTC);
2425 KeywordReplacement->startToken();
2426 KeywordReplacement->setKind(II->getTokenID());
2427 KeywordReplacement->setIdentifierInfo(II);
2428 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2429 // Clean up the state associated with the TypoExpr, since it has
2430 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2431 clearDelayedTypo(TE);
2432 // Signal that a correction to a keyword was performed by returning a
2433 // valid-but-null ExprResult.
2434 return (Expr*)nullptr;
2435 }
2436 State.Consumer->resetCorrectionStream();
2437 }
2438 return TE ? TE : ExprError();
2439 }
2440
2441 assert(!R.empty() &&((!R.empty() && "DiagnoseEmptyLookup returned false but added no results"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2442, __PRETTY_FUNCTION__))
2442 "DiagnoseEmptyLookup returned false but added no results")((!R.empty() && "DiagnoseEmptyLookup returned false but added no results"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"DiagnoseEmptyLookup returned false but added no results\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2442, __PRETTY_FUNCTION__))
;
2443
2444 // If we found an Objective-C instance variable, let
2445 // LookupInObjCMethod build the appropriate expression to
2446 // reference the ivar.
2447 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2448 R.clear();
2449 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2450 // In a hopelessly buggy code, Objective-C instance variable
2451 // lookup fails and no expression will be built to reference it.
2452 if (!E.isInvalid() && !E.get())
2453 return ExprError();
2454 return E;
2455 }
2456 }
2457
2458 // This is guaranteed from this point on.
2459 assert(!R.empty() || ADL)((!R.empty() || ADL) ? static_cast<void> (0) : __assert_fail
("!R.empty() || ADL", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2459, __PRETTY_FUNCTION__))
;
2460
2461 // Check whether this might be a C++ implicit instance member access.
2462 // C++ [class.mfct.non-static]p3:
2463 // When an id-expression that is not part of a class member access
2464 // syntax and not used to form a pointer to member is used in the
2465 // body of a non-static member function of class X, if name lookup
2466 // resolves the name in the id-expression to a non-static non-type
2467 // member of some class C, the id-expression is transformed into a
2468 // class member access expression using (*this) as the
2469 // postfix-expression to the left of the . operator.
2470 //
2471 // But we don't actually need to do this for '&' operands if R
2472 // resolved to a function or overloaded function set, because the
2473 // expression is ill-formed if it actually works out to be a
2474 // non-static member function:
2475 //
2476 // C++ [expr.ref]p4:
2477 // Otherwise, if E1.E2 refers to a non-static member function. . .
2478 // [t]he expression can be used only as the left-hand operand of a
2479 // member function call.
2480 //
2481 // There are other safeguards against such uses, but it's important
2482 // to get this right here so that we don't end up making a
2483 // spuriously dependent expression if we're inside a dependent
2484 // instance method.
2485 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2486 bool MightBeImplicitMember;
2487 if (!IsAddressOfOperand)
2488 MightBeImplicitMember = true;
2489 else if (!SS.isEmpty())
2490 MightBeImplicitMember = false;
2491 else if (R.isOverloadedResult())
2492 MightBeImplicitMember = false;
2493 else if (R.isUnresolvableResult())
2494 MightBeImplicitMember = true;
2495 else
2496 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2497 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2498 isa<MSPropertyDecl>(R.getFoundDecl());
2499
2500 if (MightBeImplicitMember)
2501 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2502 R, TemplateArgs, S);
2503 }
2504
2505 if (TemplateArgs || TemplateKWLoc.isValid()) {
2506
2507 // In C++1y, if this is a variable template id, then check it
2508 // in BuildTemplateIdExpr().
2509 // The single lookup result must be a variable template declaration.
2510 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2511 Id.TemplateId->Kind == TNK_Var_template) {
2512 assert(R.getAsSingle<VarTemplateDecl>() &&((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found."
) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2513, __PRETTY_FUNCTION__))
2513 "There should only be one declaration found.")((R.getAsSingle<VarTemplateDecl>() && "There should only be one declaration found."
) ? static_cast<void> (0) : __assert_fail ("R.getAsSingle<VarTemplateDecl>() && \"There should only be one declaration found.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2513, __PRETTY_FUNCTION__))
;
2514 }
2515
2516 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2517 }
2518
2519 return BuildDeclarationNameExpr(SS, R, ADL);
2520}
2521
2522/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2523/// declaration name, generally during template instantiation.
2524/// There's a large number of things which don't need to be done along
2525/// this path.
2526ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2527 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2528 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2529 DeclContext *DC = computeDeclContext(SS, false);
2530 if (!DC)
2531 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2532 NameInfo, /*TemplateArgs=*/nullptr);
2533
2534 if (RequireCompleteDeclContext(SS, DC))
2535 return ExprError();
2536
2537 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2538 LookupQualifiedName(R, DC);
2539
2540 if (R.isAmbiguous())
2541 return ExprError();
2542
2543 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2544 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2545 NameInfo, /*TemplateArgs=*/nullptr);
2546
2547 if (R.empty()) {
2548 Diag(NameInfo.getLoc(), diag::err_no_member)
2549 << NameInfo.getName() << DC << SS.getRange();
2550 return ExprError();
2551 }
2552
2553 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2554 // Diagnose a missing typename if this resolved unambiguously to a type in
2555 // a dependent context. If we can recover with a type, downgrade this to
2556 // a warning in Microsoft compatibility mode.
2557 unsigned DiagID = diag::err_typename_missing;
2558 if (RecoveryTSI && getLangOpts().MSVCCompat)
2559 DiagID = diag::ext_typename_missing;
2560 SourceLocation Loc = SS.getBeginLoc();
2561 auto D = Diag(Loc, DiagID);
2562 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2563 << SourceRange(Loc, NameInfo.getEndLoc());
2564
2565 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2566 // context.
2567 if (!RecoveryTSI)
2568 return ExprError();
2569
2570 // Only issue the fixit if we're prepared to recover.
2571 D << FixItHint::CreateInsertion(Loc, "typename ");
2572
2573 // Recover by pretending this was an elaborated type.
2574 QualType Ty = Context.getTypeDeclType(TD);
2575 TypeLocBuilder TLB;
2576 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2577
2578 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2579 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2580 QTL.setElaboratedKeywordLoc(SourceLocation());
2581 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2582
2583 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2584
2585 return ExprEmpty();
2586 }
2587
2588 // Defend against this resolving to an implicit member access. We usually
2589 // won't get here if this might be a legitimate a class member (we end up in
2590 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2591 // a pointer-to-member or in an unevaluated context in C++11.
2592 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2593 return BuildPossibleImplicitMemberExpr(SS,
2594 /*TemplateKWLoc=*/SourceLocation(),
2595 R, /*TemplateArgs=*/nullptr, S);
2596
2597 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2598}
2599
2600/// The parser has read a name in, and Sema has detected that we're currently
2601/// inside an ObjC method. Perform some additional checks and determine if we
2602/// should form a reference to an ivar.
2603///
2604/// Ideally, most of this would be done by lookup, but there's
2605/// actually quite a lot of extra work involved.
2606DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2607 IdentifierInfo *II) {
2608 SourceLocation Loc = Lookup.getNameLoc();
2609 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2610
2611 // Check for error condition which is already reported.
2612 if (!CurMethod)
2613 return DeclResult(true);
2614
2615 // There are two cases to handle here. 1) scoped lookup could have failed,
2616 // in which case we should look for an ivar. 2) scoped lookup could have
2617 // found a decl, but that decl is outside the current instance method (i.e.
2618 // a global variable). In these two cases, we do a lookup for an ivar with
2619 // this name, if the lookup sucedes, we replace it our current decl.
2620
2621 // If we're in a class method, we don't normally want to look for
2622 // ivars. But if we don't find anything else, and there's an
2623 // ivar, that's an error.
2624 bool IsClassMethod = CurMethod->isClassMethod();
2625
2626 bool LookForIvars;
2627 if (Lookup.empty())
2628 LookForIvars = true;
2629 else if (IsClassMethod)
2630 LookForIvars = false;
2631 else
2632 LookForIvars = (Lookup.isSingleResult() &&
2633 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2634 ObjCInterfaceDecl *IFace = nullptr;
2635 if (LookForIvars) {
2636 IFace = CurMethod->getClassInterface();
2637 ObjCInterfaceDecl *ClassDeclared;
2638 ObjCIvarDecl *IV = nullptr;
2639 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2640 // Diagnose using an ivar in a class method.
2641 if (IsClassMethod) {
2642 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2643 return DeclResult(true);
2644 }
2645
2646 // Diagnose the use of an ivar outside of the declaring class.
2647 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2648 !declaresSameEntity(ClassDeclared, IFace) &&
2649 !getLangOpts().DebuggerSupport)
2650 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2651
2652 // Success.
2653 return IV;
2654 }
2655 } else if (CurMethod->isInstanceMethod()) {
2656 // We should warn if a local variable hides an ivar.
2657 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2658 ObjCInterfaceDecl *ClassDeclared;
2659 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2660 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2661 declaresSameEntity(IFace, ClassDeclared))
2662 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2663 }
2664 }
2665 } else if (Lookup.isSingleResult() &&
2666 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2667 // If accessing a stand-alone ivar in a class method, this is an error.
2668 if (const ObjCIvarDecl *IV =
2669 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2670 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2671 return DeclResult(true);
2672 }
2673 }
2674
2675 // Didn't encounter an error, didn't find an ivar.
2676 return DeclResult(false);
2677}
2678
2679ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2680 ObjCIvarDecl *IV) {
2681 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2682 assert(CurMethod && CurMethod->isInstanceMethod() &&((CurMethod && CurMethod->isInstanceMethod() &&
"should not reference ivar from this context") ? static_cast
<void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2683, __PRETTY_FUNCTION__))
2683 "should not reference ivar from this context")((CurMethod && CurMethod->isInstanceMethod() &&
"should not reference ivar from this context") ? static_cast
<void> (0) : __assert_fail ("CurMethod && CurMethod->isInstanceMethod() && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2683, __PRETTY_FUNCTION__))
;
2684
2685 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2686 assert(IFace && "should not reference ivar from this context")((IFace && "should not reference ivar from this context"
) ? static_cast<void> (0) : __assert_fail ("IFace && \"should not reference ivar from this context\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2686, __PRETTY_FUNCTION__))
;
2687
2688 // If we're referencing an invalid decl, just return this as a silent
2689 // error node. The error diagnostic was already emitted on the decl.
2690 if (IV->isInvalidDecl())
2691 return ExprError();
2692
2693 // Check if referencing a field with __attribute__((deprecated)).
2694 if (DiagnoseUseOfDecl(IV, Loc))
2695 return ExprError();
2696
2697 // FIXME: This should use a new expr for a direct reference, don't
2698 // turn this into Self->ivar, just return a BareIVarExpr or something.
2699 IdentifierInfo &II = Context.Idents.get("self");
2700 UnqualifiedId SelfName;
2701 SelfName.setIdentifier(&II, SourceLocation());
2702 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2703 CXXScopeSpec SelfScopeSpec;
2704 SourceLocation TemplateKWLoc;
2705 ExprResult SelfExpr =
2706 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2707 /*HasTrailingLParen=*/false,
2708 /*IsAddressOfOperand=*/false);
2709 if (SelfExpr.isInvalid())
2710 return ExprError();
2711
2712 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2713 if (SelfExpr.isInvalid())
2714 return ExprError();
2715
2716 MarkAnyDeclReferenced(Loc, IV, true);
2717
2718 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2719 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2720 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2721 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2722
2723 ObjCIvarRefExpr *Result = new (Context)
2724 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2725 IV->getLocation(), SelfExpr.get(), true, true);
2726
2727 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2728 if (!isUnevaluatedContext() &&
2729 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2730 getCurFunction()->recordUseOfWeak(Result);
2731 }
2732 if (getLangOpts().ObjCAutoRefCount)
2733 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2734 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2735
2736 return Result;
2737}
2738
2739/// The parser has read a name in, and Sema has detected that we're currently
2740/// inside an ObjC method. Perform some additional checks and determine if we
2741/// should form a reference to an ivar. If so, build an expression referencing
2742/// that ivar.
2743ExprResult
2744Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2745 IdentifierInfo *II, bool AllowBuiltinCreation) {
2746 // FIXME: Integrate this lookup step into LookupParsedName.
2747 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2748 if (Ivar.isInvalid())
2749 return ExprError();
2750 if (Ivar.isUsable())
2751 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2752 cast<ObjCIvarDecl>(Ivar.get()));
2753
2754 if (Lookup.empty() && II && AllowBuiltinCreation)
2755 LookupBuiltin(Lookup);
2756
2757 // Sentinel value saying that we didn't do anything special.
2758 return ExprResult(false);
2759}
2760
2761/// Cast a base object to a member's actual type.
2762///
2763/// Logically this happens in three phases:
2764///
2765/// * First we cast from the base type to the naming class.
2766/// The naming class is the class into which we were looking
2767/// when we found the member; it's the qualifier type if a
2768/// qualifier was provided, and otherwise it's the base type.
2769///
2770/// * Next we cast from the naming class to the declaring class.
2771/// If the member we found was brought into a class's scope by
2772/// a using declaration, this is that class; otherwise it's
2773/// the class declaring the member.
2774///
2775/// * Finally we cast from the declaring class to the "true"
2776/// declaring class of the member. This conversion does not
2777/// obey access control.
2778ExprResult
2779Sema::PerformObjectMemberConversion(Expr *From,
2780 NestedNameSpecifier *Qualifier,
2781 NamedDecl *FoundDecl,
2782 NamedDecl *Member) {
2783 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2784 if (!RD)
2785 return From;
2786
2787 QualType DestRecordType;
2788 QualType DestType;
2789 QualType FromRecordType;
2790 QualType FromType = From->getType();
2791 bool PointerConversions = false;
2792 if (isa<FieldDecl>(Member)) {
2793 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2794 auto FromPtrType = FromType->getAs<PointerType>();
2795 DestRecordType = Context.getAddrSpaceQualType(
2796 DestRecordType, FromPtrType
2797 ? FromType->getPointeeType().getAddressSpace()
2798 : FromType.getAddressSpace());
2799
2800 if (FromPtrType) {
2801 DestType = Context.getPointerType(DestRecordType);
2802 FromRecordType = FromPtrType->getPointeeType();
2803 PointerConversions = true;
2804 } else {
2805 DestType = DestRecordType;
2806 FromRecordType = FromType;
2807 }
2808 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2809 if (Method->isStatic())
2810 return From;
2811
2812 DestType = Method->getThisType();
2813 DestRecordType = DestType->getPointeeType();
2814
2815 if (FromType->getAs<PointerType>()) {
2816 FromRecordType = FromType->getPointeeType();
2817 PointerConversions = true;
2818 } else {
2819 FromRecordType = FromType;
2820 DestType = DestRecordType;
2821 }
2822
2823 LangAS FromAS = FromRecordType.getAddressSpace();
2824 LangAS DestAS = DestRecordType.getAddressSpace();
2825 if (FromAS != DestAS) {
2826 QualType FromRecordTypeWithoutAS =
2827 Context.removeAddrSpaceQualType(FromRecordType);
2828 QualType FromTypeWithDestAS =
2829 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2830 if (PointerConversions)
2831 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2832 From = ImpCastExprToType(From, FromTypeWithDestAS,
2833 CK_AddressSpaceConversion, From->getValueKind())
2834 .get();
2835 }
2836 } else {
2837 // No conversion necessary.
2838 return From;
2839 }
2840
2841 if (DestType->isDependentType() || FromType->isDependentType())
2842 return From;
2843
2844 // If the unqualified types are the same, no conversion is necessary.
2845 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2846 return From;
2847
2848 SourceRange FromRange = From->getSourceRange();
2849 SourceLocation FromLoc = FromRange.getBegin();
2850
2851 ExprValueKind VK = From->getValueKind();
2852
2853 // C++ [class.member.lookup]p8:
2854 // [...] Ambiguities can often be resolved by qualifying a name with its
2855 // class name.
2856 //
2857 // If the member was a qualified name and the qualified referred to a
2858 // specific base subobject type, we'll cast to that intermediate type
2859 // first and then to the object in which the member is declared. That allows
2860 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2861 //
2862 // class Base { public: int x; };
2863 // class Derived1 : public Base { };
2864 // class Derived2 : public Base { };
2865 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2866 //
2867 // void VeryDerived::f() {
2868 // x = 17; // error: ambiguous base subobjects
2869 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2870 // }
2871 if (Qualifier && Qualifier->getAsType()) {
2872 QualType QType = QualType(Qualifier->getAsType(), 0);
2873 assert(QType->isRecordType() && "lookup done with non-record type")((QType->isRecordType() && "lookup done with non-record type"
) ? static_cast<void> (0) : __assert_fail ("QType->isRecordType() && \"lookup done with non-record type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2873, __PRETTY_FUNCTION__))
;
2874
2875 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2876
2877 // In C++98, the qualifier type doesn't actually have to be a base
2878 // type of the object type, in which case we just ignore it.
2879 // Otherwise build the appropriate casts.
2880 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2881 CXXCastPath BasePath;
2882 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2883 FromLoc, FromRange, &BasePath))
2884 return ExprError();
2885
2886 if (PointerConversions)
2887 QType = Context.getPointerType(QType);
2888 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2889 VK, &BasePath).get();
2890
2891 FromType = QType;
2892 FromRecordType = QRecordType;
2893
2894 // If the qualifier type was the same as the destination type,
2895 // we're done.
2896 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2897 return From;
2898 }
2899 }
2900
2901 bool IgnoreAccess = false;
2902
2903 // If we actually found the member through a using declaration, cast
2904 // down to the using declaration's type.
2905 //
2906 // Pointer equality is fine here because only one declaration of a
2907 // class ever has member declarations.
2908 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2909 assert(isa<UsingShadowDecl>(FoundDecl))((isa<UsingShadowDecl>(FoundDecl)) ? static_cast<void
> (0) : __assert_fail ("isa<UsingShadowDecl>(FoundDecl)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2909, __PRETTY_FUNCTION__))
;
2910 QualType URecordType = Context.getTypeDeclType(
2911 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2912
2913 // We only need to do this if the naming-class to declaring-class
2914 // conversion is non-trivial.
2915 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2916 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType))((IsDerivedFrom(FromLoc, FromRecordType, URecordType)) ? static_cast
<void> (0) : __assert_fail ("IsDerivedFrom(FromLoc, FromRecordType, URecordType)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 2916, __PRETTY_FUNCTION__))
;
2917 CXXCastPath BasePath;
2918 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2919 FromLoc, FromRange, &BasePath))
2920 return ExprError();
2921
2922 QualType UType = URecordType;
2923 if (PointerConversions)
2924 UType = Context.getPointerType(UType);
2925 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2926 VK, &BasePath).get();
2927 FromType = UType;
2928 FromRecordType = URecordType;
2929 }
2930
2931 // We don't do access control for the conversion from the
2932 // declaring class to the true declaring class.
2933 IgnoreAccess = true;
2934 }
2935
2936 CXXCastPath BasePath;
2937 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2938 FromLoc, FromRange, &BasePath,
2939 IgnoreAccess))
2940 return ExprError();
2941
2942 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2943 VK, &BasePath);
2944}
2945
2946bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2947 const LookupResult &R,
2948 bool HasTrailingLParen) {
2949 // Only when used directly as the postfix-expression of a call.
2950 if (!HasTrailingLParen)
2951 return false;
2952
2953 // Never if a scope specifier was provided.
2954 if (SS.isSet())
2955 return false;
2956
2957 // Only in C++ or ObjC++.
2958 if (!getLangOpts().CPlusPlus)
2959 return false;
2960
2961 // Turn off ADL when we find certain kinds of declarations during
2962 // normal lookup:
2963 for (NamedDecl *D : R) {
2964 // C++0x [basic.lookup.argdep]p3:
2965 // -- a declaration of a class member
2966 // Since using decls preserve this property, we check this on the
2967 // original decl.
2968 if (D->isCXXClassMember())
2969 return false;
2970
2971 // C++0x [basic.lookup.argdep]p3:
2972 // -- a block-scope function declaration that is not a
2973 // using-declaration
2974 // NOTE: we also trigger this for function templates (in fact, we
2975 // don't check the decl type at all, since all other decl types
2976 // turn off ADL anyway).
2977 if (isa<UsingShadowDecl>(D))
2978 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2979 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2980 return false;
2981
2982 // C++0x [basic.lookup.argdep]p3:
2983 // -- a declaration that is neither a function or a function
2984 // template
2985 // And also for builtin functions.
2986 if (isa<FunctionDecl>(D)) {
2987 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2988
2989 // But also builtin functions.
2990 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2991 return false;
2992 } else if (!isa<FunctionTemplateDecl>(D))
2993 return false;
2994 }
2995
2996 return true;
2997}
2998
2999
3000/// Diagnoses obvious problems with the use of the given declaration
3001/// as an expression. This is only actually called for lookups that
3002/// were not overloaded, and it doesn't promise that the declaration
3003/// will in fact be used.
3004static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3005 if (D->isInvalidDecl())
3006 return true;
3007
3008 if (isa<TypedefNameDecl>(D)) {
3009 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3010 return true;
3011 }
3012
3013 if (isa<ObjCInterfaceDecl>(D)) {
3014 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3015 return true;
3016 }
3017
3018 if (isa<NamespaceDecl>(D)) {
3019 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3020 return true;
3021 }
3022
3023 return false;
3024}
3025
3026// Certain multiversion types should be treated as overloaded even when there is
3027// only one result.
3028static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3029 assert(R.isSingleResult() && "Expected only a single result")((R.isSingleResult() && "Expected only a single result"
) ? static_cast<void> (0) : __assert_fail ("R.isSingleResult() && \"Expected only a single result\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3029, __PRETTY_FUNCTION__))
;
3030 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3031 return FD &&
3032 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3033}
3034
3035ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3036 LookupResult &R, bool NeedsADL,
3037 bool AcceptInvalidDecl) {
3038 // If this is a single, fully-resolved result and we don't need ADL,
3039 // just build an ordinary singleton decl ref.
3040 if (!NeedsADL && R.isSingleResult() &&
3041 !R.getAsSingle<FunctionTemplateDecl>() &&
3042 !ShouldLookupResultBeMultiVersionOverload(R))
3043 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3044 R.getRepresentativeDecl(), nullptr,
3045 AcceptInvalidDecl);
3046
3047 // We only need to check the declaration if there's exactly one
3048 // result, because in the overloaded case the results can only be
3049 // functions and function templates.
3050 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3051 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3052 return ExprError();
3053
3054 // Otherwise, just build an unresolved lookup expression. Suppress
3055 // any lookup-related diagnostics; we'll hash these out later, when
3056 // we've picked a target.
3057 R.suppressDiagnostics();
3058
3059 UnresolvedLookupExpr *ULE
3060 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3061 SS.getWithLocInContext(Context),
3062 R.getLookupNameInfo(),
3063 NeedsADL, R.isOverloadedResult(),
3064 R.begin(), R.end());
3065
3066 return ULE;
3067}
3068
3069static void
3070diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3071 ValueDecl *var, DeclContext *DC);
3072
3073/// Complete semantic analysis for a reference to the given declaration.
3074ExprResult Sema::BuildDeclarationNameExpr(
3075 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3076 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3077 bool AcceptInvalidDecl) {
3078 assert(D && "Cannot refer to a NULL declaration")((D && "Cannot refer to a NULL declaration") ? static_cast
<void> (0) : __assert_fail ("D && \"Cannot refer to a NULL declaration\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3078, __PRETTY_FUNCTION__))
;
3079 assert(!isa<FunctionTemplateDecl>(D) &&((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template"
) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3080, __PRETTY_FUNCTION__))
3080 "Cannot refer unambiguously to a function template")((!isa<FunctionTemplateDecl>(D) && "Cannot refer unambiguously to a function template"
) ? static_cast<void> (0) : __assert_fail ("!isa<FunctionTemplateDecl>(D) && \"Cannot refer unambiguously to a function template\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3080, __PRETTY_FUNCTION__))
;
3081
3082 SourceLocation Loc = NameInfo.getLoc();
3083 if (CheckDeclInExpr(*this, Loc, D))
3084 return ExprError();
3085
3086 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3087 // Specifically diagnose references to class templates that are missing
3088 // a template argument list.
3089 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3090 return ExprError();
3091 }
3092
3093 // Make sure that we're referring to a value.
3094 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3095 if (!VD) {
3096 Diag(Loc, diag::err_ref_non_value)
3097 << D << SS.getRange();
3098 Diag(D->getLocation(), diag::note_declared_at);
3099 return ExprError();
3100 }
3101
3102 // Check whether this declaration can be used. Note that we suppress
3103 // this check when we're going to perform argument-dependent lookup
3104 // on this function name, because this might not be the function
3105 // that overload resolution actually selects.
3106 if (DiagnoseUseOfDecl(VD, Loc))
3107 return ExprError();
3108
3109 // Only create DeclRefExpr's for valid Decl's.
3110 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3111 return ExprError();
3112
3113 // Handle members of anonymous structs and unions. If we got here,
3114 // and the reference is to a class member indirect field, then this
3115 // must be the subject of a pointer-to-member expression.
3116 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3117 if (!indirectField->isCXXClassMember())
3118 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3119 indirectField);
3120
3121 {
3122 QualType type = VD->getType();
3123 if (type.isNull())
3124 return ExprError();
3125 ExprValueKind valueKind = VK_RValue;
3126
3127 switch (D->getKind()) {
3128 // Ignore all the non-ValueDecl kinds.
3129#define ABSTRACT_DECL(kind)
3130#define VALUE(type, base)
3131#define DECL(type, base) \
3132 case Decl::type:
3133#include "clang/AST/DeclNodes.inc"
3134 llvm_unreachable("invalid value decl kind")::llvm::llvm_unreachable_internal("invalid value decl kind", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3134)
;
3135
3136 // These shouldn't make it here.
3137 case Decl::ObjCAtDefsField:
3138 llvm_unreachable("forming non-member reference to ivar?")::llvm::llvm_unreachable_internal("forming non-member reference to ivar?"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3138)
;
3139
3140 // Enum constants are always r-values and never references.
3141 // Unresolved using declarations are dependent.
3142 case Decl::EnumConstant:
3143 case Decl::UnresolvedUsingValue:
3144 case Decl::OMPDeclareReduction:
3145 case Decl::OMPDeclareMapper:
3146 valueKind = VK_RValue;
3147 break;
3148
3149 // Fields and indirect fields that got here must be for
3150 // pointer-to-member expressions; we just call them l-values for
3151 // internal consistency, because this subexpression doesn't really
3152 // exist in the high-level semantics.
3153 case Decl::Field:
3154 case Decl::IndirectField:
3155 case Decl::ObjCIvar:
3156 assert(getLangOpts().CPlusPlus &&((getLangOpts().CPlusPlus && "building reference to field in C?"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3157, __PRETTY_FUNCTION__))
3157 "building reference to field in C?")((getLangOpts().CPlusPlus && "building reference to field in C?"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"building reference to field in C?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3157, __PRETTY_FUNCTION__))
;
3158
3159 // These can't have reference type in well-formed programs, but
3160 // for internal consistency we do this anyway.
3161 type = type.getNonReferenceType();
3162 valueKind = VK_LValue;
3163 break;
3164
3165 // Non-type template parameters are either l-values or r-values
3166 // depending on the type.
3167 case Decl::NonTypeTemplateParm: {
3168 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3169 type = reftype->getPointeeType();
3170 valueKind = VK_LValue; // even if the parameter is an r-value reference
3171 break;
3172 }
3173
3174 // For non-references, we need to strip qualifiers just in case
3175 // the template parameter was declared as 'const int' or whatever.
3176 valueKind = VK_RValue;
3177 type = type.getUnqualifiedType();
3178 break;
3179 }
3180
3181 case Decl::Var:
3182 case Decl::VarTemplateSpecialization:
3183 case Decl::VarTemplatePartialSpecialization:
3184 case Decl::Decomposition:
3185 case Decl::OMPCapturedExpr:
3186 // In C, "extern void blah;" is valid and is an r-value.
3187 if (!getLangOpts().CPlusPlus &&
3188 !type.hasQualifiers() &&
3189 type->isVoidType()) {
3190 valueKind = VK_RValue;
3191 break;
3192 }
3193 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3194
3195 case Decl::ImplicitParam:
3196 case Decl::ParmVar: {
3197 // These are always l-values.
3198 valueKind = VK_LValue;
3199 type = type.getNonReferenceType();
3200
3201 // FIXME: Does the addition of const really only apply in
3202 // potentially-evaluated contexts? Since the variable isn't actually
3203 // captured in an unevaluated context, it seems that the answer is no.
3204 if (!isUnevaluatedContext()) {
3205 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3206 if (!CapturedType.isNull())
3207 type = CapturedType;
3208 }
3209
3210 break;
3211 }
3212
3213 case Decl::Binding: {
3214 // These are always lvalues.
3215 valueKind = VK_LValue;
3216 type = type.getNonReferenceType();
3217 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3218 // decides how that's supposed to work.
3219 auto *BD = cast<BindingDecl>(VD);
3220 if (BD->getDeclContext() != CurContext) {
3221 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3222 if (DD && DD->hasLocalStorage())
3223 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3224 }
3225 break;
3226 }
3227
3228 case Decl::Function: {
3229 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3230 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3231 type = Context.BuiltinFnTy;
3232 valueKind = VK_RValue;
3233 break;
3234 }
3235 }
3236
3237 const FunctionType *fty = type->castAs<FunctionType>();
3238
3239 // If we're referring to a function with an __unknown_anytype
3240 // result type, make the entire expression __unknown_anytype.
3241 if (fty->getReturnType() == Context.UnknownAnyTy) {
3242 type = Context.UnknownAnyTy;
3243 valueKind = VK_RValue;
3244 break;
3245 }
3246
3247 // Functions are l-values in C++.
3248 if (getLangOpts().CPlusPlus) {
3249 valueKind = VK_LValue;
3250 break;
3251 }
3252
3253 // C99 DR 316 says that, if a function type comes from a
3254 // function definition (without a prototype), that type is only
3255 // used for checking compatibility. Therefore, when referencing
3256 // the function, we pretend that we don't have the full function
3257 // type.
3258 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3259 isa<FunctionProtoType>(fty))
3260 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3261 fty->getExtInfo());
3262
3263 // Functions are r-values in C.
3264 valueKind = VK_RValue;
3265 break;
3266 }
3267
3268 case Decl::CXXDeductionGuide:
3269 llvm_unreachable("building reference to deduction guide")::llvm::llvm_unreachable_internal("building reference to deduction guide"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3269)
;
3270
3271 case Decl::MSProperty:
3272 valueKind = VK_LValue;
3273 break;
3274
3275 case Decl::CXXMethod:
3276 // If we're referring to a method with an __unknown_anytype
3277 // result type, make the entire expression __unknown_anytype.
3278 // This should only be possible with a type written directly.
3279 if (const FunctionProtoType *proto
3280 = dyn_cast<FunctionProtoType>(VD->getType()))
3281 if (proto->getReturnType() == Context.UnknownAnyTy) {
3282 type = Context.UnknownAnyTy;
3283 valueKind = VK_RValue;
3284 break;
3285 }
3286
3287 // C++ methods are l-values if static, r-values if non-static.
3288 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3289 valueKind = VK_LValue;
3290 break;
3291 }
3292 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3293
3294 case Decl::CXXConversion:
3295 case Decl::CXXDestructor:
3296 case Decl::CXXConstructor:
3297 valueKind = VK_RValue;
3298 break;
3299 }
3300
3301 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3302 /*FIXME: TemplateKWLoc*/ SourceLocation(),
3303 TemplateArgs);
3304 }
3305}
3306
3307static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3308 SmallString<32> &Target) {
3309 Target.resize(CharByteWidth * (Source.size() + 1));
3310 char *ResultPtr = &Target[0];
3311 const llvm::UTF8 *ErrorPtr;
3312 bool success =
3313 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3314 (void)success;
3315 assert(success)((success) ? static_cast<void> (0) : __assert_fail ("success"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3315, __PRETTY_FUNCTION__))
;
3316 Target.resize(ResultPtr - &Target[0]);
3317}
3318
3319ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3320 PredefinedExpr::IdentKind IK) {
3321 // Pick the current block, lambda, captured statement or function.
3322 Decl *currentDecl = nullptr;
3323 if (const BlockScopeInfo *BSI = getCurBlock())
3324 currentDecl = BSI->TheDecl;
3325 else if (const LambdaScopeInfo *LSI = getCurLambda())
3326 currentDecl = LSI->CallOperator;
3327 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3328 currentDecl = CSI->TheCapturedDecl;
3329 else
3330 currentDecl = getCurFunctionOrMethodDecl();
3331
3332 if (!currentDecl) {
3333 Diag(Loc, diag::ext_predef_outside_function);
3334 currentDecl = Context.getTranslationUnitDecl();
3335 }
3336
3337 QualType ResTy;
3338 StringLiteral *SL = nullptr;
3339 if (cast<DeclContext>(currentDecl)->isDependentContext())
3340 ResTy = Context.DependentTy;
3341 else {
3342 // Pre-defined identifiers are of type char[x], where x is the length of
3343 // the string.
3344 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3345 unsigned Length = Str.length();
3346
3347 llvm::APInt LengthI(32, Length + 1);
3348 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3349 ResTy =
3350 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3351 SmallString<32> RawChars;
3352 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3353 Str, RawChars);
3354 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3355 ArrayType::Normal,
3356 /*IndexTypeQuals*/ 0);
3357 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3358 /*Pascal*/ false, ResTy, Loc);
3359 } else {
3360 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3361 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3362 ArrayType::Normal,
3363 /*IndexTypeQuals*/ 0);
3364 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3365 /*Pascal*/ false, ResTy, Loc);
3366 }
3367 }
3368
3369 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3370}
3371
3372ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3373 PredefinedExpr::IdentKind IK;
3374
3375 switch (Kind) {
3376 default: llvm_unreachable("Unknown simple primary expr!")::llvm::llvm_unreachable_internal("Unknown simple primary expr!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3376)
;
3377 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3378 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3379 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3380 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3381 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3382 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3383 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3384 }
3385
3386 return BuildPredefinedExpr(Loc, IK);
3387}
3388
3389ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3390 SmallString<16> CharBuffer;
3391 bool Invalid = false;
3392 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3393 if (Invalid)
3394 return ExprError();
3395
3396 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3397 PP, Tok.getKind());
3398 if (Literal.hadError())
3399 return ExprError();
3400
3401 QualType Ty;
3402 if (Literal.isWide())
3403 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3404 else if (Literal.isUTF8() && getLangOpts().Char8)
3405 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3406 else if (Literal.isUTF16())
3407 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3408 else if (Literal.isUTF32())
3409 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3410 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3411 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3412 else
3413 Ty = Context.CharTy; // 'x' -> char in C++
3414
3415 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3416 if (Literal.isWide())
3417 Kind = CharacterLiteral::Wide;
3418 else if (Literal.isUTF16())
3419 Kind = CharacterLiteral::UTF16;
3420 else if (Literal.isUTF32())
3421 Kind = CharacterLiteral::UTF32;
3422 else if (Literal.isUTF8())
3423 Kind = CharacterLiteral::UTF8;
3424
3425 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3426 Tok.getLocation());
3427
3428 if (Literal.getUDSuffix().empty())
3429 return Lit;
3430
3431 // We're building a user-defined literal.
3432 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3433 SourceLocation UDSuffixLoc =
3434 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3435
3436 // Make sure we're allowed user-defined literals here.
3437 if (!UDLScope)
3438 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3439
3440 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3441 // operator "" X (ch)
3442 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3443 Lit, Tok.getLocation());
3444}
3445
3446ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3447 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3448 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3449 Context.IntTy, Loc);
3450}
3451
3452static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3453 QualType Ty, SourceLocation Loc) {
3454 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3455
3456 using llvm::APFloat;
3457 APFloat Val(Format);
3458
3459 APFloat::opStatus result = Literal.GetFloatValue(Val);
3460
3461 // Overflow is always an error, but underflow is only an error if
3462 // we underflowed to zero (APFloat reports denormals as underflow).
3463 if ((result & APFloat::opOverflow) ||
3464 ((result & APFloat::opUnderflow) && Val.isZero())) {
3465 unsigned diagnostic;
3466 SmallString<20> buffer;
3467 if (result & APFloat::opOverflow) {
3468 diagnostic = diag::warn_float_overflow;
3469 APFloat::getLargest(Format).toString(buffer);
3470 } else {
3471 diagnostic = diag::warn_float_underflow;
3472 APFloat::getSmallest(Format).toString(buffer);
3473 }
3474
3475 S.Diag(Loc, diagnostic)
3476 << Ty
3477 << StringRef(buffer.data(), buffer.size());
3478 }
3479
3480 bool isExact = (result == APFloat::opOK);
3481 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3482}
3483
3484bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3485 assert(E && "Invalid expression")((E && "Invalid expression") ? static_cast<void>
(0) : __assert_fail ("E && \"Invalid expression\"", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3485, __PRETTY_FUNCTION__))
;
3486
3487 if (E->isValueDependent())
3488 return false;
3489
3490 QualType QT = E->getType();
3491 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3492 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3493 return true;
3494 }
3495
3496 llvm::APSInt ValueAPS;
3497 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3498
3499 if (R.isInvalid())
3500 return true;
3501
3502 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3503 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3504 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3505 << ValueAPS.toString(10) << ValueIsPositive;
3506 return true;
3507 }
3508
3509 return false;
3510}
3511
3512ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3513 // Fast path for a single digit (which is quite common). A single digit
3514 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3515 if (Tok.getLength() == 1) {
3516 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3517 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3518 }
3519
3520 SmallString<128> SpellingBuffer;
3521 // NumericLiteralParser wants to overread by one character. Add padding to
3522 // the buffer in case the token is copied to the buffer. If getSpelling()
3523 // returns a StringRef to the memory buffer, it should have a null char at
3524 // the EOF, so it is also safe.
3525 SpellingBuffer.resize(Tok.getLength() + 1);
3526
3527 // Get the spelling of the token, which eliminates trigraphs, etc.
3528 bool Invalid = false;
3529 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3530 if (Invalid)
3531 return ExprError();
3532
3533 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3534 if (Literal.hadError)
3535 return ExprError();
3536
3537 if (Literal.hasUDSuffix()) {
3538 // We're building a user-defined literal.
3539 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3540 SourceLocation UDSuffixLoc =
3541 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3542
3543 // Make sure we're allowed user-defined literals here.
3544 if (!UDLScope)
3545 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3546
3547 QualType CookedTy;
3548 if (Literal.isFloatingLiteral()) {
3549 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3550 // long double, the literal is treated as a call of the form
3551 // operator "" X (f L)
3552 CookedTy = Context.LongDoubleTy;
3553 } else {
3554 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3555 // unsigned long long, the literal is treated as a call of the form
3556 // operator "" X (n ULL)
3557 CookedTy = Context.UnsignedLongLongTy;
3558 }
3559
3560 DeclarationName OpName =
3561 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3562 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3563 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3564
3565 SourceLocation TokLoc = Tok.getLocation();
3566
3567 // Perform literal operator lookup to determine if we're building a raw
3568 // literal or a cooked one.
3569 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3570 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3571 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3572 /*AllowStringTemplate*/ false,
3573 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3574 case LOLR_ErrorNoDiagnostic:
3575 // Lookup failure for imaginary constants isn't fatal, there's still the
3576 // GNU extension producing _Complex types.
3577 break;
3578 case LOLR_Error:
3579 return ExprError();
3580 case LOLR_Cooked: {
3581 Expr *Lit;
3582 if (Literal.isFloatingLiteral()) {
3583 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3584 } else {
3585 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3586 if (Literal.GetIntegerValue(ResultVal))
3587 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3588 << /* Unsigned */ 1;
3589 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3590 Tok.getLocation());
3591 }
3592 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3593 }
3594
3595 case LOLR_Raw: {
3596 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3597 // literal is treated as a call of the form
3598 // operator "" X ("n")
3599 unsigned Length = Literal.getUDSuffixOffset();
3600 QualType StrTy = Context.getConstantArrayType(
3601 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3602 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3603 Expr *Lit = StringLiteral::Create(
3604 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3605 /*Pascal*/false, StrTy, &TokLoc, 1);
3606 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3607 }
3608
3609 case LOLR_Template: {
3610 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3611 // template), L is treated as a call fo the form
3612 // operator "" X <'c1', 'c2', ... 'ck'>()
3613 // where n is the source character sequence c1 c2 ... ck.
3614 TemplateArgumentListInfo ExplicitArgs;
3615 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3616 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3617 llvm::APSInt Value(CharBits, CharIsUnsigned);
3618 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3619 Value = TokSpelling[I];
3620 TemplateArgument Arg(Context, Value, Context.CharTy);
3621 TemplateArgumentLocInfo ArgInfo;
3622 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3623 }
3624 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3625 &ExplicitArgs);
3626 }
3627 case LOLR_StringTemplate:
3628 llvm_unreachable("unexpected literal operator lookup result")::llvm::llvm_unreachable_internal("unexpected literal operator lookup result"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3628)
;
3629 }
3630 }
3631
3632 Expr *Res;
3633
3634 if (Literal.isFixedPointLiteral()) {
3635 QualType Ty;
3636
3637 if (Literal.isAccum) {
3638 if (Literal.isHalf) {
3639 Ty = Context.ShortAccumTy;
3640 } else if (Literal.isLong) {
3641 Ty = Context.LongAccumTy;
3642 } else {
3643 Ty = Context.AccumTy;
3644 }
3645 } else if (Literal.isFract) {
3646 if (Literal.isHalf) {
3647 Ty = Context.ShortFractTy;
3648 } else if (Literal.isLong) {
3649 Ty = Context.LongFractTy;
3650 } else {
3651 Ty = Context.FractTy;
3652 }
3653 }
3654
3655 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3656
3657 bool isSigned = !Literal.isUnsigned;
3658 unsigned scale = Context.getFixedPointScale(Ty);
3659 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3660
3661 llvm::APInt Val(bit_width, 0, isSigned);
3662 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3663 bool ValIsZero = Val.isNullValue() && !Overflowed;
3664
3665 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3666 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3667 // Clause 6.4.4 - The value of a constant shall be in the range of
3668 // representable values for its type, with exception for constants of a
3669 // fract type with a value of exactly 1; such a constant shall denote
3670 // the maximal value for the type.
3671 --Val;
3672 else if (Val.ugt(MaxVal) || Overflowed)
3673 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3674
3675 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3676 Tok.getLocation(), scale);
3677 } else if (Literal.isFloatingLiteral()) {
3678 QualType Ty;
3679 if (Literal.isHalf){
3680 if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3681 Ty = Context.HalfTy;
3682 else {
3683 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3684 return ExprError();
3685 }
3686 } else if (Literal.isFloat)
3687 Ty = Context.FloatTy;
3688 else if (Literal.isLong)
3689 Ty = Context.LongDoubleTy;
3690 else if (Literal.isFloat16)
3691 Ty = Context.Float16Ty;
3692 else if (Literal.isFloat128)
3693 Ty = Context.Float128Ty;
3694 else
3695 Ty = Context.DoubleTy;
3696
3697 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3698
3699 if (Ty == Context.DoubleTy) {
3700 if (getLangOpts().SinglePrecisionConstants) {
3701 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3702 if (BTy->getKind() != BuiltinType::Float) {
3703 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3704 }
3705 } else if (getLangOpts().OpenCL &&
3706 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3707 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3708 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3709 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3710 }
3711 }
3712 } else if (!Literal.isIntegerLiteral()) {
3713 return ExprError();
3714 } else {
3715 QualType Ty;
3716
3717 // 'long long' is a C99 or C++11 feature.
3718 if (!getLangOpts().C99 && Literal.isLongLong) {
3719 if (getLangOpts().CPlusPlus)
3720 Diag(Tok.getLocation(),
3721 getLangOpts().CPlusPlus11 ?
3722 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3723 else
3724 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3725 }
3726
3727 // Get the value in the widest-possible width.
3728 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3729 llvm::APInt ResultVal(MaxWidth, 0);
3730
3731 if (Literal.GetIntegerValue(ResultVal)) {
3732 // If this value didn't fit into uintmax_t, error and force to ull.
3733 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3734 << /* Unsigned */ 1;
3735 Ty = Context.UnsignedLongLongTy;
3736 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&((Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
"long long is not intmax_t?") ? static_cast<void> (0) :
__assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3737, __PRETTY_FUNCTION__))
3737 "long long is not intmax_t?")((Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
"long long is not intmax_t?") ? static_cast<void> (0) :
__assert_fail ("Context.getTypeSize(Ty) == ResultVal.getBitWidth() && \"long long is not intmax_t?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3737, __PRETTY_FUNCTION__))
;
3738 } else {
3739 // If this value fits into a ULL, try to figure out what else it fits into
3740 // according to the rules of C99 6.4.4.1p5.
3741
3742 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3743 // be an unsigned int.
3744 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3745
3746 // Check from smallest to largest, picking the smallest type we can.
3747 unsigned Width = 0;
3748
3749 // Microsoft specific integer suffixes are explicitly sized.
3750 if (Literal.MicrosoftInteger) {
3751 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3752 Width = 8;
3753 Ty = Context.CharTy;
3754 } else {
3755 Width = Literal.MicrosoftInteger;
3756 Ty = Context.getIntTypeForBitwidth(Width,
3757 /*Signed=*/!Literal.isUnsigned);
3758 }
3759 }
3760
3761 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3762 // Are int/unsigned possibilities?
3763 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3764
3765 // Does it fit in a unsigned int?
3766 if (ResultVal.isIntN(IntSize)) {
3767 // Does it fit in a signed int?
3768 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3769 Ty = Context.IntTy;
3770 else if (AllowUnsigned)
3771 Ty = Context.UnsignedIntTy;
3772 Width = IntSize;
3773 }
3774 }
3775
3776 // Are long/unsigned long possibilities?
3777 if (Ty.isNull() && !Literal.isLongLong) {
3778 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3779
3780 // Does it fit in a unsigned long?
3781 if (ResultVal.isIntN(LongSize)) {
3782 // Does it fit in a signed long?
3783 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3784 Ty = Context.LongTy;
3785 else if (AllowUnsigned)
3786 Ty = Context.UnsignedLongTy;
3787 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3788 // is compatible.
3789 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3790 const unsigned LongLongSize =
3791 Context.getTargetInfo().getLongLongWidth();
3792 Diag(Tok.getLocation(),
3793 getLangOpts().CPlusPlus
3794 ? Literal.isLong
3795 ? diag::warn_old_implicitly_unsigned_long_cxx
3796 : /*C++98 UB*/ diag::
3797 ext_old_implicitly_unsigned_long_cxx
3798 : diag::warn_old_implicitly_unsigned_long)
3799 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3800 : /*will be ill-formed*/ 1);
3801 Ty = Context.UnsignedLongTy;
3802 }
3803 Width = LongSize;
3804 }
3805 }
3806
3807 // Check long long if needed.
3808 if (Ty.isNull()) {
3809 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3810
3811 // Does it fit in a unsigned long long?
3812 if (ResultVal.isIntN(LongLongSize)) {
3813 // Does it fit in a signed long long?
3814 // To be compatible with MSVC, hex integer literals ending with the
3815 // LL or i64 suffix are always signed in Microsoft mode.
3816 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3817 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3818 Ty = Context.LongLongTy;
3819 else if (AllowUnsigned)
3820 Ty = Context.UnsignedLongLongTy;
3821 Width = LongLongSize;
3822 }
3823 }
3824
3825 // If we still couldn't decide a type, we probably have something that
3826 // does not fit in a signed long long, but has no U suffix.
3827 if (Ty.isNull()) {
3828 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3829 Ty = Context.UnsignedLongLongTy;
3830 Width = Context.getTargetInfo().getLongLongWidth();
3831 }
3832
3833 if (ResultVal.getBitWidth() != Width)
3834 ResultVal = ResultVal.trunc(Width);
3835 }
3836 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3837 }
3838
3839 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3840 if (Literal.isImaginary) {
3841 Res = new (Context) ImaginaryLiteral(Res,
3842 Context.getComplexType(Res->getType()));
3843
3844 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3845 }
3846 return Res;
3847}
3848
3849ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3850 assert(E && "ActOnParenExpr() missing expr")((E && "ActOnParenExpr() missing expr") ? static_cast
<void> (0) : __assert_fail ("E && \"ActOnParenExpr() missing expr\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3850, __PRETTY_FUNCTION__))
;
3851 return new (Context) ParenExpr(L, R, E);
3852}
3853
3854static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3855 SourceLocation Loc,
3856 SourceRange ArgRange) {
3857 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3858 // scalar or vector data type argument..."
3859 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3860 // type (C99 6.2.5p18) or void.
3861 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3862 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3863 << T << ArgRange;
3864 return true;
3865 }
3866
3867 assert((T->isVoidType() || !T->isIncompleteType()) &&(((T->isVoidType() || !T->isIncompleteType()) &&
"Scalar types should always be complete") ? static_cast<void
> (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3868, __PRETTY_FUNCTION__))
3868 "Scalar types should always be complete")(((T->isVoidType() || !T->isIncompleteType()) &&
"Scalar types should always be complete") ? static_cast<void
> (0) : __assert_fail ("(T->isVoidType() || !T->isIncompleteType()) && \"Scalar types should always be complete\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3868, __PRETTY_FUNCTION__))
;
3869 return false;
3870}
3871
3872static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3873 SourceLocation Loc,
3874 SourceRange ArgRange,
3875 UnaryExprOrTypeTrait TraitKind) {
3876 // Invalid types must be hard errors for SFINAE in C++.
3877 if (S.LangOpts.CPlusPlus)
3878 return true;
3879
3880 // C99 6.5.3.4p1:
3881 if (T->isFunctionType() &&
3882 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3883 TraitKind == UETT_PreferredAlignOf)) {
3884 // sizeof(function)/alignof(function) is allowed as an extension.
3885 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3886 << TraitKind << ArgRange;
3887 return false;
3888 }
3889
3890 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3891 // this is an error (OpenCL v1.1 s6.3.k)
3892 if (T->isVoidType()) {
3893 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3894 : diag::ext_sizeof_alignof_void_type;
3895 S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3896 return false;
3897 }
3898
3899 return true;
3900}
3901
3902static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3903 SourceLocation Loc,
3904 SourceRange ArgRange,
3905 UnaryExprOrTypeTrait TraitKind) {
3906 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3907 // runtime doesn't allow it.
3908 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3909 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3910 << T << (TraitKind == UETT_SizeOf)
3911 << ArgRange;
3912 return true;
3913 }
3914
3915 return false;
3916}
3917
3918/// Check whether E is a pointer from a decayed array type (the decayed
3919/// pointer type is equal to T) and emit a warning if it is.
3920static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3921 Expr *E) {
3922 // Don't warn if the operation changed the type.
3923 if (T != E->getType())
3924 return;
3925
3926 // Now look for array decays.
3927 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3928 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3929 return;
3930
3931 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3932 << ICE->getType()
3933 << ICE->getSubExpr()->getType();
3934}
3935
3936/// Check the constraints on expression operands to unary type expression
3937/// and type traits.
3938///
3939/// Completes any types necessary and validates the constraints on the operand
3940/// expression. The logic mostly mirrors the type-based overload, but may modify
3941/// the expression as it completes the type for that expression through template
3942/// instantiation, etc.
3943bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3944 UnaryExprOrTypeTrait ExprKind) {
3945 QualType ExprTy = E->getType();
3946 assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0
) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3946, __PRETTY_FUNCTION__))
;
3947
3948 bool IsUnevaluatedOperand =
3949 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3950 ExprKind == UETT_PreferredAlignOf);
3951 if (IsUnevaluatedOperand) {
3952 ExprResult Result = CheckUnevaluatedOperand(E);
3953 if (Result.isInvalid())
3954 return true;
3955 E = Result.get();
3956 }
3957
3958 if (ExprKind == UETT_VecStep)
3959 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3960 E->getSourceRange());
3961
3962 // Whitelist some types as extensions
3963 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3964 E->getSourceRange(), ExprKind))
3965 return false;
3966
3967 // 'alignof' applied to an expression only requires the base element type of
3968 // the expression to be complete. 'sizeof' requires the expression's type to
3969 // be complete (and will attempt to complete it if it's an array of unknown
3970 // bound).
3971 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3972 if (RequireCompleteType(E->getExprLoc(),
3973 Context.getBaseElementType(E->getType()),
3974 diag::err_sizeof_alignof_incomplete_type, ExprKind,
3975 E->getSourceRange()))
3976 return true;
3977 } else {
3978 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3979 ExprKind, E->getSourceRange()))
3980 return true;
3981 }
3982
3983 // Completing the expression's type may have changed it.
3984 ExprTy = E->getType();
3985 assert(!ExprTy->isReferenceType())((!ExprTy->isReferenceType()) ? static_cast<void> (0
) : __assert_fail ("!ExprTy->isReferenceType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 3985, __PRETTY_FUNCTION__))
;
3986
3987 if (ExprTy->isFunctionType()) {
3988 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3989 << ExprKind << E->getSourceRange();
3990 return true;
3991 }
3992
3993 // The operand for sizeof and alignof is in an unevaluated expression context,
3994 // so side effects could result in unintended consequences.
3995 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
3996 E->HasSideEffects(Context, false))
3997 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3998
3999 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4000 E->getSourceRange(), ExprKind))
4001 return true;
4002
4003 if (ExprKind == UETT_SizeOf) {
4004 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4005 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4006 QualType OType = PVD->getOriginalType();
4007 QualType Type = PVD->getType();
4008 if (Type->isPointerType() && OType->isArrayType()) {
4009 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4010 << Type << OType;
4011 Diag(PVD->getLocation(), diag::note_declared_at);
4012 }
4013 }
4014 }
4015
4016 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4017 // decays into a pointer and returns an unintended result. This is most
4018 // likely a typo for "sizeof(array) op x".
4019 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4020 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4021 BO->getLHS());
4022 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4023 BO->getRHS());
4024 }
4025 }
4026
4027 return false;
4028}
4029
4030/// Check the constraints on operands to unary expression and type
4031/// traits.
4032///
4033/// This will complete any types necessary, and validate the various constraints
4034/// on those operands.
4035///
4036/// The UsualUnaryConversions() function is *not* called by this routine.
4037/// C99 6.3.2.1p[2-4] all state:
4038/// Except when it is the operand of the sizeof operator ...
4039///
4040/// C++ [expr.sizeof]p4
4041/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4042/// standard conversions are not applied to the operand of sizeof.
4043///
4044/// This policy is followed for all of the unary trait expressions.
4045bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4046 SourceLocation OpLoc,
4047 SourceRange ExprRange,
4048 UnaryExprOrTypeTrait ExprKind) {
4049 if (ExprType->isDependentType())
4050 return false;
4051
4052 // C++ [expr.sizeof]p2:
4053 // When applied to a reference or a reference type, the result
4054 // is the size of the referenced type.
4055 // C++11 [expr.alignof]p3:
4056 // When alignof is applied to a reference type, the result
4057 // shall be the alignment of the referenced type.
4058 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4059 ExprType = Ref->getPointeeType();
4060
4061 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4062 // When alignof or _Alignof is applied to an array type, the result
4063 // is the alignment of the element type.
4064 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4065 ExprKind == UETT_OpenMPRequiredSimdAlign)
4066 ExprType = Context.getBaseElementType(ExprType);
4067
4068 if (ExprKind == UETT_VecStep)
4069 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4070
4071 // Whitelist some types as extensions
4072 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4073 ExprKind))
4074 return false;
4075
4076 if (RequireCompleteType(OpLoc, ExprType,
4077 diag::err_sizeof_alignof_incomplete_type,
4078 ExprKind, ExprRange))
4079 return true;
4080
4081 if (ExprType->isFunctionType()) {
4082 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4083 << ExprKind << ExprRange;
4084 return true;
4085 }
4086
4087 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4088 ExprKind))
4089 return true;
4090
4091 return false;
4092}
4093
4094static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4095 // Cannot know anything else if the expression is dependent.
4096 if (E->isTypeDependent())
4097 return false;
4098
4099 if (E->getObjectKind() == OK_BitField) {
4100 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4101 << 1 << E->getSourceRange();
4102 return true;
4103 }
4104
4105 ValueDecl *D = nullptr;
4106 Expr *Inner = E->IgnoreParens();
4107 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4108 D = DRE->getDecl();
4109 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4110 D = ME->getMemberDecl();
4111 }
4112
4113 // If it's a field, require the containing struct to have a
4114 // complete definition so that we can compute the layout.
4115 //
4116 // This can happen in C++11 onwards, either by naming the member
4117 // in a way that is not transformed into a member access expression
4118 // (in an unevaluated operand, for instance), or by naming the member
4119 // in a trailing-return-type.
4120 //
4121 // For the record, since __alignof__ on expressions is a GCC
4122 // extension, GCC seems to permit this but always gives the
4123 // nonsensical answer 0.
4124 //
4125 // We don't really need the layout here --- we could instead just
4126 // directly check for all the appropriate alignment-lowing
4127 // attributes --- but that would require duplicating a lot of
4128 // logic that just isn't worth duplicating for such a marginal
4129 // use-case.
4130 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4131 // Fast path this check, since we at least know the record has a
4132 // definition if we can find a member of it.
4133 if (!FD->getParent()->isCompleteDefinition()) {
4134 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4135 << E->getSourceRange();
4136 return true;
4137 }
4138
4139 // Otherwise, if it's a field, and the field doesn't have
4140 // reference type, then it must have a complete type (or be a
4141 // flexible array member, which we explicitly want to
4142 // white-list anyway), which makes the following checks trivial.
4143 if (!FD->getType()->isReferenceType())
4144 return false;
4145 }
4146
4147 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4148}
4149
4150bool Sema::CheckVecStepExpr(Expr *E) {
4151 E = E->IgnoreParens();
4152
4153 // Cannot know anything else if the expression is dependent.
4154 if (E->isTypeDependent())
4155 return false;
4156
4157 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4158}
4159
4160static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4161 CapturingScopeInfo *CSI) {
4162 assert(T->isVariablyModifiedType())((T->isVariablyModifiedType()) ? static_cast<void> (
0) : __assert_fail ("T->isVariablyModifiedType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 4162, __PRETTY_FUNCTION__))
;
4163 assert(CSI != nullptr)((CSI != nullptr) ? static_cast<void> (0) : __assert_fail
("CSI != nullptr", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 4163, __PRETTY_FUNCTION__))
;
4164
4165 // We're going to walk down into the type and look for VLA expressions.
4166 do {
4167 const Type *Ty = T.getTypePtr();
4168 switch (Ty->getTypeClass()) {
4169#define TYPE(Class, Base)
4170#define ABSTRACT_TYPE(Class, Base)
4171#define NON_CANONICAL_TYPE(Class, Base)
4172#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4173#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4174#include "clang/AST/TypeNodes.inc"
4175 T = QualType();
4176 break;
4177 // These types are never variably-modified.
4178 case Type::Builtin:
4179 case Type::Complex:
4180 case Type::Vector:
4181 case Type::ExtVector:
4182 case Type::Record:
4183 case Type::Enum:
4184 case Type::Elaborated:
4185 case Type::TemplateSpecialization:
4186 case Type::ObjCObject:
4187 case Type::ObjCInterface:
4188 case Type::ObjCObjectPointer:
4189 case Type::ObjCTypeParam:
4190 case Type::Pipe:
4191 llvm_unreachable("type class is never variably-modified!")::llvm::llvm_unreachable_internal("type class is never variably-modified!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 4191)
;
4192 case Type::Adjusted:
4193 T = cast<AdjustedType>(Ty)->getOriginalType();
4194 break;
4195 case Type::Decayed:
4196 T = cast<DecayedType>(Ty)->getPointeeType();
4197 break;
4198 case Type::Pointer:
4199 T = cast<PointerType>(Ty)->getPointeeType();
4200 break;
4201 case Type::BlockPointer:
4202 T = cast<BlockPointerType>(Ty)->getPointeeType();
4203 break;
4204 case Type::LValueReference:
4205 case Type::RValueReference:
4206 T = cast<ReferenceType>(Ty)->getPointeeType();
4207 break;
4208 case Type::MemberPointer:
4209 T = cast<MemberPointerType>(Ty)->getPointeeType();
4210 break;
4211 case Type::ConstantArray:
4212 case Type::IncompleteArray:
4213 // Losing element qualification here is fine.
4214 T = cast<ArrayType>(Ty)->getElementType();
4215 break;
4216 case Type::VariableArray: {
4217 // Losing element qualification here is fine.
4218 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4219
4220 // Unknown size indication requires no size computation.
4221 // Otherwise, evaluate and record it.
4222 auto Size = VAT->getSizeExpr();
4223 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4224 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4225 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4226
4227 T = VAT->getElementType();
4228 break;
4229 }
4230 case Type::FunctionProto:
4231 case Type::FunctionNoProto:
4232 T = cast<FunctionType>(Ty)->getReturnType();
4233 break;
4234 case Type::Paren:
4235 case Type::TypeOf:
4236 case Type::UnaryTransform:
4237 case Type::Attributed:
4238 case Type::SubstTemplateTypeParm:
4239 case Type::PackExpansion:
4240 case Type::MacroQualified:
4241 // Keep walking after single level desugaring.
4242 T = T.getSingleStepDesugaredType(Context);
4243 break;
4244 case Type::Typedef:
4245 T = cast<TypedefType>(Ty)->desugar();
4246 break;
4247 case Type::Decltype:
4248 T = cast<DecltypeType>(Ty)->desugar();
4249 break;
4250 case Type::Auto:
4251 case Type::DeducedTemplateSpecialization:
4252 T = cast<DeducedType>(Ty)->getDeducedType();
4253 break;
4254 case Type::TypeOfExpr:
4255 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4256 break;
4257 case Type::Atomic:
4258 T = cast<AtomicType>(Ty)->getValueType();
4259 break;
4260 }
4261 } while (!T.isNull() && T->isVariablyModifiedType());
4262}
4263
4264/// Build a sizeof or alignof expression given a type operand.
4265ExprResult
4266Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4267 SourceLocation OpLoc,
4268 UnaryExprOrTypeTrait ExprKind,
4269 SourceRange R) {
4270 if (!TInfo)
4271 return ExprError();
4272
4273 QualType T = TInfo->getType();
4274
4275 if (!T->isDependentType() &&
4276 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4277 return ExprError();
4278
4279 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4280 if (auto *TT = T->getAs<TypedefType>()) {
4281 for (auto I = FunctionScopes.rbegin(),
4282 E = std::prev(FunctionScopes.rend());
4283 I != E; ++I) {
4284 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4285 if (CSI == nullptr)
4286 break;
4287 DeclContext *DC = nullptr;
4288 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4289 DC = LSI->CallOperator;
4290 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4291 DC = CRSI->TheCapturedDecl;
4292 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4293 DC = BSI->TheDecl;
4294 if (DC) {
4295 if (DC->containsDecl(TT->getDecl()))
4296 break;
4297 captureVariablyModifiedType(Context, T, CSI);
4298 }
4299 }
4300 }
4301 }
4302
4303 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4304 return new (Context) UnaryExprOrTypeTraitExpr(
4305 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4306}
4307
4308/// Build a sizeof or alignof expression given an expression
4309/// operand.
4310ExprResult
4311Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4312 UnaryExprOrTypeTrait ExprKind) {
4313 ExprResult PE = CheckPlaceholderExpr(E);
4314 if (PE.isInvalid())
4315 return ExprError();
4316
4317 E = PE.get();
4318
4319 // Verify that the operand is valid.
4320 bool isInvalid = false;
4321 if (E->isTypeDependent()) {
4322 // Delay type-checking for type-dependent expressions.
4323 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4324 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4325 } else if (ExprKind == UETT_VecStep) {
4326 isInvalid = CheckVecStepExpr(E);
4327 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4328 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4329 isInvalid = true;
4330 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4331 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4332 isInvalid = true;
4333 } else {
4334 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4335 }
4336
4337 if (isInvalid)
4338 return ExprError();
4339
4340 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4341 PE = TransformToPotentiallyEvaluated(E);
4342 if (PE.isInvalid()) return ExprError();
4343 E = PE.get();
4344 }
4345
4346 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4347 return new (Context) UnaryExprOrTypeTraitExpr(
4348 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4349}
4350
4351/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4352/// expr and the same for @c alignof and @c __alignof
4353/// Note that the ArgRange is invalid if isType is false.
4354ExprResult
4355Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4356 UnaryExprOrTypeTrait ExprKind, bool IsType,
4357 void *TyOrEx, SourceRange ArgRange) {
4358 // If error parsing type, ignore.
4359 if (!TyOrEx) return ExprError();
4360
4361 if (IsType) {
4362 TypeSourceInfo *TInfo;
4363 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4364 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4365 }
4366
4367 Expr *ArgEx = (Expr *)TyOrEx;
4368 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4369 return Result;
4370}
4371
4372static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4373 bool IsReal) {
4374 if (V.get()->isTypeDependent())
4375 return S.Context.DependentTy;
4376
4377 // _Real and _Imag are only l-values for normal l-values.
4378 if (V.get()->getObjectKind() != OK_Ordinary) {
4379 V = S.DefaultLvalueConversion(V.get());
4380 if (V.isInvalid())
4381 return QualType();
4382 }
4383
4384 // These operators return the element type of a complex type.
4385 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4386 return CT->getElementType();
4387
4388 // Otherwise they pass through real integer and floating point types here.
4389 if (V.get()->getType()->isArithmeticType())
4390 return V.get()->getType();
4391
4392 // Test for placeholders.
4393 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4394 if (PR.isInvalid()) return QualType();
4395 if (PR.get() != V.get()) {
4396 V = PR;
4397 return CheckRealImagOperand(S, V, Loc, IsReal);
4398 }
4399
4400 // Reject anything else.
4401 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4402 << (IsReal ? "__real" : "__imag");
4403 return QualType();
4404}
4405
4406
4407
4408ExprResult
4409Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4410 tok::TokenKind Kind, Expr *Input) {
4411 UnaryOperatorKind Opc;
4412 switch (Kind) {
4413 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 4413)
;
4414 case tok::plusplus: Opc = UO_PostInc; break;
4415 case tok::minusminus: Opc = UO_PostDec; break;
4416 }
4417
4418 // Since this might is a postfix expression, get rid of ParenListExprs.
4419 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4420 if (Result.isInvalid()) return ExprError();
4421 Input = Result.get();
4422
4423 return BuildUnaryOp(S, OpLoc, Opc, Input);
4424}
4425
4426/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4427///
4428/// \return true on error
4429static bool checkArithmeticOnObjCPointer(Sema &S,
4430 SourceLocation opLoc,
4431 Expr *op) {
4432 assert(op->getType()->isObjCObjectPointerType())((op->getType()->isObjCObjectPointerType()) ? static_cast
<void> (0) : __assert_fail ("op->getType()->isObjCObjectPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 4432, __PRETTY_FUNCTION__))
;
4433 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4434 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4435 return false;
4436
4437 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4438 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4439 << op->getSourceRange();
4440 return true;
4441}
4442
4443static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4444 auto *BaseNoParens = Base->IgnoreParens();
4445 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4446 return MSProp->getPropertyDecl()->getType()->isArrayType();
4447 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4448}
4449
4450ExprResult
4451Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4452 Expr *idx, SourceLocation rbLoc) {
4453 if (base && !base->getType().isNull() &&
4454 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4455 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4456 /*Length=*/nullptr, rbLoc);
4457
4458 // Since this might be a postfix expression, get rid of ParenListExprs.
4459 if (isa<ParenListExpr>(base)) {
4460 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4461 if (result.isInvalid()) return ExprError();
4462 base = result.get();
4463 }
4464
4465 // A comma-expression as the index is deprecated in C++2a onwards.
4466 if (getLangOpts().CPlusPlus2a &&
4467 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4468 (isa<CXXOperatorCallExpr>(idx) &&
4469 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4470 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4471 << SourceRange(base->getBeginLoc(), rbLoc);
4472 }
4473
4474 // Handle any non-overload placeholder types in the base and index
4475 // expressions. We can't handle overloads here because the other
4476 // operand might be an overloadable type, in which case the overload
4477 // resolution for the operator overload should get the first crack
4478 // at the overload.
4479 bool IsMSPropertySubscript = false;
4480 if (base->getType()->isNonOverloadPlaceholderType()) {
4481 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4482 if (!IsMSPropertySubscript) {
4483 ExprResult result = CheckPlaceholderExpr(base);
4484 if (result.isInvalid())
4485 return ExprError();
4486 base = result.get();
4487 }
4488 }
4489 if (idx->getType()->isNonOverloadPlaceholderType()) {
4490 ExprResult result = CheckPlaceholderExpr(idx);
4491 if (result.isInvalid()) return ExprError();
4492 idx = result.get();
4493 }
4494
4495 // Build an unanalyzed expression if either operand is type-dependent.
4496 if (getLangOpts().CPlusPlus &&
4497 (base->isTypeDependent() || idx->isTypeDependent())) {
4498 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4499 VK_LValue, OK_Ordinary, rbLoc);
4500 }
4501
4502 // MSDN, property (C++)
4503 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4504 // This attribute can also be used in the declaration of an empty array in a
4505 // class or structure definition. For example:
4506 // __declspec(property(get=GetX, put=PutX)) int x[];
4507 // The above statement indicates that x[] can be used with one or more array
4508 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4509 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4510 if (IsMSPropertySubscript) {
4511 // Build MS property subscript expression if base is MS property reference
4512 // or MS property subscript.
4513 return new (Context) MSPropertySubscriptExpr(
4514 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4515 }
4516
4517 // Use C++ overloaded-operator rules if either operand has record
4518 // type. The spec says to do this if either type is *overloadable*,
4519 // but enum types can't declare subscript operators or conversion
4520 // operators, so there's nothing interesting for overload resolution
4521 // to do if there aren't any record types involved.
4522 //
4523 // ObjC pointers have their own subscripting logic that is not tied
4524 // to overload resolution and so should not take this path.
4525 if (getLangOpts().CPlusPlus &&
4526 (base->getType()->isRecordType() ||
4527 (!base->getType()->isObjCObjectPointerType() &&
4528 idx->getType()->isRecordType()))) {
4529 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4530 }
4531
4532 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4533
4534 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4535 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4536
4537 return Res;
4538}
4539
4540void Sema::CheckAddressOfNoDeref(const Expr *E) {
4541 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4542 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4543
4544 // For expressions like `&(*s).b`, the base is recorded and what should be
4545 // checked.
4546 const MemberExpr *Member = nullptr;
4547 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4548 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4549
4550 LastRecord.PossibleDerefs.erase(StrippedExpr);
4551}
4552
4553void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4554 QualType ResultTy = E->getType();
4555 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4556
4557 // Bail if the element is an array since it is not memory access.
4558 if (isa<ArrayType>(ResultTy))
4559 return;
4560
4561 if (ResultTy->hasAttr(attr::NoDeref)) {
4562 LastRecord.PossibleDerefs.insert(E);
4563 return;
4564 }
4565
4566 // Check if the base type is a pointer to a member access of a struct
4567 // marked with noderef.
4568 const Expr *Base = E->getBase();
4569 QualType BaseTy = Base->getType();
4570 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4571 // Not a pointer access
4572 return;
4573
4574 const MemberExpr *Member = nullptr;
4575 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4576 Member->isArrow())
4577 Base = Member->getBase();
4578
4579 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4580 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4581 LastRecord.PossibleDerefs.insert(E);
4582 }
4583}
4584
4585ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4586 Expr *LowerBound,
4587 SourceLocation ColonLoc, Expr *Length,
4588 SourceLocation RBLoc) {
4589 if (Base->getType()->isPlaceholderType() &&
4590 !Base->getType()->isSpecificPlaceholderType(
4591 BuiltinType::OMPArraySection)) {
4592 ExprResult Result = CheckPlaceholderExpr(Base);
4593 if (Result.isInvalid())
4594 return ExprError();
4595 Base = Result.get();
4596 }
4597 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4598 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4599 if (Result.isInvalid())
4600 return ExprError();
4601 Result = DefaultLvalueConversion(Result.get());
4602 if (Result.isInvalid())
4603 return ExprError();
4604 LowerBound = Result.get();
4605 }
4606 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4607 ExprResult Result = CheckPlaceholderExpr(Length);
4608 if (Result.isInvalid())
4609 return ExprError();
4610 Result = DefaultLvalueConversion(Result.get());
4611 if (Result.isInvalid())
4612 return ExprError();
4613 Length = Result.get();
4614 }
4615
4616 // Build an unanalyzed expression if either operand is type-dependent.
4617 if (Base->isTypeDependent() ||
4618 (LowerBound &&
4619 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4620 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4621 return new (Context)
4622 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4623 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4624 }
4625
4626 // Perform default conversions.
4627 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4628 QualType ResultTy;
4629 if (OriginalTy->isAnyPointerType()) {
4630 ResultTy = OriginalTy->getPointeeType();
4631 } else if (OriginalTy->isArrayType()) {
4632 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4633 } else {
4634 return ExprError(
4635 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4636 << Base->getSourceRange());
4637 }
4638 // C99 6.5.2.1p1
4639 if (LowerBound) {
4640 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4641 LowerBound);
4642 if (Res.isInvalid())
4643 return ExprError(Diag(LowerBound->getExprLoc(),
4644 diag::err_omp_typecheck_section_not_integer)
4645 << 0 << LowerBound->getSourceRange());
4646 LowerBound = Res.get();
4647
4648 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4649 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4650 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4651 << 0 << LowerBound->getSourceRange();
4652 }
4653 if (Length) {
4654 auto Res =
4655 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4656 if (Res.isInvalid())
4657 return ExprError(Diag(Length->getExprLoc(),
4658 diag::err_omp_typecheck_section_not_integer)
4659 << 1 << Length->getSourceRange());
4660 Length = Res.get();
4661
4662 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4663 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4664 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4665 << 1 << Length->getSourceRange();
4666 }
4667
4668 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4669 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4670 // type. Note that functions are not objects, and that (in C99 parlance)
4671 // incomplete types are not object types.
4672 if (ResultTy->isFunctionType()) {
4673 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4674 << ResultTy << Base->getSourceRange();
4675 return ExprError();
4676 }
4677
4678 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4679 diag::err_omp_section_incomplete_type, Base))
4680 return ExprError();
4681
4682 if (LowerBound && !OriginalTy->isAnyPointerType()) {
4683 Expr::EvalResult Result;
4684 if (LowerBound->EvaluateAsInt(Result, Context)) {
4685 // OpenMP 4.5, [2.4 Array Sections]
4686 // The array section must be a subset of the original array.
4687 llvm::APSInt LowerBoundValue = Result.Val.getInt();
4688 if (LowerBoundValue.isNegative()) {
4689 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4690 << LowerBound->getSourceRange();
4691 return ExprError();
4692 }
4693 }
4694 }
4695
4696 if (Length) {
4697 Expr::EvalResult Result;
4698 if (Length->EvaluateAsInt(Result, Context)) {
4699 // OpenMP 4.5, [2.4 Array Sections]
4700 // The length must evaluate to non-negative integers.
4701 llvm::APSInt LengthValue = Result.Val.getInt();
4702 if (LengthValue.isNegative()) {
4703 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4704 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4705 << Length->getSourceRange();
4706 return ExprError();
4707 }
4708 }
4709 } else if (ColonLoc.isValid() &&
4710 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4711 !OriginalTy->isVariableArrayType()))) {
4712 // OpenMP 4.5, [2.4 Array Sections]
4713 // When the size of the array dimension is not known, the length must be
4714 // specified explicitly.
4715 Diag(ColonLoc, diag::err_omp_section_length_undefined)
4716 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4717 return ExprError();
4718 }
4719
4720 if (!Base->getType()->isSpecificPlaceholderType(
4721 BuiltinType::OMPArraySection)) {
4722 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4723 if (Result.isInvalid())
4724 return ExprError();
4725 Base = Result.get();
4726 }
4727 return new (Context)
4728 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4729 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4730}
4731
4732ExprResult
4733Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4734 Expr *Idx, SourceLocation RLoc) {
4735 Expr *LHSExp = Base;
4736 Expr *RHSExp = Idx;
4737
4738 ExprValueKind VK = VK_LValue;
4739 ExprObjectKind OK = OK_Ordinary;
4740
4741 // Per C++ core issue 1213, the result is an xvalue if either operand is
4742 // a non-lvalue array, and an lvalue otherwise.
4743 if (getLangOpts().CPlusPlus11) {
4744 for (auto *Op : {LHSExp, RHSExp}) {
4745 Op = Op->IgnoreImplicit();
4746 if (Op->getType()->isArrayType() && !Op->isLValue())
4747 VK = VK_XValue;
4748 }
4749 }
4750
4751 // Perform default conversions.
4752 if (!LHSExp->getType()->getAs<VectorType>()) {
4753 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4754 if (Result.isInvalid())
4755 return ExprError();
4756 LHSExp = Result.get();
4757 }
4758 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4759 if (Result.isInvalid())
4760 return ExprError();
4761 RHSExp = Result.get();
4762
4763 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4764
4765 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4766 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4767 // in the subscript position. As a result, we need to derive the array base
4768 // and index from the expression types.
4769 Expr *BaseExpr, *IndexExpr;
4770 QualType ResultType;
4771 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4772 BaseExpr = LHSExp;
4773 IndexExpr = RHSExp;
4774 ResultType = Context.DependentTy;
4775 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4776 BaseExpr = LHSExp;
4777 IndexExpr = RHSExp;
4778 ResultType = PTy->getPointeeType();
4779 } else if (const ObjCObjectPointerType *PTy =
4780 LHSTy->getAs<ObjCObjectPointerType>()) {
4781 BaseExpr = LHSExp;
4782 IndexExpr = RHSExp;
4783
4784 // Use custom logic if this should be the pseudo-object subscript
4785 // expression.
4786 if (!LangOpts.isSubscriptPointerArithmetic())
4787 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4788 nullptr);
4789
4790 ResultType = PTy->getPointeeType();
4791 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4792 // Handle the uncommon case of "123[Ptr]".
4793 BaseExpr = RHSExp;
4794 IndexExpr = LHSExp;
4795 ResultType = PTy->getPointeeType();
4796 } else if (const ObjCObjectPointerType *PTy =
4797 RHSTy->getAs<ObjCObjectPointerType>()) {
4798 // Handle the uncommon case of "123[Ptr]".
4799 BaseExpr = RHSExp;
4800 IndexExpr = LHSExp;
4801 ResultType = PTy->getPointeeType();
4802 if (!LangOpts.isSubscriptPointerArithmetic()) {
4803 Diag(LLoc, diag::err_subscript_nonfragile_interface)
4804 << ResultType << BaseExpr->getSourceRange();
4805 return ExprError();
4806 }
4807 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4808 BaseExpr = LHSExp; // vectors: V[123]
4809 IndexExpr = RHSExp;
4810 // We apply C++ DR1213 to vector subscripting too.
4811 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4812 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4813 if (Materialized.isInvalid())
4814 return ExprError();
4815 LHSExp = Materialized.get();
4816 }
4817 VK = LHSExp->getValueKind();
4818 if (VK != VK_RValue)
4819 OK = OK_VectorComponent;
4820
4821 ResultType = VTy->getElementType();
4822 QualType BaseType = BaseExpr->getType();
4823 Qualifiers BaseQuals = BaseType.getQualifiers();
4824 Qualifiers MemberQuals = ResultType.getQualifiers();
4825 Qualifiers Combined = BaseQuals + MemberQuals;
4826 if (Combined != MemberQuals)
4827 ResultType = Context.getQualifiedType(ResultType, Combined);
4828 } else if (LHSTy->isArrayType()) {
4829 // If we see an array that wasn't promoted by
4830 // DefaultFunctionArrayLvalueConversion, it must be an array that
4831 // wasn't promoted because of the C90 rule that doesn't
4832 // allow promoting non-lvalue arrays. Warn, then
4833 // force the promotion here.
4834 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4835 << LHSExp->getSourceRange();
4836 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4837 CK_ArrayToPointerDecay).get();
4838 LHSTy = LHSExp->getType();
4839
4840 BaseExpr = LHSExp;
4841 IndexExpr = RHSExp;
4842 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4843 } else if (RHSTy->isArrayType()) {
4844 // Same as previous, except for 123[f().a] case
4845 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4846 << RHSExp->getSourceRange();
4847 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4848 CK_ArrayToPointerDecay).get();
4849 RHSTy = RHSExp->getType();
4850
4851 BaseExpr = RHSExp;
4852 IndexExpr = LHSExp;
4853 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4854 } else {
4855 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4856 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4857 }
4858 // C99 6.5.2.1p1
4859 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4860 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4861 << IndexExpr->getSourceRange());
4862
4863 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4864 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4865 && !IndexExpr->isTypeDependent())
4866 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4867
4868 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4869 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4870 // type. Note that Functions are not objects, and that (in C99 parlance)
4871 // incomplete types are not object types.
4872 if (ResultType->isFunctionType()) {
4873 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4874 << ResultType << BaseExpr->getSourceRange();
4875 return ExprError();
4876 }
4877
4878 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4879 // GNU extension: subscripting on pointer to void
4880 Diag(LLoc, diag::ext_gnu_subscript_void_type)
4881 << BaseExpr->getSourceRange();
4882
4883 // C forbids expressions of unqualified void type from being l-values.
4884 // See IsCForbiddenLValueType.
4885 if (!ResultType.hasQualifiers()) VK = VK_RValue;
4886 } else if (!ResultType->isDependentType() &&
4887 RequireCompleteType(LLoc, ResultType,
4888 diag::err_subscript_incomplete_type, BaseExpr))
4889 return ExprError();
4890
4891 assert(VK == VK_RValue || LangOpts.CPlusPlus ||((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType
()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 4892, __PRETTY_FUNCTION__))
4892 !ResultType.isCForbiddenLValueType())((VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType
()) ? static_cast<void> (0) : __assert_fail ("VK == VK_RValue || LangOpts.CPlusPlus || !ResultType.isCForbiddenLValueType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 4892, __PRETTY_FUNCTION__))
;
4893
4894 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
4895 FunctionScopes.size() > 1) {
4896 if (auto *TT =
4897 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
4898 for (auto I = FunctionScopes.rbegin(),
4899 E = std::prev(FunctionScopes.rend());
4900 I != E; ++I) {
4901 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4902 if (CSI == nullptr)
4903 break;
4904 DeclContext *DC = nullptr;
4905 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4906 DC = LSI->CallOperator;
4907 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4908 DC = CRSI->TheCapturedDecl;
4909 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4910 DC = BSI->TheDecl;
4911 if (DC) {
4912 if (DC->containsDecl(TT->getDecl()))
4913 break;
4914 captureVariablyModifiedType(
4915 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
4916 }
4917 }
4918 }
4919 }
4920
4921 return new (Context)
4922 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4923}
4924
4925bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4926 ParmVarDecl *Param) {
4927 if (Param->hasUnparsedDefaultArg()) {
4928 Diag(CallLoc,
4929 diag::err_use_of_default_argument_to_function_declared_later) <<
4930 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4931 Diag(UnparsedDefaultArgLocs[Param],
4932 diag::note_default_argument_declared_here);
4933 return true;
4934 }
4935
4936 if (Param->hasUninstantiatedDefaultArg()) {
4937 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4938
4939 EnterExpressionEvaluationContext EvalContext(
4940 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4941
4942 // Instantiate the expression.
4943 //
4944 // FIXME: Pass in a correct Pattern argument, otherwise
4945 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4946 //
4947 // template<typename T>
4948 // struct A {
4949 // static int FooImpl();
4950 //
4951 // template<typename Tp>
4952 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4953 // // template argument list [[T], [Tp]], should be [[Tp]].
4954 // friend A<Tp> Foo(int a);
4955 // };
4956 //
4957 // template<typename T>
4958 // A<T> Foo(int a = A<T>::FooImpl());
4959 MultiLevelTemplateArgumentList MutiLevelArgList
4960 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4961
4962 InstantiatingTemplate Inst(*this, CallLoc, Param,
4963 MutiLevelArgList.getInnermost());
4964 if (Inst.isInvalid())
4965 return true;
4966 if (Inst.isAlreadyInstantiating()) {
4967 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4968 Param->setInvalidDecl();
4969 return true;
4970 }
4971
4972 ExprResult Result;
4973 {
4974 // C++ [dcl.fct.default]p5:
4975 // The names in the [default argument] expression are bound, and
4976 // the semantic constraints are checked, at the point where the
4977 // default argument expression appears.
4978 ContextRAII SavedContext(*this, FD);
4979 LocalInstantiationScope Local(*this);
4980 runWithSufficientStackSpace(CallLoc, [&] {
4981 Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4982 /*DirectInit*/false);
4983 });
4984 }
4985 if (Result.isInvalid())
4986 return true;
4987
4988 // Check the expression as an initializer for the parameter.
4989 InitializedEntity Entity
4990 = InitializedEntity::InitializeParameter(Context, Param);
4991 InitializationKind Kind = InitializationKind::CreateCopy(
4992 Param->getLocation(),
4993 /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4994 Expr *ResultE = Result.getAs<Expr>();
4995
4996 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4997 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4998 if (Result.isInvalid())
4999 return true;
5000
5001 Result =
5002 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
5003 /*DiscardedValue*/ false);
5004 if (Result.isInvalid())
5005 return true;
5006
5007 // Remember the instantiated default argument.
5008 Param->setDefaultArg(Result.getAs<Expr>());
5009 if (ASTMutationListener *L = getASTMutationListener()) {
5010 L->DefaultArgumentInstantiated(Param);
5011 }
5012 }
5013
5014 // If the default argument expression is not set yet, we are building it now.
5015 if (!Param->hasInit()) {
5016 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5017 Param->setInvalidDecl();
5018 return true;
5019 }
5020
5021 // If the default expression creates temporaries, we need to
5022 // push them to the current stack of expression temporaries so they'll
5023 // be properly destroyed.
5024 // FIXME: We should really be rebuilding the default argument with new
5025 // bound temporaries; see the comment in PR5810.
5026 // We don't need to do that with block decls, though, because
5027 // blocks in default argument expression can never capture anything.
5028 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5029 // Set the "needs cleanups" bit regardless of whether there are
5030 // any explicit objects.
5031 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5032
5033 // Append all the objects to the cleanup list. Right now, this
5034 // should always be a no-op, because blocks in default argument
5035 // expressions should never be able to capture anything.
5036 assert(!Init->getNumObjects() &&((!Init->getNumObjects() && "default argument expression has capturing blocks?"
) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 5037, __PRETTY_FUNCTION__))
5037 "default argument expression has capturing blocks?")((!Init->getNumObjects() && "default argument expression has capturing blocks?"
) ? static_cast<void> (0) : __assert_fail ("!Init->getNumObjects() && \"default argument expression has capturing blocks?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 5037, __PRETTY_FUNCTION__))
;
5038 }
5039
5040 // We already type-checked the argument, so we know it works.
5041 // Just mark all of the declarations in this potentially-evaluated expression
5042 // as being "referenced".
5043 EnterExpressionEvaluationContext EvalContext(
5044 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5045 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5046 /*SkipLocalVariables=*/true);
5047 return false;
5048}
5049
5050ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5051 FunctionDecl *FD, ParmVarDecl *Param) {
5052 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5053 return ExprError();
5054 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5055}
5056
5057Sema::VariadicCallType
5058Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5059 Expr *Fn) {
5060 if (Proto && Proto->isVariadic()) {
5061 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5062 return VariadicConstructor;
5063 else if (Fn && Fn->getType()->isBlockPointerType())
5064 return VariadicBlock;
5065 else if (FDecl) {
5066 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5067 if (Method->isInstance())
5068 return VariadicMethod;
5069 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5070 return VariadicMethod;
5071 return VariadicFunction;
5072 }
5073 return VariadicDoesNotApply;
5074}
5075
5076namespace {
5077class FunctionCallCCC final : public FunctionCallFilterCCC {
5078public:
5079 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5080 unsigned NumArgs, MemberExpr *ME)
5081 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5082 FunctionName(FuncName) {}
5083
5084 bool ValidateCandidate(const TypoCorrection &candidate) override {
5085 if (!candidate.getCorrectionSpecifier() ||
5086 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5087 return false;
5088 }
5089
5090 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5091 }
5092
5093 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5094 return std::make_unique<FunctionCallCCC>(*this);
5095 }
5096
5097private:
5098 const IdentifierInfo *const FunctionName;
5099};
5100}
5101
5102static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5103 FunctionDecl *FDecl,
5104 ArrayRef<Expr *> Args) {
5105 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5106 DeclarationName FuncName = FDecl->getDeclName();
5107 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5108
5109 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5110 if (TypoCorrection Corrected = S.CorrectTypo(
5111 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5112 S.getScopeForContext(S.CurContext), nullptr, CCC,
5113 Sema::CTK_ErrorRecovery)) {
5114 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5115 if (Corrected.isOverloaded()) {
5116 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5117 OverloadCandidateSet::iterator Best;
5118 for (NamedDecl *CD : Corrected) {
5119 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5120 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5121 OCS);
5122 }
5123 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5124 case OR_Success:
5125 ND = Best->FoundDecl;
5126 Corrected.setCorrectionDecl(ND);
5127 break;
5128 default:
5129 break;
5130 }
5131 }
5132 ND = ND->getUnderlyingDecl();
5133 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5134 return Corrected;
5135 }
5136 }
5137 return TypoCorrection();
5138}
5139
5140/// ConvertArgumentsForCall - Converts the arguments specified in
5141/// Args/NumArgs to the parameter types of the function FDecl with
5142/// function prototype Proto. Call is the call expression itself, and
5143/// Fn is the function expression. For a C++ member function, this
5144/// routine does not attempt to convert the object argument. Returns
5145/// true if the call is ill-formed.
5146bool
5147Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5148 FunctionDecl *FDecl,
5149 const FunctionProtoType *Proto,
5150 ArrayRef<Expr *> Args,
5151 SourceLocation RParenLoc,
5152 bool IsExecConfig) {
5153 // Bail out early if calling a builtin with custom typechecking.
5154 if (FDecl)
5155 if (unsigned ID = FDecl->getBuiltinID())
5156 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5157 return false;
5158
5159 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5160 // assignment, to the types of the corresponding parameter, ...
5161 unsigned NumParams = Proto->getNumParams();
5162 bool Invalid = false;
5163 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5164 unsigned FnKind = Fn->getType()->isBlockPointerType()
5165 ? 1 /* block */
5166 : (IsExecConfig ? 3 /* kernel function (exec config) */
5167 : 0 /* function */);
5168
5169 // If too few arguments are available (and we don't have default
5170 // arguments for the remaining parameters), don't make the call.
5171 if (Args.size() < NumParams) {
5172 if (Args.size() < MinArgs) {
5173 TypoCorrection TC;
5174 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5175 unsigned diag_id =
5176 MinArgs == NumParams && !Proto->isVariadic()
5177 ? diag::err_typecheck_call_too_few_args_suggest
5178 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5179 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5180 << static_cast<unsigned>(Args.size())
5181 << TC.getCorrectionRange());
5182 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5183 Diag(RParenLoc,
5184 MinArgs == NumParams && !Proto->isVariadic()
5185 ? diag::err_typecheck_call_too_few_args_one
5186 : diag::err_typecheck_call_too_few_args_at_least_one)
5187 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5188 else
5189 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5190 ? diag::err_typecheck_call_too_few_args
5191 : diag::err_typecheck_call_too_few_args_at_least)
5192 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5193 << Fn->getSourceRange();
5194
5195 // Emit the location of the prototype.
5196 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5197 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5198
5199 return true;
5200 }
5201 // We reserve space for the default arguments when we create
5202 // the call expression, before calling ConvertArgumentsForCall.
5203 assert((Call->getNumArgs() == NumParams) &&(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!"
) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 5204, __PRETTY_FUNCTION__))
5204 "We should have reserved space for the default arguments before!")(((Call->getNumArgs() == NumParams) && "We should have reserved space for the default arguments before!"
) ? static_cast<void> (0) : __assert_fail ("(Call->getNumArgs() == NumParams) && \"We should have reserved space for the default arguments before!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 5204, __PRETTY_FUNCTION__))
;
5205 }
5206
5207 // If too many are passed and not variadic, error on the extras and drop
5208 // them.
5209 if (Args.size() > NumParams) {
5210 if (!Proto->isVariadic()) {
5211 TypoCorrection TC;
5212 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5213 unsigned diag_id =
5214 MinArgs == NumParams && !Proto->isVariadic()
5215 ? diag::err_typecheck_call_too_many_args_suggest
5216 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5217 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5218 << static_cast<unsigned>(Args.size())
5219 << TC.getCorrectionRange());
5220 } else if (NumParams == 1 && FDecl &&
5221 FDecl->getParamDecl(0)->getDeclName())
5222 Diag(Args[NumParams]->getBeginLoc(),
5223 MinArgs == NumParams
5224 ? diag::err_typecheck_call_too_many_args_one
5225 : diag::err_typecheck_call_too_many_args_at_most_one)
5226 << FnKind << FDecl->getParamDecl(0)
5227 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5228 << SourceRange(Args[NumParams]->getBeginLoc(),
5229 Args.back()->getEndLoc());
5230 else
5231 Diag(Args[NumParams]->getBeginLoc(),
5232 MinArgs == NumParams
5233 ? diag::err_typecheck_call_too_many_args
5234 : diag::err_typecheck_call_too_many_args_at_most)
5235 << FnKind << NumParams << static_cast<unsigned>(Args.size())
5236 << Fn->getSourceRange()
5237 << SourceRange(Args[NumParams]->getBeginLoc(),
5238 Args.back()->getEndLoc());
5239
5240 // Emit the location of the prototype.
5241 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5242 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5243
5244 // This deletes the extra arguments.
5245 Call->shrinkNumArgs(NumParams);
5246 return true;
5247 }
5248 }
5249 SmallVector<Expr *, 8> AllArgs;
5250 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5251
5252 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5253 AllArgs, CallType);
5254 if (Invalid)
5255 return true;
5256 unsigned TotalNumArgs = AllArgs.size();
5257 for (unsigned i = 0; i < TotalNumArgs; ++i)
5258 Call->setArg(i, AllArgs[i]);
5259
5260 return false;
5261}
5262
5263bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5264 const FunctionProtoType *Proto,
5265 unsigned FirstParam, ArrayRef<Expr *> Args,
5266 SmallVectorImpl<Expr *> &AllArgs,
5267 VariadicCallType CallType, bool AllowExplicit,
5268 bool IsListInitialization) {
5269 unsigned NumParams = Proto->getNumParams();
5270 bool Invalid = false;
5271 size_t ArgIx = 0;
5272 // Continue to check argument types (even if we have too few/many args).
5273 for (unsigned i = FirstParam; i < NumParams; i++) {
5274 QualType ProtoArgType = Proto->getParamType(i);
5275
5276 Expr *Arg;
5277 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5278 if (ArgIx < Args.size()) {
5279 Arg = Args[ArgIx++];
5280
5281 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5282 diag::err_call_incomplete_argument, Arg))
5283 return true;
5284
5285 // Strip the unbridged-cast placeholder expression off, if applicable.
5286 bool CFAudited = false;
5287 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5288 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5289 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5290 Arg = stripARCUnbridgedCast(Arg);
5291 else if (getLangOpts().ObjCAutoRefCount &&
5292 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5293 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5294 CFAudited = true;
5295
5296 if (Proto->getExtParameterInfo(i).isNoEscape())
5297 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5298 BE->getBlockDecl()->setDoesNotEscape();
5299
5300 InitializedEntity Entity =
5301 Param ? InitializedEntity::InitializeParameter(Context, Param,
5302 ProtoArgType)
5303 : InitializedEntity::InitializeParameter(
5304 Context, ProtoArgType, Proto->isParamConsumed(i));
5305
5306 // Remember that parameter belongs to a CF audited API.
5307 if (CFAudited)
5308 Entity.setParameterCFAudited();
5309
5310 ExprResult ArgE = PerformCopyInitialization(
5311 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5312 if (ArgE.isInvalid())
5313 return true;
5314
5315 Arg = ArgE.getAs<Expr>();
5316 } else {
5317 assert(Param && "can't use default arguments without a known callee")((Param && "can't use default arguments without a known callee"
) ? static_cast<void> (0) : __assert_fail ("Param && \"can't use default arguments without a known callee\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 5317, __PRETTY_FUNCTION__))
;
5318
5319 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5320 if (ArgExpr.isInvalid())
5321 return true;
5322
5323 Arg = ArgExpr.getAs<Expr>();
5324 }
5325
5326 // Check for array bounds violations for each argument to the call. This
5327 // check only triggers warnings when the argument isn't a more complex Expr
5328 // with its own checking, such as a BinaryOperator.
5329 CheckArrayAccess(Arg);
5330
5331 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5332 CheckStaticArrayArgument(CallLoc, Param, Arg);
5333
5334 AllArgs.push_back(Arg);
5335 }
5336
5337 // If this is a variadic call, handle args passed through "...".
5338 if (CallType != VariadicDoesNotApply) {
5339 // Assume that extern "C" functions with variadic arguments that
5340 // return __unknown_anytype aren't *really* variadic.
5341 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5342 FDecl->isExternC()) {
5343 for (Expr *A : Args.slice(ArgIx)) {
5344 QualType paramType; // ignored
5345 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5346 Invalid |= arg.isInvalid();
5347 AllArgs.push_back(arg.get());
5348 }
5349
5350 // Otherwise do argument promotion, (C99 6.5.2.2p7).
5351 } else {
5352 for (Expr *A : Args.slice(ArgIx)) {
5353 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5354 Invalid |= Arg.isInvalid();
5355 // Copy blocks to the heap.
5356 if (A->getType()->isBlockPointerType())
5357 maybeExtendBlockObject(Arg);
5358 AllArgs.push_back(Arg.get());
5359 }
5360 }
5361
5362 // Check for array bounds violations.
5363 for (Expr *A : Args.slice(ArgIx))
5364 CheckArrayAccess(A);
5365 }
5366 return Invalid;
5367}
5368
5369static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5370 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5371 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5372 TL = DTL.getOriginalLoc();
5373 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5374 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5375 << ATL.getLocalSourceRange();
5376}
5377
5378/// CheckStaticArrayArgument - If the given argument corresponds to a static
5379/// array parameter, check that it is non-null, and that if it is formed by
5380/// array-to-pointer decay, the underlying array is sufficiently large.
5381///
5382/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5383/// array type derivation, then for each call to the function, the value of the
5384/// corresponding actual argument shall provide access to the first element of
5385/// an array with at least as many elements as specified by the size expression.
5386void
5387Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5388 ParmVarDecl *Param,
5389 const Expr *ArgExpr) {
5390 // Static array parameters are not supported in C++.
5391 if (!Param || getLangOpts().CPlusPlus)
5392 return;
5393
5394 QualType OrigTy = Param->getOriginalType();
5395
5396 const ArrayType *AT = Context.getAsArrayType(OrigTy);
5397 if (!AT || AT->getSizeModifier() != ArrayType::Static)
5398 return;
5399
5400 if (ArgExpr->isNullPointerConstant(Context,
5401 Expr::NPC_NeverValueDependent)) {
5402 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5403 DiagnoseCalleeStaticArrayParam(*this, Param);
5404 return;
5405 }
5406
5407 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5408 if (!CAT)
5409 return;
5410
5411 const ConstantArrayType *ArgCAT =
5412 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5413 if (!ArgCAT)
5414 return;
5415
5416 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5417 ArgCAT->getElementType())) {
5418 if (ArgCAT->getSize().ult(CAT->getSize())) {
5419 Diag(CallLoc, diag::warn_static_array_too_small)
5420 << ArgExpr->getSourceRange()
5421 << (unsigned)ArgCAT->getSize().getZExtValue()
5422 << (unsigned)CAT->getSize().getZExtValue() << 0;
5423 DiagnoseCalleeStaticArrayParam(*this, Param);
5424 }
5425 return;
5426 }
5427
5428 Optional<CharUnits> ArgSize =
5429 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5430 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5431 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5432 Diag(CallLoc, diag::warn_static_array_too_small)
5433 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5434 << (unsigned)ParmSize->getQuantity() << 1;
5435 DiagnoseCalleeStaticArrayParam(*this, Param);
5436 }
5437}
5438
5439/// Given a function expression of unknown-any type, try to rebuild it
5440/// to have a function type.
5441static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5442
5443/// Is the given type a placeholder that we need to lower out
5444/// immediately during argument processing?
5445static bool isPlaceholderToRemoveAsArg(QualType type) {
5446 // Placeholders are never sugared.
5447 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5448 if (!placeholder) return false;
5449
5450 switch (placeholder->getKind()) {
5451 // Ignore all the non-placeholder types.
5452#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5453 case BuiltinType::Id:
5454#include "clang/Basic/OpenCLImageTypes.def"
5455#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5456 case BuiltinType::Id:
5457#include "clang/Basic/OpenCLExtensionTypes.def"
5458 // In practice we'll never use this, since all SVE types are sugared
5459 // via TypedefTypes rather than exposed directly as BuiltinTypes.
5460#define SVE_TYPE(Name, Id, SingletonId) \
5461 case BuiltinType::Id:
5462#include "clang/Basic/AArch64SVEACLETypes.def"
5463#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5464#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5465#include "clang/AST/BuiltinTypes.def"
5466 return false;
5467
5468 // We cannot lower out overload sets; they might validly be resolved
5469 // by the call machinery.
5470 case BuiltinType::Overload:
5471 return false;
5472
5473 // Unbridged casts in ARC can be handled in some call positions and
5474 // should be left in place.
5475 case BuiltinType::ARCUnbridgedCast:
5476 return false;
5477
5478 // Pseudo-objects should be converted as soon as possible.
5479 case BuiltinType::PseudoObject:
5480 return true;
5481
5482 // The debugger mode could theoretically but currently does not try
5483 // to resolve unknown-typed arguments based on known parameter types.
5484 case BuiltinType::UnknownAny:
5485 return true;
5486
5487 // These are always invalid as call arguments and should be reported.
5488 case BuiltinType::BoundMember:
5489 case BuiltinType::BuiltinFn:
5490 case BuiltinType::OMPArraySection:
5491 return true;
5492
5493 }
5494 llvm_unreachable("bad builtin type kind")::llvm::llvm_unreachable_internal("bad builtin type kind", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 5494)
;
5495}
5496
5497/// Check an argument list for placeholders that we won't try to
5498/// handle later.
5499static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5500 // Apply this processing to all the arguments at once instead of
5501 // dying at the first failure.
5502 bool hasInvalid = false;
5503 for (size_t i = 0, e = args.size(); i != e; i++) {
5504 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5505 ExprResult result = S.CheckPlaceholderExpr(args[i]);
5506 if (result.isInvalid()) hasInvalid = true;
5507 else args[i] = result.get();
5508 } else if (hasInvalid) {
5509 (void)S.CorrectDelayedTyposInExpr(args[i]);
5510 }
5511 }
5512 return hasInvalid;
5513}
5514
5515/// If a builtin function has a pointer argument with no explicit address
5516/// space, then it should be able to accept a pointer to any address
5517/// space as input. In order to do this, we need to replace the
5518/// standard builtin declaration with one that uses the same address space
5519/// as the call.
5520///
5521/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5522/// it does not contain any pointer arguments without
5523/// an address space qualifer. Otherwise the rewritten
5524/// FunctionDecl is returned.
5525/// TODO: Handle pointer return types.
5526static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5527 FunctionDecl *FDecl,
5528 MultiExprArg ArgExprs) {
5529
5530 QualType DeclType = FDecl->getType();
5531 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5532
5533 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
5534 ArgExprs.size() < FT->getNumParams())
5535 return nullptr;
5536
5537 bool NeedsNewDecl = false;
5538 unsigned i = 0;
5539 SmallVector<QualType, 8> OverloadParams;
5540
5541 for (QualType ParamType : FT->param_types()) {
5542
5543 // Convert array arguments to pointer to simplify type lookup.
5544 ExprResult ArgRes =
5545 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5546 if (ArgRes.isInvalid())
5547 return nullptr;
5548 Expr *Arg = ArgRes.get();
5549 QualType ArgType = Arg->getType();
5550 if (!ParamType->isPointerType() ||
5551 ParamType.hasAddressSpace() ||
5552 !ArgType->isPointerType() ||
5553 !ArgType->getPointeeType().hasAddressSpace()) {
5554 OverloadParams.push_back(ParamType);
5555 continue;
5556 }
5557
5558 QualType PointeeType = ParamType->getPointeeType();
5559 if (PointeeType.hasAddressSpace())
5560 continue;
5561
5562 NeedsNewDecl = true;
5563 LangAS AS = ArgType->getPointeeType().getAddressSpace();
5564
5565 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5566 OverloadParams.push_back(Context.getPointerType(PointeeType));
5567 }
5568
5569 if (!NeedsNewDecl)
5570 return nullptr;
5571
5572 FunctionProtoType::ExtProtoInfo EPI;
5573 EPI.Variadic = FT->isVariadic();
5574 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5575 OverloadParams, EPI);
5576 DeclContext *Parent = FDecl->getParent();
5577 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5578 FDecl->getLocation(),
5579 FDecl->getLocation(),
5580 FDecl->getIdentifier(),
5581 OverloadTy,
5582 /*TInfo=*/nullptr,
5583 SC_Extern, false,
5584 /*hasPrototype=*/true);
5585 SmallVector<ParmVarDecl*, 16> Params;
5586 FT = cast<FunctionProtoType>(OverloadTy);
5587 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5588 QualType ParamType = FT->getParamType(i);
5589 ParmVarDecl *Parm =
5590 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5591 SourceLocation(), nullptr, ParamType,
5592 /*TInfo=*/nullptr, SC_None, nullptr);
5593 Parm->setScopeInfo(0, i);
5594 Params.push_back(Parm);
5595 }
5596 OverloadDecl->setParams(Params);
5597 return OverloadDecl;
5598}
5599
5600static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5601 FunctionDecl *Callee,
5602 MultiExprArg ArgExprs) {
5603 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5604 // similar attributes) really don't like it when functions are called with an
5605 // invalid number of args.
5606 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5607 /*PartialOverloading=*/false) &&
5608 !Callee->isVariadic())
5609 return;
5610 if (Callee->getMinRequiredArguments() > ArgExprs.size())
5611 return;
5612
5613 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5614 S.Diag(Fn->getBeginLoc(),
5615 isa<CXXMethodDecl>(Callee)
5616 ? diag::err_ovl_no_viable_member_function_in_call
5617 : diag::err_ovl_no_viable_function_in_call)
5618 << Callee << Callee->getSourceRange();
5619 S.Diag(Callee->getLocation(),
5620 diag::note_ovl_candidate_disabled_by_function_cond_attr)
5621 << Attr->getCond()->getSourceRange() << Attr->getMessage();
5622 return;
5623 }
5624}
5625
5626static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5627 const UnresolvedMemberExpr *const UME, Sema &S) {
5628
5629 const auto GetFunctionLevelDCIfCXXClass =
5630 [](Sema &S) -> const CXXRecordDecl * {
5631 const DeclContext *const DC = S.getFunctionLevelDeclContext();
5632 if (!DC || !DC->getParent())
5633 return nullptr;
5634
5635 // If the call to some member function was made from within a member
5636 // function body 'M' return return 'M's parent.
5637 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5638 return MD->getParent()->getCanonicalDecl();
5639 // else the call was made from within a default member initializer of a
5640 // class, so return the class.
5641 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5642 return RD->getCanonicalDecl();
5643 return nullptr;
5644 };
5645 // If our DeclContext is neither a member function nor a class (in the
5646 // case of a lambda in a default member initializer), we can't have an
5647 // enclosing 'this'.
5648
5649 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5650 if (!CurParentClass)
5651 return false;
5652
5653 // The naming class for implicit member functions call is the class in which
5654 // name lookup starts.
5655 const CXXRecordDecl *const NamingClass =
5656 UME->getNamingClass()->getCanonicalDecl();
5657 assert(NamingClass && "Must have naming class even for implicit access")((NamingClass && "Must have naming class even for implicit access"
) ? static_cast<void> (0) : __assert_fail ("NamingClass && \"Must have naming class even for implicit access\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 5657, __PRETTY_FUNCTION__))
;
5658
5659 // If the unresolved member functions were found in a 'naming class' that is
5660 // related (either the same or derived from) to the class that contains the
5661 // member function that itself contained the implicit member access.
5662
5663 return CurParentClass == NamingClass ||
5664 CurParentClass->isDerivedFrom(NamingClass);
5665}
5666
5667static void
5668tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5669 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5670
5671 if (!UME)
5672 return;
5673
5674 LambdaScopeInfo *const CurLSI = S.getCurLambda();
5675 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5676 // already been captured, or if this is an implicit member function call (if
5677 // it isn't, an attempt to capture 'this' should already have been made).
5678 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5679 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5680 return;
5681
5682 // Check if the naming class in which the unresolved members were found is
5683 // related (same as or is a base of) to the enclosing class.
5684
5685 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5686 return;
5687
5688
5689 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5690 // If the enclosing function is not dependent, then this lambda is
5691 // capture ready, so if we can capture this, do so.
5692 if (!EnclosingFunctionCtx->isDependentContext()) {
5693 // If the current lambda and all enclosing lambdas can capture 'this' -
5694 // then go ahead and capture 'this' (since our unresolved overload set
5695 // contains at least one non-static member function).
5696 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5697 S.CheckCXXThisCapture(CallLoc);
5698 } else if (S.CurContext->isDependentContext()) {
5699 // ... since this is an implicit member reference, that might potentially
5700 // involve a 'this' capture, mark 'this' for potential capture in
5701 // enclosing lambdas.
5702 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5703 CurLSI->addPotentialThisCapture(CallLoc);
5704 }
5705}
5706
5707ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5708 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5709 Expr *ExecConfig) {
5710 ExprResult Call =
5711 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
5712 if (Call.isInvalid())
5713 return Call;
5714
5715 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
5716 // language modes.
5717 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
5718 if (ULE->hasExplicitTemplateArgs() &&
5719 ULE->decls_begin() == ULE->decls_end()) {
5720 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus2a
5721 ? diag::warn_cxx17_compat_adl_only_template_id
5722 : diag::ext_adl_only_template_id)
5723 << ULE->getName();
5724 }
5725 }
5726
5727 return Call;
5728}
5729
5730/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
5731/// This provides the location of the left/right parens and a list of comma
5732/// locations.
5733ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5734 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5735 Expr *ExecConfig, bool IsExecConfig) {
5736 // Since this might be a postfix expression, get rid of ParenListExprs.
5737 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5738 if (Result.isInvalid()) return ExprError();
5739 Fn = Result.get();
5740
5741 if (checkArgsForPlaceholders(*this, ArgExprs))
5742 return ExprError();
5743
5744 if (getLangOpts().CPlusPlus) {
5745 // If this is a pseudo-destructor expression, build the call immediately.
5746 if (isa<CXXPseudoDestructorExpr>(Fn)) {
5747 if (!ArgExprs.empty()) {
5748 // Pseudo-destructor calls should not have any arguments.
5749 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5750 << FixItHint::CreateRemoval(
5751 SourceRange(ArgExprs.front()->getBeginLoc(),
5752 ArgExprs.back()->getEndLoc()));
5753 }
5754
5755 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5756 VK_RValue, RParenLoc);
5757 }
5758 if (Fn->getType() == Context.PseudoObjectTy) {
5759 ExprResult result = CheckPlaceholderExpr(Fn);
5760 if (result.isInvalid()) return ExprError();
5761 Fn = result.get();
5762 }
5763
5764 // Determine whether this is a dependent call inside a C++ template,
5765 // in which case we won't do any semantic analysis now.
5766 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5767 if (ExecConfig) {
5768 return CUDAKernelCallExpr::Create(
5769 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5770 Context.DependentTy, VK_RValue, RParenLoc);
5771 } else {
5772
5773 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5774 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5775 Fn->getBeginLoc());
5776
5777 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5778 VK_RValue, RParenLoc);
5779 }
5780 }
5781
5782 // Determine whether this is a call to an object (C++ [over.call.object]).
5783 if (Fn->getType()->isRecordType())
5784 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5785 RParenLoc);
5786
5787 if (Fn->getType() == Context.UnknownAnyTy) {
5788 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5789 if (result.isInvalid()) return ExprError();
5790 Fn = result.get();
5791 }
5792
5793 if (Fn->getType() == Context.BoundMemberTy) {
5794 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5795 RParenLoc);
5796 }
5797 }
5798
5799 // Check for overloaded calls. This can happen even in C due to extensions.
5800 if (Fn->getType() == Context.OverloadTy) {
5801 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5802
5803 // We aren't supposed to apply this logic if there's an '&' involved.
5804 if (!find.HasFormOfMemberPointer) {
5805 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5806 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5807 VK_RValue, RParenLoc);
5808 OverloadExpr *ovl = find.Expression;
5809 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5810 return BuildOverloadedCallExpr(
5811 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5812 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5813 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5814 RParenLoc);
5815 }
5816 }
5817
5818 // If we're directly calling a function, get the appropriate declaration.
5819 if (Fn->getType() == Context.UnknownAnyTy) {
5820 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5821 if (result.isInvalid()) return ExprError();
5822 Fn = result.get();
5823 }
5824
5825 Expr *NakedFn = Fn->IgnoreParens();
5826
5827 bool CallingNDeclIndirectly = false;
5828 NamedDecl *NDecl = nullptr;
5829 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5830 if (UnOp->getOpcode() == UO_AddrOf) {
5831 CallingNDeclIndirectly = true;
5832 NakedFn = UnOp->getSubExpr()->IgnoreParens();
5833 }
5834 }
5835
5836 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
5837 NDecl = DRE->getDecl();
5838
5839 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5840 if (FDecl && FDecl->getBuiltinID()) {
5841 // Rewrite the function decl for this builtin by replacing parameters
5842 // with no explicit address space with the address space of the arguments
5843 // in ArgExprs.
5844 if ((FDecl =
5845 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5846 NDecl = FDecl;
5847 Fn = DeclRefExpr::Create(
5848 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5849 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
5850 nullptr, DRE->isNonOdrUse());
5851 }
5852 }
5853 } else if (isa<MemberExpr>(NakedFn))
5854 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5855
5856 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5857 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5858 FD, /*Complain=*/true, Fn->getBeginLoc()))
5859 return ExprError();
5860
5861 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5862 return ExprError();
5863
5864 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5865 }
5866
5867 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5868 ExecConfig, IsExecConfig);
5869}
5870
5871/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5872///
5873/// __builtin_astype( value, dst type )
5874///
5875ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5876 SourceLocation BuiltinLoc,
5877 SourceLocation RParenLoc) {
5878 ExprValueKind VK = VK_RValue;
5879 ExprObjectKind OK = OK_Ordinary;
5880 QualType DstTy = GetTypeFromParser(ParsedDestTy);
5881 QualType SrcTy = E->getType();
5882 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5883 return ExprError(Diag(BuiltinLoc,
5884 diag::err_invalid_astype_of_different_size)
5885 << DstTy
5886 << SrcTy
5887 << E->getSourceRange());
5888 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5889}
5890
5891/// ActOnConvertVectorExpr - create a new convert-vector expression from the
5892/// provided arguments.
5893///
5894/// __builtin_convertvector( value, dst type )
5895///
5896ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5897 SourceLocation BuiltinLoc,
5898 SourceLocation RParenLoc) {
5899 TypeSourceInfo *TInfo;
5900 GetTypeFromParser(ParsedDestTy, &TInfo);
5901 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5902}
5903
5904/// BuildResolvedCallExpr - Build a call to a resolved expression,
5905/// i.e. an expression not of \p OverloadTy. The expression should
5906/// unary-convert to an expression of function-pointer or
5907/// block-pointer type.
5908///
5909/// \param NDecl the declaration being called, if available
5910ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5911 SourceLocation LParenLoc,
5912 ArrayRef<Expr *> Args,
5913 SourceLocation RParenLoc, Expr *Config,
5914 bool IsExecConfig, ADLCallKind UsesADL) {
5915 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
1
Assuming null pointer is passed into cast
5916 unsigned BuiltinID = (FDecl
1.1
'FDecl' is null
? FDecl->getBuiltinID() : 0);
2
'?' condition is false
5917
5918 // Functions with 'interrupt' attribute cannot be called directly.
5919 if (FDecl
2.1
'FDecl' is null
&& FDecl->hasAttr<AnyX86InterruptAttr>()) {
5920 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5921 return ExprError();
5922 }
5923
5924 // Interrupt handlers don't save off the VFP regs automatically on ARM,
5925 // so there's some risk when calling out to non-interrupt handler functions
5926 // that the callee might not preserve them. This is easy to diagnose here,
5927 // but can be very challenging to debug.
5928 if (auto *Caller = getCurFunctionDecl())
3
Assuming 'Caller' is null
4
Taking false branch
5929 if (Caller->hasAttr<ARMInterruptAttr>()) {
5930 bool VFP = Context.getTargetInfo().hasFeature("vfp");
5931 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5932 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5933 }
5934
5935 // Promote the function operand.
5936 // We special-case function promotion here because we only allow promoting
5937 // builtin functions to function pointers in the callee of a call.
5938 ExprResult Result;
5939 QualType ResultTy;
5940 if (BuiltinID
4.1
'BuiltinID' is 0
&&
5
Taking false branch
5941 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5942 // Extract the return type from the (builtin) function pointer type.
5943 // FIXME Several builtins still have setType in
5944 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5945 // Builtins.def to ensure they are correct before removing setType calls.
5946 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5947 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5948 ResultTy = FDecl->getCallResultType();
5949 } else {
5950 Result = CallExprUnaryConversions(Fn);
5951 ResultTy = Context.BoolTy;
5952 }
5953 if (Result.isInvalid())
6
Assuming the condition is false
7
Taking false branch
5954 return ExprError();
5955 Fn = Result.get();
5956
5957 // Check for a valid function type, but only if it is not a builtin which
5958 // requires custom type checking. These will be handled by
5959 // CheckBuiltinFunctionCall below just after creation of the call expression.
5960 const FunctionType *FuncT = nullptr;
5961 if (!BuiltinID
7.1
'BuiltinID' is 0
|| !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5962 retry:
5963 if (const PointerType *PT
8.1
'PT' is null
= Fn->getType()->getAs<PointerType>()) {
8
Assuming the object is not a 'PointerType'
9
Taking false branch
5964 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5965 // have type pointer to function".
5966 FuncT = PT->getPointeeType()->getAs<FunctionType>();
5967 if (!FuncT)
5968 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5969 << Fn->getType() << Fn->getSourceRange());
5970 } else if (const BlockPointerType *BPT =
11
Assuming 'BPT' is non-null
12
Taking true branch
5971 Fn->getType()->getAs<BlockPointerType>()) {
10
Assuming the object is a 'BlockPointerType'
5972 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
13
The object is a 'FunctionType'
14
Value assigned to 'FuncT'
5973 } else {
5974 // Handle calls to expressions of unknown-any type.
5975 if (Fn->getType() == Context.UnknownAnyTy) {
5976 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5977 if (rewrite.isInvalid())
5978 return ExprError();
5979 Fn = rewrite.get();
5980 goto retry;
5981 }
5982
5983 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5984 << Fn->getType() << Fn->getSourceRange());
5985 }
5986 }
5987
5988 // Get the number of parameters in the function prototype, if any.
5989 // We will allocate space for max(Args.size(), NumParams) arguments
5990 // in the call expression.
5991 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
15
Assuming null pointer is passed into cast
16
Assuming pointer value is null
5992 unsigned NumParams = Proto
16.1
'Proto' is null
? Proto->getNumParams() : 0;
17
'?' condition is false
5993
5994 CallExpr *TheCall;
5995 if (Config) {
18
Assuming 'Config' is null
19
Taking false branch
5996 assert(UsesADL == ADLCallKind::NotADL &&((UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL"
) ? static_cast<void> (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 5997, __PRETTY_FUNCTION__))
5997 "CUDAKernelCallExpr should not use ADL")((UsesADL == ADLCallKind::NotADL && "CUDAKernelCallExpr should not use ADL"
) ? static_cast<void> (0) : __assert_fail ("UsesADL == ADLCallKind::NotADL && \"CUDAKernelCallExpr should not use ADL\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 5997, __PRETTY_FUNCTION__))
;
5998 TheCall =
5999 CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
6000 ResultTy, VK_RValue, RParenLoc, NumParams);
6001 } else {
6002 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6003 RParenLoc, NumParams, UsesADL);
6004 }
6005
6006 if (!getLangOpts().CPlusPlus) {
20
Assuming field 'CPlusPlus' is not equal to 0
21
Taking false branch
6007 // Forget about the nulled arguments since typo correction
6008 // do not handle them well.
6009 TheCall->shrinkNumArgs(Args.size());
6010 // C cannot always handle TypoExpr nodes in builtin calls and direct
6011 // function calls as their argument checking don't necessarily handle
6012 // dependent types properly, so make sure any TypoExprs have been
6013 // dealt with.
6014 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6015 if (!Result.isUsable()) return ExprError();
6016 CallExpr *TheOldCall = TheCall;
6017 TheCall = dyn_cast<CallExpr>(Result.get());
6018 bool CorrectedTypos = TheCall != TheOldCall;
6019 if (!TheCall) return Result;
6020 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6021
6022 // A new call expression node was created if some typos were corrected.
6023 // However it may not have been constructed with enough storage. In this
6024 // case, rebuild the node with enough storage. The waste of space is
6025 // immaterial since this only happens when some typos were corrected.
6026 if (CorrectedTypos && Args.size() < NumParams) {
6027 if (Config)
6028 TheCall = CUDAKernelCallExpr::Create(
6029 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6030 RParenLoc, NumParams);
6031 else
6032 TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
6033 RParenLoc, NumParams, UsesADL);
6034 }
6035 // We can now handle the nulled arguments for the default arguments.
6036 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6037 }
6038
6039 // Bail out early if calling a builtin with custom type checking.
6040 if (BuiltinID
21.1
'BuiltinID' is 0
&& Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6041 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6042
6043 if (getLangOpts().CUDA) {
22
Assuming field 'CUDA' is 0
23
Taking false branch
6044 if (Config) {
6045 // CUDA: Kernel calls must be to global functions
6046 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6047 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6048 << FDecl << Fn->getSourceRange());
6049
6050 // CUDA: Kernel function must have 'void' return type
6051 if (!FuncT->getReturnType()->isVoidType() &&
6052 !FuncT->getReturnType()->getAs<AutoType>() &&
6053 !FuncT->getReturnType()->isInstantiationDependentType())
6054 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6055 << Fn->getType() << Fn->getSourceRange());
6056 } else {
6057 // CUDA: Calls to global functions must be configured
6058 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6059 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6060 << FDecl << Fn->getSourceRange());
6061 }
6062 }
6063
6064 // Check for a valid return type
6065 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
24
Called C++ object pointer is null
6066 FDecl))
6067 return ExprError();
6068
6069 // We know the result type of the call, set it.
6070 TheCall->setType(FuncT->getCallResultType(Context));
6071 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6072
6073 if (Proto) {
6074 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6075 IsExecConfig))
6076 return ExprError();
6077 } else {
6078 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!")((isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!"
) ? static_cast<void> (0) : __assert_fail ("isa<FunctionNoProtoType>(FuncT) && \"Unknown FunctionType!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6078, __PRETTY_FUNCTION__))
;
6079
6080 if (FDecl) {
6081 // Check if we have too few/too many template arguments, based
6082 // on our knowledge of the function definition.
6083 const FunctionDecl *Def = nullptr;
6084 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6085 Proto = Def->getType()->getAs<FunctionProtoType>();
6086 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6087 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6088 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6089 }
6090
6091 // If the function we're calling isn't a function prototype, but we have
6092 // a function prototype from a prior declaratiom, use that prototype.
6093 if (!FDecl->hasPrototype())
6094 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6095 }
6096
6097 // Promote the arguments (C99 6.5.2.2p6).
6098 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6099 Expr *Arg = Args[i];
6100
6101 if (Proto && i < Proto->getNumParams()) {
6102 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6103 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6104 ExprResult ArgE =
6105 PerformCopyInitialization(Entity, SourceLocation(), Arg);
6106 if (ArgE.isInvalid())
6107 return true;
6108
6109 Arg = ArgE.getAs<Expr>();
6110
6111 } else {
6112 ExprResult ArgE = DefaultArgumentPromotion(Arg);
6113
6114 if (ArgE.isInvalid())
6115 return true;
6116
6117 Arg = ArgE.getAs<Expr>();
6118 }
6119
6120 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6121 diag::err_call_incomplete_argument, Arg))
6122 return ExprError();
6123
6124 TheCall->setArg(i, Arg);
6125 }
6126 }
6127
6128 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6129 if (!Method->isStatic())
6130 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6131 << Fn->getSourceRange());
6132
6133 // Check for sentinels
6134 if (NDecl)
6135 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6136
6137 // Do special checking on direct calls to functions.
6138 if (FDecl) {
6139 if (CheckFunctionCall(FDecl, TheCall, Proto))
6140 return ExprError();
6141
6142 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6143
6144 if (BuiltinID)
6145 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6146 } else if (NDecl) {
6147 if (CheckPointerCall(NDecl, TheCall, Proto))
6148 return ExprError();
6149 } else {
6150 if (CheckOtherCall(TheCall, Proto))
6151 return ExprError();
6152 }
6153
6154 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6155}
6156
6157ExprResult
6158Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6159 SourceLocation RParenLoc, Expr *InitExpr) {
6160 assert(Ty && "ActOnCompoundLiteral(): missing type")((Ty && "ActOnCompoundLiteral(): missing type") ? static_cast
<void> (0) : __assert_fail ("Ty && \"ActOnCompoundLiteral(): missing type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6160, __PRETTY_FUNCTION__))
;
6161 assert(InitExpr && "ActOnCompoundLiteral(): missing expression")((InitExpr && "ActOnCompoundLiteral(): missing expression"
) ? static_cast<void> (0) : __assert_fail ("InitExpr && \"ActOnCompoundLiteral(): missing expression\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6161, __PRETTY_FUNCTION__))
;
6162
6163 TypeSourceInfo *TInfo;
6164 QualType literalType = GetTypeFromParser(Ty, &TInfo);
6165 if (!TInfo)
6166 TInfo = Context.getTrivialTypeSourceInfo(literalType);
6167
6168 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6169}
6170
6171ExprResult
6172Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6173 SourceLocation RParenLoc, Expr *LiteralExpr) {
6174 QualType literalType = TInfo->getType();
6175
6176 if (literalType->isArrayType()) {
6177 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
6178 diag::err_illegal_decl_array_incomplete_type,
6179 SourceRange(LParenLoc,
6180 LiteralExpr->getSourceRange().getEnd())))
6181 return ExprError();
6182 if (literalType->isVariableArrayType())
6183 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6184 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6185 } else if (!literalType->isDependentType() &&
6186 RequireCompleteType(LParenLoc, literalType,
6187 diag::err_typecheck_decl_incomplete_type,
6188 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6189 return ExprError();
6190
6191 InitializedEntity Entity
6192 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6193 InitializationKind Kind
6194 = InitializationKind::CreateCStyleCast(LParenLoc,
6195 SourceRange(LParenLoc, RParenLoc),
6196 /*InitList=*/true);
6197 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6198 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6199 &literalType);
6200 if (Result.isInvalid())
6201 return ExprError();
6202 LiteralExpr = Result.get();
6203
6204 bool isFileScope = !CurContext->isFunctionOrMethod();
6205
6206 // In C, compound literals are l-values for some reason.
6207 // For GCC compatibility, in C++, file-scope array compound literals with
6208 // constant initializers are also l-values, and compound literals are
6209 // otherwise prvalues.
6210 //
6211 // (GCC also treats C++ list-initialized file-scope array prvalues with
6212 // constant initializers as l-values, but that's non-conforming, so we don't
6213 // follow it there.)
6214 //
6215 // FIXME: It would be better to handle the lvalue cases as materializing and
6216 // lifetime-extending a temporary object, but our materialized temporaries
6217 // representation only supports lifetime extension from a variable, not "out
6218 // of thin air".
6219 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6220 // is bound to the result of applying array-to-pointer decay to the compound
6221 // literal.
6222 // FIXME: GCC supports compound literals of reference type, which should
6223 // obviously have a value kind derived from the kind of reference involved.
6224 ExprValueKind VK =
6225 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6226 ? VK_RValue
6227 : VK_LValue;
6228
6229 if (isFileScope)
6230 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6231 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6232 Expr *Init = ILE->getInit(i);
6233 ILE->setInit(i, ConstantExpr::Create(Context, Init));
6234 }
6235
6236 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6237 VK, LiteralExpr, isFileScope);
6238 if (isFileScope) {
6239 if (!LiteralExpr->isTypeDependent() &&
6240 !LiteralExpr->isValueDependent() &&
6241 !literalType->isDependentType()) // C99 6.5.2.5p3
6242 if (CheckForConstantInitializer(LiteralExpr, literalType))
6243 return ExprError();
6244 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6245 literalType.getAddressSpace() != LangAS::Default) {
6246 // Embedded-C extensions to C99 6.5.2.5:
6247 // "If the compound literal occurs inside the body of a function, the
6248 // type name shall not be qualified by an address-space qualifier."
6249 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6250 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6251 return ExprError();
6252 }
6253
6254 // Compound literals that have automatic storage duration are destroyed at
6255 // the end of the scope. Emit diagnostics if it is or contains a C union type
6256 // that is non-trivial to destruct.
6257 if (!isFileScope)
6258 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6259 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6260 NTCUC_CompoundLiteral, NTCUK_Destruct);
6261
6262 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6263 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6264 checkNonTrivialCUnionInInitializer(E->getInitializer(),
6265 E->getInitializer()->getExprLoc());
6266
6267 return MaybeBindToTemporary(E);
6268}
6269
6270ExprResult
6271Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6272 SourceLocation RBraceLoc) {
6273 // Only produce each kind of designated initialization diagnostic once.
6274 SourceLocation FirstDesignator;
6275 bool DiagnosedArrayDesignator = false;
6276 bool DiagnosedNestedDesignator = false;
6277 bool DiagnosedMixedDesignator = false;
6278
6279 // Check that any designated initializers are syntactically valid in the
6280 // current language mode.
6281 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6282 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6283 if (FirstDesignator.isInvalid())
6284 FirstDesignator = DIE->getBeginLoc();
6285
6286 if (!getLangOpts().CPlusPlus)
6287 break;
6288
6289 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6290 DiagnosedNestedDesignator = true;
6291 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6292 << DIE->getDesignatorsSourceRange();
6293 }
6294
6295 for (auto &Desig : DIE->designators()) {
6296 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6297 DiagnosedArrayDesignator = true;
6298 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6299 << Desig.getSourceRange();
6300 }
6301 }
6302
6303 if (!DiagnosedMixedDesignator &&
6304 !isa<DesignatedInitExpr>(InitArgList[0])) {
6305 DiagnosedMixedDesignator = true;
6306 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6307 << DIE->getSourceRange();
6308 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6309 << InitArgList[0]->getSourceRange();
6310 }
6311 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6312 isa<DesignatedInitExpr>(InitArgList[0])) {
6313 DiagnosedMixedDesignator = true;
6314 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6315 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6316 << DIE->getSourceRange();
6317 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6318 << InitArgList[I]->getSourceRange();
6319 }
6320 }
6321
6322 if (FirstDesignator.isValid()) {
6323 // Only diagnose designated initiaization as a C++20 extension if we didn't
6324 // already diagnose use of (non-C++20) C99 designator syntax.
6325 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6326 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6327 Diag(FirstDesignator, getLangOpts().CPlusPlus2a
6328 ? diag::warn_cxx17_compat_designated_init
6329 : diag::ext_cxx_designated_init);
6330 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6331 Diag(FirstDesignator, diag::ext_designated_init);
6332 }
6333 }
6334
6335 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6336}
6337
6338ExprResult
6339Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6340 SourceLocation RBraceLoc) {
6341 // Semantic analysis for initializers is done by ActOnDeclarator() and
6342 // CheckInitializer() - it requires knowledge of the object being initialized.
6343
6344 // Immediately handle non-overload placeholders. Overloads can be
6345 // resolved contextually, but everything else here can't.
6346 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6347 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6348 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6349
6350 // Ignore failures; dropping the entire initializer list because
6351 // of one failure would be terrible for indexing/etc.
6352 if (result.isInvalid()) continue;
6353
6354 InitArgList[I] = result.get();
6355 }
6356 }
6357
6358 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6359 RBraceLoc);
6360 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6361 return E;
6362}
6363
6364/// Do an explicit extend of the given block pointer if we're in ARC.
6365void Sema::maybeExtendBlockObject(ExprResult &E) {
6366 assert(E.get()->getType()->isBlockPointerType())((E.get()->getType()->isBlockPointerType()) ? static_cast
<void> (0) : __assert_fail ("E.get()->getType()->isBlockPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6366, __PRETTY_FUNCTION__))
;
6367 assert(E.get()->isRValue())((E.get()->isRValue()) ? static_cast<void> (0) : __assert_fail
("E.get()->isRValue()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6367, __PRETTY_FUNCTION__))
;
6368
6369 // Only do this in an r-value context.
6370 if (!getLangOpts().ObjCAutoRefCount) return;
6371
6372 E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6373 CK_ARCExtendBlockObject, E.get(),
6374 /*base path*/ nullptr, VK_RValue);
6375 Cleanup.setExprNeedsCleanups(true);
6376}
6377
6378/// Prepare a conversion of the given expression to an ObjC object
6379/// pointer type.
6380CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6381 QualType type = E.get()->getType();
6382 if (type->isObjCObjectPointerType()) {
6383 return CK_BitCast;
6384 } else if (type->isBlockPointerType()) {
6385 maybeExtendBlockObject(E);
6386 return CK_BlockPointerToObjCPointerCast;
6387 } else {
6388 assert(type->isPointerType())((type->isPointerType()) ? static_cast<void> (0) : __assert_fail
("type->isPointerType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6388, __PRETTY_FUNCTION__))
;
6389 return CK_CPointerToObjCPointerCast;
6390 }
6391}
6392
6393/// Prepares for a scalar cast, performing all the necessary stages
6394/// except the final cast and returning the kind required.
6395CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6396 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6397 // Also, callers should have filtered out the invalid cases with
6398 // pointers. Everything else should be possible.
6399
6400 QualType SrcTy = Src.get()->getType();
6401 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6402 return CK_NoOp;
6403
6404 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6405 case Type::STK_MemberPointer:
6406 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6406)
;
6407
6408 case Type::STK_CPointer:
6409 case Type::STK_BlockPointer:
6410 case Type::STK_ObjCObjectPointer:
6411 switch (DestTy->getScalarTypeKind()) {
6412 case Type::STK_CPointer: {
6413 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6414 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6415 if (SrcAS != DestAS)
6416 return CK_AddressSpaceConversion;
6417 if (Context.hasCvrSimilarType(SrcTy, DestTy))
6418 return CK_NoOp;
6419 return CK_BitCast;
6420 }
6421 case Type::STK_BlockPointer:
6422 return (SrcKind == Type::STK_BlockPointer
6423 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6424 case Type::STK_ObjCObjectPointer:
6425 if (SrcKind == Type::STK_ObjCObjectPointer)
6426 return CK_BitCast;
6427 if (SrcKind == Type::STK_CPointer)
6428 return CK_CPointerToObjCPointerCast;
6429 maybeExtendBlockObject(Src);
6430 return CK_BlockPointerToObjCPointerCast;
6431 case Type::STK_Bool:
6432 return CK_PointerToBoolean;
6433 case Type::STK_Integral:
6434 return CK_PointerToIntegral;
6435 case Type::STK_Floating:
6436 case Type::STK_FloatingComplex:
6437 case Type::STK_IntegralComplex:
6438 case Type::STK_MemberPointer:
6439 case Type::STK_FixedPoint:
6440 llvm_unreachable("illegal cast from pointer")::llvm::llvm_unreachable_internal("illegal cast from pointer"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6440)
;
6441 }
6442 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6442)
;
6443
6444 case Type::STK_FixedPoint:
6445 switch (DestTy->getScalarTypeKind()) {
6446 case Type::STK_FixedPoint:
6447 return CK_FixedPointCast;
6448 case Type::STK_Bool:
6449 return CK_FixedPointToBoolean;
6450 case Type::STK_Integral:
6451 return CK_FixedPointToIntegral;
6452 case Type::STK_Floating:
6453 case Type::STK_IntegralComplex:
6454 case Type::STK_FloatingComplex:
6455 Diag(Src.get()->getExprLoc(),
6456 diag::err_unimplemented_conversion_with_fixed_point_type)
6457 << DestTy;
6458 return CK_IntegralCast;
6459 case Type::STK_CPointer:
6460 case Type::STK_ObjCObjectPointer:
6461 case Type::STK_BlockPointer:
6462 case Type::STK_MemberPointer:
6463 llvm_unreachable("illegal cast to pointer type")::llvm::llvm_unreachable_internal("illegal cast to pointer type"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6463)
;
6464 }
6465 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6465)
;
6466
6467 case Type::STK_Bool: // casting from bool is like casting from an integer
6468 case Type::STK_Integral:
6469 switch (DestTy->getScalarTypeKind()) {
6470 case Type::STK_CPointer:
6471 case Type::STK_ObjCObjectPointer:
6472 case Type::STK_BlockPointer:
6473 if (Src.get()->isNullPointerConstant(Context,
6474 Expr::NPC_ValueDependentIsNull))
6475 return CK_NullToPointer;
6476 return CK_IntegralToPointer;
6477 case Type::STK_Bool:
6478 return CK_IntegralToBoolean;
6479 case Type::STK_Integral:
6480 return CK_IntegralCast;
6481 case Type::STK_Floating:
6482 return CK_IntegralToFloating;
6483 case Type::STK_IntegralComplex:
6484 Src = ImpCastExprToType(Src.get(),
6485 DestTy->castAs<ComplexType>()->getElementType(),
6486 CK_IntegralCast);
6487 return CK_IntegralRealToComplex;
6488 case Type::STK_FloatingComplex:
6489 Src = ImpCastExprToType(Src.get(),
6490 DestTy->castAs<ComplexType>()->getElementType(),
6491 CK_IntegralToFloating);
6492 return CK_FloatingRealToComplex;
6493 case Type::STK_MemberPointer:
6494 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6494)
;
6495 case Type::STK_FixedPoint:
6496 return CK_IntegralToFixedPoint;
6497 }
6498 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6498)
;
6499
6500 case Type::STK_Floating:
6501 switch (DestTy->getScalarTypeKind()) {
6502 case Type::STK_Floating:
6503 return CK_FloatingCast;
6504 case Type::STK_Bool:
6505 return CK_FloatingToBoolean;
6506 case Type::STK_Integral:
6507 return CK_FloatingToIntegral;
6508 case Type::STK_FloatingComplex:
6509 Src = ImpCastExprToType(Src.get(),
6510 DestTy->castAs<ComplexType>()->getElementType(),
6511 CK_FloatingCast);
6512 return CK_FloatingRealToComplex;
6513 case Type::STK_IntegralComplex:
6514 Src = ImpCastExprToType(Src.get(),
6515 DestTy->castAs<ComplexType>()->getElementType(),
6516 CK_FloatingToIntegral);
6517 return CK_IntegralRealToComplex;
6518 case Type::STK_CPointer:
6519 case Type::STK_ObjCObjectPointer:
6520 case Type::STK_BlockPointer:
6521 llvm_unreachable("valid float->pointer cast?")::llvm::llvm_unreachable_internal("valid float->pointer cast?"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6521)
;
6522 case Type::STK_MemberPointer:
6523 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6523)
;
6524 case Type::STK_FixedPoint:
6525 Diag(Src.get()->getExprLoc(),
6526 diag::err_unimplemented_conversion_with_fixed_point_type)
6527 << SrcTy;
6528 return CK_IntegralCast;
6529 }
6530 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6530)
;
6531
6532 case Type::STK_FloatingComplex:
6533 switch (DestTy->getScalarTypeKind()) {
6534 case Type::STK_FloatingComplex:
6535 return CK_FloatingComplexCast;
6536 case Type::STK_IntegralComplex:
6537 return CK_FloatingComplexToIntegralComplex;
6538 case Type::STK_Floating: {
6539 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6540 if (Context.hasSameType(ET, DestTy))
6541 return CK_FloatingComplexToReal;
6542 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6543 return CK_FloatingCast;
6544 }
6545 case Type::STK_Bool:
6546 return CK_FloatingComplexToBoolean;
6547 case Type::STK_Integral:
6548 Src = ImpCastExprToType(Src.get(),
6549 SrcTy->castAs<ComplexType>()->getElementType(),
6550 CK_FloatingComplexToReal);
6551 return CK_FloatingToIntegral;
6552 case Type::STK_CPointer:
6553 case Type::STK_ObjCObjectPointer:
6554 case Type::STK_BlockPointer:
6555 llvm_unreachable("valid complex float->pointer cast?")::llvm::llvm_unreachable_internal("valid complex float->pointer cast?"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6555)
;
6556 case Type::STK_MemberPointer:
6557 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6557)
;
6558 case Type::STK_FixedPoint:
6559 Diag(Src.get()->getExprLoc(),
6560 diag::err_unimplemented_conversion_with_fixed_point_type)
6561 << SrcTy;
6562 return CK_IntegralCast;
6563 }
6564 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6564)
;
6565
6566 case Type::STK_IntegralComplex:
6567 switch (DestTy->getScalarTypeKind()) {
6568 case Type::STK_FloatingComplex:
6569 return CK_IntegralComplexToFloatingComplex;
6570 case Type::STK_IntegralComplex:
6571 return CK_IntegralComplexCast;
6572 case Type::STK_Integral: {
6573 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6574 if (Context.hasSameType(ET, DestTy))
6575 return CK_IntegralComplexToReal;
6576 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6577 return CK_IntegralCast;
6578 }
6579 case Type::STK_Bool:
6580 return CK_IntegralComplexToBoolean;
6581 case Type::STK_Floating:
6582 Src = ImpCastExprToType(Src.get(),
6583 SrcTy->castAs<ComplexType>()->getElementType(),
6584 CK_IntegralComplexToReal);
6585 return CK_IntegralToFloating;
6586 case Type::STK_CPointer:
6587 case Type::STK_ObjCObjectPointer:
6588 case Type::STK_BlockPointer:
6589 llvm_unreachable("valid complex int->pointer cast?")::llvm::llvm_unreachable_internal("valid complex int->pointer cast?"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6589)
;
6590 case Type::STK_MemberPointer:
6591 llvm_unreachable("member pointer type in C")::llvm::llvm_unreachable_internal("member pointer type in C",
"/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6591)
;
6592 case Type::STK_FixedPoint:
6593 Diag(Src.get()->getExprLoc(),
6594 diag::err_unimplemented_conversion_with_fixed_point_type)
6595 << SrcTy;
6596 return CK_IntegralCast;
6597 }
6598 llvm_unreachable("Should have returned before this")::llvm::llvm_unreachable_internal("Should have returned before this"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6598)
;
6599 }
6600
6601 llvm_unreachable("Unhandled scalar cast")::llvm::llvm_unreachable_internal("Unhandled scalar cast", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6601)
;
6602}
6603
6604static bool breakDownVectorType(QualType type, uint64_t &len,
6605 QualType &eltType) {
6606 // Vectors are simple.
6607 if (const VectorType *vecType = type->getAs<VectorType>()) {
6608 len = vecType->getNumElements();
6609 eltType = vecType->getElementType();
6610 assert(eltType->isScalarType())((eltType->isScalarType()) ? static_cast<void> (0) :
__assert_fail ("eltType->isScalarType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6610, __PRETTY_FUNCTION__))
;
6611 return true;
6612 }
6613
6614 // We allow lax conversion to and from non-vector types, but only if
6615 // they're real types (i.e. non-complex, non-pointer scalar types).
6616 if (!type->isRealType()) return false;
6617
6618 len = 1;
6619 eltType = type;
6620 return true;
6621}
6622
6623/// Are the two types lax-compatible vector types? That is, given
6624/// that one of them is a vector, do they have equal storage sizes,
6625/// where the storage size is the number of elements times the element
6626/// size?
6627///
6628/// This will also return false if either of the types is neither a
6629/// vector nor a real type.
6630bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6631 assert(destTy->isVectorType() || srcTy->isVectorType())((destTy->isVectorType() || srcTy->isVectorType()) ? static_cast
<void> (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6631, __PRETTY_FUNCTION__))
;
6632
6633 // Disallow lax conversions between scalars and ExtVectors (these
6634 // conversions are allowed for other vector types because common headers
6635 // depend on them). Most scalar OP ExtVector cases are handled by the
6636 // splat path anyway, which does what we want (convert, not bitcast).
6637 // What this rules out for ExtVectors is crazy things like char4*float.
6638 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6639 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6640
6641 uint64_t srcLen, destLen;
6642 QualType srcEltTy, destEltTy;
6643 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6644 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6645
6646 // ASTContext::getTypeSize will return the size rounded up to a
6647 // power of 2, so instead of using that, we need to use the raw
6648 // element size multiplied by the element count.
6649 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6650 uint64_t destEltSize = Context.getTypeSize(destEltTy);
6651
6652 return (srcLen * srcEltSize == destLen * destEltSize);
6653}
6654
6655/// Is this a legal conversion between two types, one of which is
6656/// known to be a vector type?
6657bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6658 assert(destTy->isVectorType() || srcTy->isVectorType())((destTy->isVectorType() || srcTy->isVectorType()) ? static_cast
<void> (0) : __assert_fail ("destTy->isVectorType() || srcTy->isVectorType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6658, __PRETTY_FUNCTION__))
;
6659
6660 switch (Context.getLangOpts().getLaxVectorConversions()) {
6661 case LangOptions::LaxVectorConversionKind::None:
6662 return false;
6663
6664 case LangOptions::LaxVectorConversionKind::Integer:
6665 if (!srcTy->isIntegralOrEnumerationType()) {
6666 auto *Vec = srcTy->getAs<VectorType>();
6667 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6668 return false;
6669 }
6670 if (!destTy->isIntegralOrEnumerationType()) {
6671 auto *Vec = destTy->getAs<VectorType>();
6672 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
6673 return false;
6674 }
6675 // OK, integer (vector) -> integer (vector) bitcast.
6676 break;
6677
6678 case LangOptions::LaxVectorConversionKind::All:
6679 break;
6680 }
6681
6682 return areLaxCompatibleVectorTypes(srcTy, destTy);
6683}
6684
6685bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6686 CastKind &Kind) {
6687 assert(VectorTy->isVectorType() && "Not a vector type!")((VectorTy->isVectorType() && "Not a vector type!"
) ? static_cast<void> (0) : __assert_fail ("VectorTy->isVectorType() && \"Not a vector type!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6687, __PRETTY_FUNCTION__))
;
6688
6689 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6690 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6691 return Diag(R.getBegin(),
6692 Ty->isVectorType() ?
6693 diag::err_invalid_conversion_between_vectors :
6694 diag::err_invalid_conversion_between_vector_and_integer)
6695 << VectorTy << Ty << R;
6696 } else
6697 return Diag(R.getBegin(),
6698 diag::err_invalid_conversion_between_vector_and_scalar)
6699 << VectorTy << Ty << R;
6700
6701 Kind = CK_BitCast;
6702 return false;
6703}
6704
6705ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6706 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6707
6708 if (DestElemTy == SplattedExpr->getType())
6709 return SplattedExpr;
6710
6711 assert(DestElemTy->isFloatingType() ||((DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType
()) ? static_cast<void> (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6712, __PRETTY_FUNCTION__))
6712 DestElemTy->isIntegralOrEnumerationType())((DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType
()) ? static_cast<void> (0) : __assert_fail ("DestElemTy->isFloatingType() || DestElemTy->isIntegralOrEnumerationType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6712, __PRETTY_FUNCTION__))
;
6713
6714 CastKind CK;
6715 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6716 // OpenCL requires that we convert `true` boolean expressions to -1, but
6717 // only when splatting vectors.
6718 if (DestElemTy->isFloatingType()) {
6719 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6720 // in two steps: boolean to signed integral, then to floating.
6721 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6722 CK_BooleanToSignedIntegral);
6723 SplattedExpr = CastExprRes.get();
6724 CK = CK_IntegralToFloating;
6725 } else {
6726 CK = CK_BooleanToSignedIntegral;
6727 }
6728 } else {
6729 ExprResult CastExprRes = SplattedExpr;
6730 CK = PrepareScalarCast(CastExprRes, DestElemTy);
6731 if (CastExprRes.isInvalid())
6732 return ExprError();
6733 SplattedExpr = CastExprRes.get();
6734 }
6735 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6736}
6737
6738ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6739 Expr *CastExpr, CastKind &Kind) {
6740 assert(DestTy->isExtVectorType() && "Not an extended vector type!")((DestTy->isExtVectorType() && "Not an extended vector type!"
) ? static_cast<void> (0) : __assert_fail ("DestTy->isExtVectorType() && \"Not an extended vector type!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6740, __PRETTY_FUNCTION__))
;
6741
6742 QualType SrcTy = CastExpr->getType();
6743
6744 // If SrcTy is a VectorType, the total size must match to explicitly cast to
6745 // an ExtVectorType.
6746 // In OpenCL, casts between vectors of different types are not allowed.
6747 // (See OpenCL 6.2).
6748 if (SrcTy->isVectorType()) {
6749 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6750 (getLangOpts().OpenCL &&
6751 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6752 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6753 << DestTy << SrcTy << R;
6754 return ExprError();
6755 }
6756 Kind = CK_BitCast;
6757 return CastExpr;
6758 }
6759
6760 // All non-pointer scalars can be cast to ExtVector type. The appropriate
6761 // conversion will take place first from scalar to elt type, and then
6762 // splat from elt type to vector.
6763 if (SrcTy->isPointerType())
6764 return Diag(R.getBegin(),
6765 diag::err_invalid_conversion_between_vector_and_scalar)
6766 << DestTy << SrcTy << R;
6767
6768 Kind = CK_VectorSplat;
6769 return prepareVectorSplat(DestTy, CastExpr);
6770}
6771
6772ExprResult
6773Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6774 Declarator &D, ParsedType &Ty,
6775 SourceLocation RParenLoc, Expr *CastExpr) {
6776 assert(!D.isInvalidType() && (CastExpr != nullptr) &&((!D.isInvalidType() && (CastExpr != nullptr) &&
"ActOnCastExpr(): missing type or expr") ? static_cast<void
> (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6777, __PRETTY_FUNCTION__))
6777 "ActOnCastExpr(): missing type or expr")((!D.isInvalidType() && (CastExpr != nullptr) &&
"ActOnCastExpr(): missing type or expr") ? static_cast<void
> (0) : __assert_fail ("!D.isInvalidType() && (CastExpr != nullptr) && \"ActOnCastExpr(): missing type or expr\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6777, __PRETTY_FUNCTION__))
;
6778
6779 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6780 if (D.isInvalidType())
6781 return ExprError();
6782
6783 if (getLangOpts().CPlusPlus) {
6784 // Check that there are no default arguments (C++ only).
6785 CheckExtraCXXDefaultArguments(D);
6786 } else {
6787 // Make sure any TypoExprs have been dealt with.
6788 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6789 if (!Res.isUsable())
6790 return ExprError();
6791 CastExpr = Res.get();
6792 }
6793
6794 checkUnusedDeclAttributes(D);
6795
6796 QualType castType = castTInfo->getType();
6797 Ty = CreateParsedType(castType, castTInfo);
6798
6799 bool isVectorLiteral = false;
6800
6801 // Check for an altivec or OpenCL literal,
6802 // i.e. all the elements are integer constants.
6803 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6804 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6805 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6806 && castType->isVectorType() && (PE || PLE)) {
6807 if (PLE && PLE->getNumExprs() == 0) {
6808 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6809 return ExprError();
6810 }
6811 if (PE || PLE->getNumExprs() == 1) {
6812 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6813 if (!E->getType()->isVectorType())
6814 isVectorLiteral = true;
6815 }
6816 else
6817 isVectorLiteral = true;
6818 }
6819
6820 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6821 // then handle it as such.
6822 if (isVectorLiteral)
6823 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6824
6825 // If the Expr being casted is a ParenListExpr, handle it specially.
6826 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6827 // sequence of BinOp comma operators.
6828 if (isa<ParenListExpr>(CastExpr)) {
6829 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6830 if (Result.isInvalid()) return ExprError();
6831 CastExpr = Result.get();
6832 }
6833
6834 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6835 !getSourceManager().isInSystemMacro(LParenLoc))
6836 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6837
6838 CheckTollFreeBridgeCast(castType, CastExpr);
6839
6840 CheckObjCBridgeRelatedCast(castType, CastExpr);
6841
6842 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6843
6844 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6845}
6846
6847ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6848 SourceLocation RParenLoc, Expr *E,
6849 TypeSourceInfo *TInfo) {
6850 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&(((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
"Expected paren or paren list expression") ? static_cast<
void> (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6851, __PRETTY_FUNCTION__))
6851 "Expected paren or paren list expression")(((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
"Expected paren or paren list expression") ? static_cast<
void> (0) : __assert_fail ("(isa<ParenListExpr>(E) || isa<ParenExpr>(E)) && \"Expected paren or paren list expression\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6851, __PRETTY_FUNCTION__))
;
6852
6853 Expr **exprs;
6854 unsigned numExprs;
6855 Expr *subExpr;
6856 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6857 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6858 LiteralLParenLoc = PE->getLParenLoc();
6859 LiteralRParenLoc = PE->getRParenLoc();
6860 exprs = PE->getExprs();
6861 numExprs = PE->getNumExprs();
6862 } else { // isa<ParenExpr> by assertion at function entrance
6863 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6864 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6865 subExpr = cast<ParenExpr>(E)->getSubExpr();
6866 exprs = &subExpr;
6867 numExprs = 1;
6868 }
6869
6870 QualType Ty = TInfo->getType();
6871 assert(Ty->isVectorType() && "Expected vector type")((Ty->isVectorType() && "Expected vector type") ? static_cast
<void> (0) : __assert_fail ("Ty->isVectorType() && \"Expected vector type\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 6871, __PRETTY_FUNCTION__))
;
6872
6873 SmallVector<Expr *, 8> initExprs;
6874 const VectorType *VTy = Ty->castAs<VectorType>();
6875 unsigned numElems = VTy->getNumElements();
6876
6877 // '(...)' form of vector initialization in AltiVec: the number of
6878 // initializers must be one or must match the size of the vector.
6879 // If a single value is specified in the initializer then it will be
6880 // replicated to all the components of the vector
6881 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6882 // The number of initializers must be one or must match the size of the
6883 // vector. If a single value is specified in the initializer then it will
6884 // be replicated to all the components of the vector
6885 if (numExprs == 1) {
6886 QualType ElemTy = VTy->getElementType();
6887 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6888 if (Literal.isInvalid())
6889 return ExprError();
6890 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6891 PrepareScalarCast(Literal, ElemTy));
6892 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6893 }
6894 else if (numExprs < numElems) {
6895 Diag(E->getExprLoc(),
6896 diag::err_incorrect_number_of_vector_initializers);
6897 return ExprError();
6898 }
6899 else
6900 initExprs.append(exprs, exprs + numExprs);
6901 }
6902 else {
6903 // For OpenCL, when the number of initializers is a single value,
6904 // it will be replicated to all components of the vector.
6905 if (getLangOpts().OpenCL &&
6906 VTy->getVectorKind() == VectorType::GenericVector &&
6907 numExprs == 1) {
6908 QualType ElemTy = VTy->getElementType();
6909 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6910 if (Literal.isInvalid())
6911 return ExprError();
6912 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6913 PrepareScalarCast(Literal, ElemTy));
6914 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6915 }
6916
6917 initExprs.append(exprs, exprs + numExprs);
6918 }
6919 // FIXME: This means that pretty-printing the final AST will produce curly
6920 // braces instead of the original commas.
6921 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6922 initExprs, LiteralRParenLoc);
6923 initE->setType(Ty);
6924 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6925}
6926
6927/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6928/// the ParenListExpr into a sequence of comma binary operators.
6929ExprResult
6930Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6931 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6932 if (!E)
6933 return OrigExpr;
6934
6935 ExprResult Result(E->getExpr(0));
6936
6937 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6938 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6939 E->getExpr(i));
6940
6941 if (Result.isInvalid()) return ExprError();
6942
6943 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6944}
6945
6946ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6947 SourceLocation R,
6948 MultiExprArg Val) {
6949 return ParenListExpr::Create(Context, L, Val, R);
6950}
6951
6952/// Emit a specialized diagnostic when one expression is a null pointer
6953/// constant and the other is not a pointer. Returns true if a diagnostic is
6954/// emitted.
6955bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6956 SourceLocation QuestionLoc) {
6957 Expr *NullExpr = LHSExpr;
6958 Expr *NonPointerExpr = RHSExpr;
6959 Expr::NullPointerConstantKind NullKind =
6960 NullExpr->isNullPointerConstant(Context,
6961 Expr::NPC_ValueDependentIsNotNull);
6962
6963 if (NullKind == Expr::NPCK_NotNull) {
6964 NullExpr = RHSExpr;
6965 NonPointerExpr = LHSExpr;
6966 NullKind =
6967 NullExpr->isNullPointerConstant(Context,
6968 Expr::NPC_ValueDependentIsNotNull);
6969 }
6970
6971 if (NullKind == Expr::NPCK_NotNull)
6972 return false;
6973
6974 if (NullKind == Expr::NPCK_ZeroExpression)
6975 return false;
6976
6977 if (NullKind == Expr::NPCK_ZeroLiteral) {
6978 // In this case, check to make sure that we got here from a "NULL"
6979 // string in the source code.
6980 NullExpr = NullExpr->IgnoreParenImpCasts();
6981 SourceLocation loc = NullExpr->getExprLoc();
6982 if (!findMacroSpelling(loc, "NULL"))
6983 return false;
6984 }
6985
6986 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6987 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6988 << NonPointerExpr->getType() << DiagType
6989 << NonPointerExpr->getSourceRange();
6990 return true;
6991}
6992
6993/// Return false if the condition expression is valid, true otherwise.
6994static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6995 QualType CondTy = Cond->getType();
6996
6997 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6998 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6999 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7000 << CondTy << Cond->getSourceRange();
7001 return true;
7002 }
7003
7004 // C99 6.5.15p2
7005 if (CondTy->isScalarType()) return false;
7006
7007 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7008 << CondTy << Cond->getSourceRange();
7009 return true;
7010}
7011
7012/// Handle when one or both operands are void type.
7013static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7014 ExprResult &RHS) {
7015 Expr *LHSExpr = LHS.get();
7016 Expr *RHSExpr = RHS.get();
7017
7018 if (!LHSExpr->getType()->isVoidType())
7019 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7020 << RHSExpr->getSourceRange();
7021 if (!RHSExpr->getType()->isVoidType())
7022 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7023 << LHSExpr->getSourceRange();
7024 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7025 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7026 return S.Context.VoidTy;
7027}
7028
7029/// Return false if the NullExpr can be promoted to PointerTy,
7030/// true otherwise.
7031static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7032 QualType PointerTy) {
7033 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7034 !NullExpr.get()->isNullPointerConstant(S.Context,
7035 Expr::NPC_ValueDependentIsNull))
7036 return true;
7037
7038 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7039 return false;
7040}
7041
7042/// Checks compatibility between two pointers and return the resulting
7043/// type.
7044static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7045 ExprResult &RHS,
7046 SourceLocation Loc) {
7047 QualType LHSTy = LHS.get()->getType();
7048 QualType RHSTy = RHS.get()->getType();
7049
7050 if (S.Context.hasSameType(LHSTy, RHSTy)) {
7051 // Two identical pointers types are always compatible.
7052 return LHSTy;
7053 }
7054
7055 QualType lhptee, rhptee;
7056
7057 // Get the pointee types.
7058 bool IsBlockPointer = false;
7059 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7060 lhptee = LHSBTy->getPointeeType();
7061 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7062 IsBlockPointer = true;
7063 } else {
7064 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7065 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7066 }
7067
7068 // C99 6.5.15p6: If both operands are pointers to compatible types or to
7069 // differently qualified versions of compatible types, the result type is
7070 // a pointer to an appropriately qualified version of the composite
7071 // type.
7072
7073 // Only CVR-qualifiers exist in the standard, and the differently-qualified
7074 // clause doesn't make sense for our extensions. E.g. address space 2 should
7075 // be incompatible with address space 3: they may live on different devices or
7076 // anything.
7077 Qualifiers lhQual = lhptee.getQualifiers();
7078 Qualifiers rhQual = rhptee.getQualifiers();
7079
7080 LangAS ResultAddrSpace = LangAS::Default;
7081 LangAS LAddrSpace = lhQual.getAddressSpace();
7082 LangAS RAddrSpace = rhQual.getAddressSpace();
7083
7084 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7085 // spaces is disallowed.
7086 if (lhQual.isAddressSpaceSupersetOf(rhQual))
7087 ResultAddrSpace = LAddrSpace;
7088 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7089 ResultAddrSpace = RAddrSpace;
7090 else {
7091 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7092 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7093 << RHS.get()->getSourceRange();
7094 return QualType();
7095 }
7096
7097 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7098 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7099 lhQual.removeCVRQualifiers();
7100 rhQual.removeCVRQualifiers();
7101
7102 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7103 // (C99 6.7.3) for address spaces. We assume that the check should behave in
7104 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7105 // qual types are compatible iff
7106 // * corresponded types are compatible
7107 // * CVR qualifiers are equal
7108 // * address spaces are equal
7109 // Thus for conditional operator we merge CVR and address space unqualified
7110 // pointees and if there is a composite type we return a pointer to it with
7111 // merged qualifiers.
7112 LHSCastKind =
7113 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7114 RHSCastKind =
7115 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7116 lhQual.removeAddressSpace();
7117 rhQual.removeAddressSpace();
7118
7119 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7120 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7121
7122 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7123
7124 if (CompositeTy.isNull()) {
7125 // In this situation, we assume void* type. No especially good
7126 // reason, but this is what gcc does, and we do have to pick
7127 // to get a consistent AST.
7128 QualType incompatTy;
7129 incompatTy = S.Context.getPointerType(
7130 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7131 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7132 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7133
7134 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7135 // for casts between types with incompatible address space qualifiers.
7136 // For the following code the compiler produces casts between global and
7137 // local address spaces of the corresponded innermost pointees:
7138 // local int *global *a;
7139 // global int *global *b;
7140 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7141 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7142 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7143 << RHS.get()->getSourceRange();
7144
7145 return incompatTy;
7146 }
7147
7148 // The pointer types are compatible.
7149 // In case of OpenCL ResultTy should have the address space qualifier
7150 // which is a superset of address spaces of both the 2nd and the 3rd
7151 // operands of the conditional operator.
7152 QualType ResultTy = [&, ResultAddrSpace]() {
7153 if (S.getLangOpts().OpenCL) {
7154 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7155 CompositeQuals.setAddressSpace(ResultAddrSpace);
7156 return S.Context
7157 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7158 .withCVRQualifiers(MergedCVRQual);
7159 }
7160 return CompositeTy.withCVRQualifiers(MergedCVRQual);
7161 }();
7162 if (IsBlockPointer)
7163 ResultTy = S.Context.getBlockPointerType(ResultTy);
7164 else
7165 ResultTy = S.Context.getPointerType(ResultTy);
7166
7167 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7168 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7169 return ResultTy;
7170}
7171
7172/// Return the resulting type when the operands are both block pointers.
7173static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7174 ExprResult &LHS,
7175 ExprResult &RHS,
7176 SourceLocation Loc) {
7177 QualType LHSTy = LHS.get()->getType();
7178 QualType RHSTy = RHS.get()->getType();
7179
7180 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7181 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7182 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7183 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7184 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7185 return destType;
7186 }
7187 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7188 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7189 << RHS.get()->getSourceRange();
7190 return QualType();
7191 }
7192
7193 // We have 2 block pointer types.
7194 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7195}
7196
7197/// Return the resulting type when the operands are both pointers.
7198static QualType
7199checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7200 ExprResult &RHS,
7201 SourceLocation Loc) {
7202 // get the pointer types
7203 QualType LHSTy = LHS.get()->getType();
7204 QualType RHSTy = RHS.get()->getType();
7205
7206 // get the "pointed to" types
7207 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7208 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7209
7210 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7211 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7212 // Figure out necessary qualifiers (C99 6.5.15p6)
7213 QualType destPointee
7214 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7215 QualType destType = S.Context.getPointerType(destPointee);
7216 // Add qualifiers if necessary.
7217 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7218 // Promote to void*.
7219 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7220 return destType;
7221 }
7222 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7223 QualType destPointee
7224 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7225 QualType destType = S.Context.getPointerType(destPointee);
7226 // Add qualifiers if necessary.
7227 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7228 // Promote to void*.
7229 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7230 return destType;
7231 }
7232
7233 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7234}
7235
7236/// Return false if the first expression is not an integer and the second
7237/// expression is not a pointer, true otherwise.
7238static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7239 Expr* PointerExpr, SourceLocation Loc,
7240 bool IsIntFirstExpr) {
7241 if (!PointerExpr->getType()->isPointerType() ||
7242 !Int.get()->getType()->isIntegerType())
7243 return false;
7244
7245 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7246 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7247
7248 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7249 << Expr1->getType() << Expr2->getType()
7250 << Expr1->getSourceRange() << Expr2->getSourceRange();
7251 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7252 CK_IntegralToPointer);
7253 return true;
7254}
7255
7256/// Simple conversion between integer and floating point types.
7257///
7258/// Used when handling the OpenCL conditional operator where the
7259/// condition is a vector while the other operands are scalar.
7260///
7261/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7262/// types are either integer or floating type. Between the two
7263/// operands, the type with the higher rank is defined as the "result
7264/// type". The other operand needs to be promoted to the same type. No
7265/// other type promotion is allowed. We cannot use
7266/// UsualArithmeticConversions() for this purpose, since it always
7267/// promotes promotable types.
7268static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7269 ExprResult &RHS,
7270 SourceLocation QuestionLoc) {
7271 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7272 if (LHS.isInvalid())
7273 return QualType();
7274 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7275 if (RHS.isInvalid())
7276 return QualType();
7277
7278 // For conversion purposes, we ignore any qualifiers.
7279 // For example, "const float" and "float" are equivalent.
7280 QualType LHSType =
7281 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7282 QualType RHSType =
7283 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7284
7285 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7286 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7287 << LHSType << LHS.get()->getSourceRange();
7288 return QualType();
7289 }
7290
7291 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7292 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7293 << RHSType << RHS.get()->getSourceRange();
7294 return QualType();
7295 }
7296
7297 // If both types are identical, no conversion is needed.
7298 if (LHSType == RHSType)
7299 return LHSType;
7300
7301 // Now handle "real" floating types (i.e. float, double, long double).
7302 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7303 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7304 /*IsCompAssign = */ false);
7305
7306 // Finally, we have two differing integer types.
7307 return handleIntegerConversion<doIntegralCast, doIntegralCast>
7308 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7309}
7310
7311/// Convert scalar operands to a vector that matches the
7312/// condition in length.
7313///
7314/// Used when handling the OpenCL conditional operator where the
7315/// condition is a vector while the other operands are scalar.
7316///
7317/// We first compute the "result type" for the scalar operands
7318/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7319/// into a vector of that type where the length matches the condition
7320/// vector type. s6.11.6 requires that the element types of the result
7321/// and the condition must have the same number of bits.
7322static QualType
7323OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7324 QualType CondTy, SourceLocation QuestionLoc) {
7325 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7326 if (ResTy.isNull()) return QualType();
7327
7328 const VectorType *CV = CondTy->getAs<VectorType>();
7329 assert(CV)((CV) ? static_cast<void> (0) : __assert_fail ("CV", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 7329, __PRETTY_FUNCTION__))
;
7330
7331 // Determine the vector result type
7332 unsigned NumElements = CV->getNumElements();
7333 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7334
7335 // Ensure that all types have the same number of bits
7336 if (S.Context.getTypeSize(CV->getElementType())
7337 != S.Context.getTypeSize(ResTy)) {
7338 // Since VectorTy is created internally, it does not pretty print
7339 // with an OpenCL name. Instead, we just print a description.
7340 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7341 SmallString<64> Str;
7342 llvm::raw_svector_ostream OS(Str);
7343 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7344 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7345 << CondTy << OS.str();
7346 return QualType();
7347 }
7348
7349 // Convert operands to the vector result type
7350 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7351 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7352
7353 return VectorTy;
7354}
7355
7356/// Return false if this is a valid OpenCL condition vector
7357static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7358 SourceLocation QuestionLoc) {
7359 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7360 // integral type.
7361 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7362 assert(CondTy)((CondTy) ? static_cast<void> (0) : __assert_fail ("CondTy"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 7362, __PRETTY_FUNCTION__))
;
7363 QualType EleTy = CondTy->getElementType();
7364 if (EleTy->isIntegerType()) return false;
7365
7366 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7367 << Cond->getType() << Cond->getSourceRange();
7368 return true;
7369}
7370
7371/// Return false if the vector condition type and the vector
7372/// result type are compatible.
7373///
7374/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7375/// number of elements, and their element types have the same number
7376/// of bits.
7377static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7378 SourceLocation QuestionLoc) {
7379 const VectorType *CV = CondTy->getAs<VectorType>();
7380 const VectorType *RV = VecResTy->getAs<VectorType>();
7381 assert(CV && RV)((CV && RV) ? static_cast<void> (0) : __assert_fail
("CV && RV", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 7381, __PRETTY_FUNCTION__))
;
7382
7383 if (CV->getNumElements() != RV->getNumElements()) {
7384 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7385 << CondTy << VecResTy;
7386 return true;
7387 }
7388
7389 QualType CVE = CV->getElementType();
7390 QualType RVE = RV->getElementType();
7391
7392 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7393 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7394 << CondTy << VecResTy;
7395 return true;
7396 }
7397
7398 return false;
7399}
7400
7401/// Return the resulting type for the conditional operator in
7402/// OpenCL (aka "ternary selection operator", OpenCL v1.1
7403/// s6.3.i) when the condition is a vector type.
7404static QualType
7405OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7406 ExprResult &LHS, ExprResult &RHS,
7407 SourceLocation QuestionLoc) {
7408 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7409 if (Cond.isInvalid())
7410 return QualType();
7411 QualType CondTy = Cond.get()->getType();
7412
7413 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7414 return QualType();
7415
7416 // If either operand is a vector then find the vector type of the
7417 // result as specified in OpenCL v1.1 s6.3.i.
7418 if (LHS.get()->getType()->isVectorType() ||
7419 RHS.get()->getType()->isVectorType()) {
7420 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7421 /*isCompAssign*/false,
7422 /*AllowBothBool*/true,
7423 /*AllowBoolConversions*/false);
7424 if (VecResTy.isNull()) return QualType();
7425 // The result type must match the condition type as specified in
7426 // OpenCL v1.1 s6.11.6.
7427 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7428 return QualType();
7429 return VecResTy;
7430 }
7431
7432 // Both operands are scalar.
7433 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7434}
7435
7436/// Return true if the Expr is block type
7437static bool checkBlockType(Sema &S, const Expr *E) {
7438 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7439 QualType Ty = CE->getCallee()->getType();
7440 if (Ty->isBlockPointerType()) {
7441 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7442 return true;
7443 }
7444 }
7445 return false;
7446}
7447
7448/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7449/// In that case, LHS = cond.
7450/// C99 6.5.15
7451QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7452 ExprResult &RHS, ExprValueKind &VK,
7453 ExprObjectKind &OK,
7454 SourceLocation QuestionLoc) {
7455
7456 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7457 if (!LHSResult.isUsable()) return QualType();
7458 LHS = LHSResult;
7459
7460 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7461 if (!RHSResult.isUsable()) return QualType();
7462 RHS = RHSResult;
7463
7464 // C++ is sufficiently different to merit its own checker.
7465 if (getLangOpts().CPlusPlus)
7466 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7467
7468 VK = VK_RValue;
7469 OK = OK_Ordinary;
7470
7471 // The OpenCL operator with a vector condition is sufficiently
7472 // different to merit its own checker.
7473 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7474 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7475
7476 // First, check the condition.
7477 Cond = UsualUnaryConversions(Cond.get());
7478 if (Cond.isInvalid())
7479 return QualType();
7480 if (checkCondition(*this, Cond.get(), QuestionLoc))
7481 return QualType();
7482
7483 // Now check the two expressions.
7484 if (LHS.get()->getType()->isVectorType() ||
7485 RHS.get()->getType()->isVectorType())
7486 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7487 /*AllowBothBool*/true,
7488 /*AllowBoolConversions*/false);
7489
7490 QualType ResTy =
7491 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
7492 if (LHS.isInvalid() || RHS.isInvalid())
7493 return QualType();
7494
7495 QualType LHSTy = LHS.get()->getType();
7496 QualType RHSTy = RHS.get()->getType();
7497
7498 // Diagnose attempts to convert between __float128 and long double where
7499 // such conversions currently can't be handled.
7500 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7501 Diag(QuestionLoc,
7502 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7503 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7504 return QualType();
7505 }
7506
7507 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7508 // selection operator (?:).
7509 if (getLangOpts().OpenCL &&
7510 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7511 return QualType();
7512 }
7513
7514 // If both operands have arithmetic type, do the usual arithmetic conversions
7515 // to find a common type: C99 6.5.15p3,5.
7516 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7517 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7518 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7519
7520 return ResTy;
7521 }
7522
7523 // If both operands are the same structure or union type, the result is that
7524 // type.
7525 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
7526 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7527 if (LHSRT->getDecl() == RHSRT->getDecl())
7528 // "If both the operands have structure or union type, the result has
7529 // that type." This implies that CV qualifiers are dropped.
7530 return LHSTy.getUnqualifiedType();
7531 // FIXME: Type of conditional expression must be complete in C mode.
7532 }
7533
7534 // C99 6.5.15p5: "If both operands have void type, the result has void type."
7535 // The following || allows only one side to be void (a GCC-ism).
7536 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7537 return checkConditionalVoidType(*this, LHS, RHS);
7538 }
7539
7540 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7541 // the type of the other operand."
7542 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7543 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7544
7545 // All objective-c pointer type analysis is done here.
7546 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7547 QuestionLoc);
7548 if (LHS.isInvalid() || RHS.isInvalid())
7549 return QualType();
7550 if (!compositeType.isNull())
7551 return compositeType;
7552
7553
7554 // Handle block pointer types.
7555 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7556 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7557 QuestionLoc);
7558
7559 // Check constraints for C object pointers types (C99 6.5.15p3,6).
7560 if (LHSTy->isPointerType() && RHSTy->isPointerType())
7561 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7562 QuestionLoc);
7563
7564 // GCC compatibility: soften pointer/integer mismatch. Note that
7565 // null pointers have been filtered out by this point.
7566 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7567 /*IsIntFirstExpr=*/true))
7568 return RHSTy;
7569 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7570 /*IsIntFirstExpr=*/false))
7571 return LHSTy;
7572
7573 // Emit a better diagnostic if one of the expressions is a null pointer
7574 // constant and the other is not a pointer type. In this case, the user most
7575 // likely forgot to take the address of the other expression.
7576 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7577 return QualType();
7578
7579 // Otherwise, the operands are not compatible.
7580 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7581 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7582 << RHS.get()->getSourceRange();
7583 return QualType();
7584}
7585
7586/// FindCompositeObjCPointerType - Helper method to find composite type of
7587/// two objective-c pointer types of the two input expressions.
7588QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7589 SourceLocation QuestionLoc) {
7590 QualType LHSTy = LHS.get()->getType();
7591 QualType RHSTy = RHS.get()->getType();
7592
7593 // Handle things like Class and struct objc_class*. Here we case the result
7594 // to the pseudo-builtin, because that will be implicitly cast back to the
7595 // redefinition type if an attempt is made to access its fields.
7596 if (LHSTy->isObjCClassType() &&
7597 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7598 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7599 return LHSTy;
7600 }
7601 if (RHSTy->isObjCClassType() &&
7602 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7603 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7604 return RHSTy;
7605 }
7606 // And the same for struct objc_object* / id
7607 if (LHSTy->isObjCIdType() &&
7608 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7609 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7610 return LHSTy;
7611 }
7612 if (RHSTy->isObjCIdType() &&
7613 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7614 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7615 return RHSTy;
7616 }
7617 // And the same for struct objc_selector* / SEL
7618 if (Context.isObjCSelType(LHSTy) &&
7619 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7620 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7621 return LHSTy;
7622 }
7623 if (Context.isObjCSelType(RHSTy) &&
7624 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7625 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7626 return RHSTy;
7627 }
7628 // Check constraints for Objective-C object pointers types.
7629 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7630
7631 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7632 // Two identical object pointer types are always compatible.
7633 return LHSTy;
7634 }
7635 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7636 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7637 QualType compositeType = LHSTy;
7638
7639 // If both operands are interfaces and either operand can be
7640 // assigned to the other, use that type as the composite
7641 // type. This allows
7642 // xxx ? (A*) a : (B*) b
7643 // where B is a subclass of A.
7644 //
7645 // Additionally, as for assignment, if either type is 'id'
7646 // allow silent coercion. Finally, if the types are
7647 // incompatible then make sure to use 'id' as the composite
7648 // type so the result is acceptable for sending messages to.
7649
7650 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7651 // It could return the composite type.
7652 if (!(compositeType =
7653 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7654 // Nothing more to do.
7655 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7656 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7657 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7658 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7659 } else if ((LHSOPT->isObjCQualifiedIdType() ||
7660 RHSOPT->isObjCQualifiedIdType()) &&
7661 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
7662 true)) {
7663 // Need to handle "id<xx>" explicitly.
7664 // GCC allows qualified id and any Objective-C type to devolve to
7665 // id. Currently localizing to here until clear this should be
7666 // part of ObjCQualifiedIdTypesAreCompatible.
7667 compositeType = Context.getObjCIdType();
7668 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7669 compositeType = Context.getObjCIdType();
7670 } else {
7671 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7672 << LHSTy << RHSTy
7673 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7674 QualType incompatTy = Context.getObjCIdType();
7675 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7676 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7677 return incompatTy;
7678 }
7679 // The object pointer types are compatible.
7680 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7681 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7682 return compositeType;
7683 }
7684 // Check Objective-C object pointer types and 'void *'
7685 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7686 if (getLangOpts().ObjCAutoRefCount) {
7687 // ARC forbids the implicit conversion of object pointers to 'void *',
7688 // so these types are not compatible.
7689 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7690 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7691 LHS = RHS = true;
7692 return QualType();
7693 }
7694 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7695 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7696 QualType destPointee
7697 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7698 QualType destType = Context.getPointerType(destPointee);
7699 // Add qualifiers if necessary.
7700 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7701 // Promote to void*.
7702 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7703 return destType;
7704 }
7705 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7706 if (getLangOpts().ObjCAutoRefCount) {
7707 // ARC forbids the implicit conversion of object pointers to 'void *',
7708 // so these types are not compatible.
7709 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7710 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7711 LHS = RHS = true;
7712 return QualType();
7713 }
7714 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
7715 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7716 QualType destPointee
7717 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7718 QualType destType = Context.getPointerType(destPointee);
7719 // Add qualifiers if necessary.
7720 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7721 // Promote to void*.
7722 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7723 return destType;
7724 }
7725 return QualType();
7726}
7727
7728/// SuggestParentheses - Emit a note with a fixit hint that wraps
7729/// ParenRange in parentheses.
7730static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7731 const PartialDiagnostic &Note,
7732 SourceRange ParenRange) {
7733 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7734 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7735 EndLoc.isValid()) {
7736 Self.Diag(Loc, Note)
7737 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7738 << FixItHint::CreateInsertion(EndLoc, ")");
7739 } else {
7740 // We can't display the parentheses, so just show the bare note.
7741 Self.Diag(Loc, Note) << ParenRange;
7742 }
7743}
7744
7745static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7746 return BinaryOperator::isAdditiveOp(Opc) ||
7747 BinaryOperator::isMultiplicativeOp(Opc) ||
7748 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
7749 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
7750 // not any of the logical operators. Bitwise-xor is commonly used as a
7751 // logical-xor because there is no logical-xor operator. The logical
7752 // operators, including uses of xor, have a high false positive rate for
7753 // precedence warnings.
7754}
7755
7756/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7757/// expression, either using a built-in or overloaded operator,
7758/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7759/// expression.
7760static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7761 Expr **RHSExprs) {
7762 // Don't strip parenthesis: we should not warn if E is in parenthesis.
7763 E = E->IgnoreImpCasts();
7764 E = E->IgnoreConversionOperator();
7765 E = E->IgnoreImpCasts();
7766 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7767 E = MTE->getSubExpr();
7768 E = E->IgnoreImpCasts();
7769 }
7770
7771 // Built-in binary operator.
7772 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7773 if (IsArithmeticOp(OP->getOpcode())) {
7774 *Opcode = OP->getOpcode();
7775 *RHSExprs = OP->getRHS();
7776 return true;
7777 }
7778 }
7779
7780 // Overloaded operator.
7781 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7782 if (Call->getNumArgs() != 2)
7783 return false;
7784
7785 // Make sure this is really a binary operator that is safe to pass into
7786 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7787 OverloadedOperatorKind OO = Call->getOperator();
7788 if (OO < OO_Plus || OO > OO_Arrow ||
7789 OO == OO_PlusPlus || OO == OO_MinusMinus)
7790 return false;
7791
7792 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7793 if (IsArithmeticOp(OpKind)) {
7794 *Opcode = OpKind;
7795 *RHSExprs = Call->getArg(1);
7796 return true;
7797 }
7798 }
7799
7800 return false;
7801}
7802
7803/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7804/// or is a logical expression such as (x==y) which has int type, but is
7805/// commonly interpreted as boolean.
7806static bool ExprLooksBoolean(Expr *E) {
7807 E = E->IgnoreParenImpCasts();
7808
7809 if (E->getType()->isBooleanType())
7810 return true;
7811 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7812 return OP->isComparisonOp() || OP->isLogicalOp();
7813 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7814 return OP->getOpcode() == UO_LNot;
7815 if (E->getType()->isPointerType())
7816 return true;
7817 // FIXME: What about overloaded operator calls returning "unspecified boolean
7818 // type"s (commonly pointer-to-members)?
7819
7820 return false;
7821}
7822
7823/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7824/// and binary operator are mixed in a way that suggests the programmer assumed
7825/// the conditional operator has higher precedence, for example:
7826/// "int x = a + someBinaryCondition ? 1 : 2".
7827static void DiagnoseConditionalPrecedence(Sema &Self,
7828 SourceLocation OpLoc,
7829 Expr *Condition,
7830 Expr *LHSExpr,
7831 Expr *RHSExpr) {
7832 BinaryOperatorKind CondOpcode;
7833 Expr *CondRHS;
7834
7835 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7836 return;
7837 if (!ExprLooksBoolean(CondRHS))
7838 return;
7839
7840 // The condition is an arithmetic binary expression, with a right-
7841 // hand side that looks boolean, so warn.
7842
7843 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
7844 ? diag::warn_precedence_bitwise_conditional
7845 : diag::warn_precedence_conditional;
7846
7847 Self.Diag(OpLoc, DiagID)
7848 << Condition->getSourceRange()
7849 << BinaryOperator::getOpcodeStr(CondOpcode);
7850
7851 SuggestParentheses(
7852 Self, OpLoc,
7853 Self.PDiag(diag::note_precedence_silence)
7854 << BinaryOperator::getOpcodeStr(CondOpcode),
7855 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7856
7857 SuggestParentheses(Self, OpLoc,
7858 Self.PDiag(diag::note_precedence_conditional_first),
7859 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7860}
7861
7862/// Compute the nullability of a conditional expression.
7863static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7864 QualType LHSTy, QualType RHSTy,
7865 ASTContext &Ctx) {
7866 if (!ResTy->isAnyPointerType())
7867 return ResTy;
7868
7869 auto GetNullability = [&Ctx](QualType Ty) {
7870 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7871 if (Kind)
7872 return *Kind;
7873 return NullabilityKind::Unspecified;
7874 };
7875
7876 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7877 NullabilityKind MergedKind;
7878
7879 // Compute nullability of a binary conditional expression.
7880 if (IsBin) {
7881 if (LHSKind == NullabilityKind::NonNull)
7882 MergedKind = NullabilityKind::NonNull;
7883 else
7884 MergedKind = RHSKind;
7885 // Compute nullability of a normal conditional expression.
7886 } else {
7887 if (LHSKind == NullabilityKind::Nullable ||
7888 RHSKind == NullabilityKind::Nullable)
7889 MergedKind = NullabilityKind::Nullable;
7890 else if (LHSKind == NullabilityKind::NonNull)
7891 MergedKind = RHSKind;
7892 else if (RHSKind == NullabilityKind::NonNull)
7893 MergedKind = LHSKind;
7894 else
7895 MergedKind = NullabilityKind::Unspecified;
7896 }
7897
7898 // Return if ResTy already has the correct nullability.
7899 if (GetNullability(ResTy) == MergedKind)
7900 return ResTy;
7901
7902 // Strip all nullability from ResTy.
7903 while (ResTy->getNullability(Ctx))
7904 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7905
7906 // Create a new AttributedType with the new nullability kind.
7907 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7908 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7909}
7910
7911/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7912/// in the case of a the GNU conditional expr extension.
7913ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7914 SourceLocation ColonLoc,
7915 Expr *CondExpr, Expr *LHSExpr,
7916 Expr *RHSExpr) {
7917 if (!getLangOpts().CPlusPlus) {
7918 // C cannot handle TypoExpr nodes in the condition because it
7919 // doesn't handle dependent types properly, so make sure any TypoExprs have
7920 // been dealt with before checking the operands.
7921 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7922 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7923 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7924
7925 if (!CondResult.isUsable())
7926 return ExprError();
7927
7928 if (LHSExpr) {
7929 if (!LHSResult.isUsable())
7930 return ExprError();
7931 }
7932
7933 if (!RHSResult.isUsable())
7934 return ExprError();
7935
7936 CondExpr = CondResult.get();
7937 LHSExpr = LHSResult.get();
7938 RHSExpr = RHSResult.get();
7939 }
7940
7941 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7942 // was the condition.
7943 OpaqueValueExpr *opaqueValue = nullptr;
7944 Expr *commonExpr = nullptr;
7945 if (!LHSExpr) {
7946 commonExpr = CondExpr;
7947 // Lower out placeholder types first. This is important so that we don't
7948 // try to capture a placeholder. This happens in few cases in C++; such
7949 // as Objective-C++'s dictionary subscripting syntax.
7950 if (commonExpr->hasPlaceholderType()) {
7951 ExprResult result = CheckPlaceholderExpr(commonExpr);
7952 if (!result.isUsable()) return ExprError();
7953 commonExpr = result.get();
7954 }
7955 // We usually want to apply unary conversions *before* saving, except
7956 // in the special case of a C++ l-value conditional.
7957 if (!(getLangOpts().CPlusPlus
7958 && !commonExpr->isTypeDependent()
7959 && commonExpr->getValueKind() == RHSExpr->getValueKind()
7960 && commonExpr->isGLValue()
7961 && commonExpr->isOrdinaryOrBitFieldObject()
7962 && RHSExpr->isOrdinaryOrBitFieldObject()
7963 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7964 ExprResult commonRes = UsualUnaryConversions(commonExpr);
7965 if (commonRes.isInvalid())
7966 return ExprError();
7967 commonExpr = commonRes.get();
7968 }
7969
7970 // If the common expression is a class or array prvalue, materialize it
7971 // so that we can safely refer to it multiple times.
7972 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7973 commonExpr->getType()->isArrayType())) {
7974 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7975 if (MatExpr.isInvalid())
7976 return ExprError();
7977 commonExpr = MatExpr.get();
7978 }
7979
7980 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7981 commonExpr->getType(),
7982 commonExpr->getValueKind(),
7983 commonExpr->getObjectKind(),
7984 commonExpr);
7985 LHSExpr = CondExpr = opaqueValue;
7986 }
7987
7988 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7989 ExprValueKind VK = VK_RValue;
7990 ExprObjectKind OK = OK_Ordinary;
7991 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7992 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7993 VK, OK, QuestionLoc);
7994 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7995 RHS.isInvalid())
7996 return ExprError();
7997
7998 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7999 RHS.get());
8000
8001 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8002
8003 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8004 Context);
8005
8006 if (!commonExpr)
8007 return new (Context)
8008 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8009 RHS.get(), result, VK, OK);
8010
8011 return new (Context) BinaryConditionalOperator(
8012 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8013 ColonLoc, result, VK, OK);
8014}
8015
8016// checkPointerTypesForAssignment - This is a very tricky routine (despite
8017// being closely modeled after the C99 spec:-). The odd characteristic of this
8018// routine is it effectively iqnores the qualifiers on the top level pointee.
8019// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8020// FIXME: add a couple examples in this comment.
8021static Sema::AssignConvertType
8022checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8023 assert(LHSType.isCanonical() && "LHS not canonicalized!")((LHSType.isCanonical() && "LHS not canonicalized!") ?
static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 8023, __PRETTY_FUNCTION__))
;
8024 assert(RHSType.isCanonical() && "RHS not canonicalized!")((RHSType.isCanonical() && "RHS not canonicalized!") ?
static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 8024, __PRETTY_FUNCTION__))
;
8025
8026 // get the "pointed to" type (ignoring qualifiers at the top level)
8027 const Type *lhptee, *rhptee;
8028 Qualifiers lhq, rhq;
8029 std::tie(lhptee, lhq) =
8030 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8031 std::tie(rhptee, rhq) =
8032 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8033
8034 Sema::AssignConvertType ConvTy = Sema::Compatible;
8035
8036 // C99 6.5.16.1p1: This following citation is common to constraints
8037 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8038 // qualifiers of the type *pointed to* by the right;
8039
8040 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8041 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8042 lhq.compatiblyIncludesObjCLifetime(rhq)) {
8043 // Ignore lifetime for further calculation.
8044 lhq.removeObjCLifetime();
8045 rhq.removeObjCLifetime();
8046 }
8047
8048 if (!lhq.compatiblyIncludes(rhq)) {
8049 // Treat address-space mismatches as fatal.
8050 if (!lhq.isAddressSpaceSupersetOf(rhq))
8051 return Sema::IncompatiblePointerDiscardsQualifiers;
8052
8053 // It's okay to add or remove GC or lifetime qualifiers when converting to
8054 // and from void*.
8055 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8056 .compatiblyIncludes(
8057 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8058 && (lhptee->isVoidType() || rhptee->isVoidType()))
8059 ; // keep old
8060
8061 // Treat lifetime mismatches as fatal.
8062 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8063 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8064
8065 // For GCC/MS compatibility, other qualifier mismatches are treated
8066 // as still compatible in C.
8067 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8068 }
8069
8070 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8071 // incomplete type and the other is a pointer to a qualified or unqualified
8072 // version of void...
8073 if (lhptee->isVoidType()) {
8074 if (rhptee->isIncompleteOrObjectType())
8075 return ConvTy;
8076
8077 // As an extension, we allow cast to/from void* to function pointer.
8078 assert(rhptee->isFunctionType())((rhptee->isFunctionType()) ? static_cast<void> (0) :
__assert_fail ("rhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 8078, __PRETTY_FUNCTION__))
;
8079 return Sema::FunctionVoidPointer;
8080 }
8081
8082 if (rhptee->isVoidType()) {
8083 if (lhptee->isIncompleteOrObjectType())
8084 return ConvTy;
8085
8086 // As an extension, we allow cast to/from void* to function pointer.
8087 assert(lhptee->isFunctionType())((lhptee->isFunctionType()) ? static_cast<void> (0) :
__assert_fail ("lhptee->isFunctionType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 8087, __PRETTY_FUNCTION__))
;
8088 return Sema::FunctionVoidPointer;
8089 }
8090
8091 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8092 // unqualified versions of compatible types, ...
8093 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8094 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8095 // Check if the pointee types are compatible ignoring the sign.
8096 // We explicitly check for char so that we catch "char" vs
8097 // "unsigned char" on systems where "char" is unsigned.
8098 if (lhptee->isCharType())
8099 ltrans = S.Context.UnsignedCharTy;
8100 else if (lhptee->hasSignedIntegerRepresentation())
8101 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8102
8103 if (rhptee->isCharType())
8104 rtrans = S.Context.UnsignedCharTy;
8105 else if (rhptee->hasSignedIntegerRepresentation())
8106 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8107
8108 if (ltrans == rtrans) {
8109 // Types are compatible ignoring the sign. Qualifier incompatibility
8110 // takes priority over sign incompatibility because the sign
8111 // warning can be disabled.
8112 if (ConvTy != Sema::Compatible)
8113 return ConvTy;
8114
8115 return Sema::IncompatiblePointerSign;
8116 }
8117
8118 // If we are a multi-level pointer, it's possible that our issue is simply
8119 // one of qualification - e.g. char ** -> const char ** is not allowed. If
8120 // the eventual target type is the same and the pointers have the same
8121 // level of indirection, this must be the issue.
8122 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8123 do {
8124 std::tie(lhptee, lhq) =
8125 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8126 std::tie(rhptee, rhq) =
8127 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8128
8129 // Inconsistent address spaces at this point is invalid, even if the
8130 // address spaces would be compatible.
8131 // FIXME: This doesn't catch address space mismatches for pointers of
8132 // different nesting levels, like:
8133 // __local int *** a;
8134 // int ** b = a;
8135 // It's not clear how to actually determine when such pointers are
8136 // invalidly incompatible.
8137 if (lhq.getAddressSpace() != rhq.getAddressSpace())
8138 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8139
8140 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8141
8142 if (lhptee == rhptee)
8143 return Sema::IncompatibleNestedPointerQualifiers;
8144 }
8145
8146 // General pointer incompatibility takes priority over qualifiers.
8147 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8148 return Sema::IncompatibleFunctionPointer;
8149 return Sema::IncompatiblePointer;
8150 }
8151 if (!S.getLangOpts().CPlusPlus &&
8152 S.IsFunctionConversion(ltrans, rtrans, ltrans))
8153 return Sema::IncompatibleFunctionPointer;
8154 return ConvTy;
8155}
8156
8157/// checkBlockPointerTypesForAssignment - This routine determines whether two
8158/// block pointer types are compatible or whether a block and normal pointer
8159/// are compatible. It is more restrict than comparing two function pointer
8160// types.
8161static Sema::AssignConvertType
8162checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8163 QualType RHSType) {
8164 assert(LHSType.isCanonical() && "LHS not canonicalized!")((LHSType.isCanonical() && "LHS not canonicalized!") ?
static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS not canonicalized!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 8164, __PRETTY_FUNCTION__))
;
8165 assert(RHSType.isCanonical() && "RHS not canonicalized!")((RHSType.isCanonical() && "RHS not canonicalized!") ?
static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS not canonicalized!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 8165, __PRETTY_FUNCTION__))
;
8166
8167 QualType lhptee, rhptee;
8168
8169 // get the "pointed to" type (ignoring qualifiers at the top level)
8170 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8171 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8172
8173 // In C++, the types have to match exactly.
8174 if (S.getLangOpts().CPlusPlus)
8175 return Sema::IncompatibleBlockPointer;
8176
8177 Sema::AssignConvertType ConvTy = Sema::Compatible;
8178
8179 // For blocks we enforce that qualifiers are identical.
8180 Qualifiers LQuals = lhptee.getLocalQualifiers();
8181 Qualifiers RQuals = rhptee.getLocalQualifiers();
8182 if (S.getLangOpts().OpenCL) {
8183 LQuals.removeAddressSpace();
8184 RQuals.removeAddressSpace();
8185 }
8186 if (LQuals != RQuals)
8187 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8188
8189 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8190 // assignment.
8191 // The current behavior is similar to C++ lambdas. A block might be
8192 // assigned to a variable iff its return type and parameters are compatible
8193 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8194 // an assignment. Presumably it should behave in way that a function pointer
8195 // assignment does in C, so for each parameter and return type:
8196 // * CVR and address space of LHS should be a superset of CVR and address
8197 // space of RHS.
8198 // * unqualified types should be compatible.
8199 if (S.getLangOpts().OpenCL) {
8200 if (!S.Context.typesAreBlockPointerCompatible(
8201 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8202 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8203 return Sema::IncompatibleBlockPointer;
8204 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8205 return Sema::IncompatibleBlockPointer;
8206
8207 return ConvTy;
8208}
8209
8210/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8211/// for assignment compatibility.
8212static Sema::AssignConvertType
8213checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8214 QualType RHSType) {
8215 assert(LHSType.isCanonical() && "LHS was not canonicalized!")((LHSType.isCanonical() && "LHS was not canonicalized!"
) ? static_cast<void> (0) : __assert_fail ("LHSType.isCanonical() && \"LHS was not canonicalized!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 8215, __PRETTY_FUNCTION__))
;
8216 assert(RHSType.isCanonical() && "RHS was not canonicalized!")((RHSType.isCanonical() && "RHS was not canonicalized!"
) ? static_cast<void> (0) : __assert_fail ("RHSType.isCanonical() && \"RHS was not canonicalized!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 8216, __PRETTY_FUNCTION__))
;
8217
8218 if (LHSType->isObjCBuiltinType()) {
8219 // Class is not compatible with ObjC object pointers.
8220 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8221 !RHSType->isObjCQualifiedClassType())
8222 return Sema::IncompatiblePointer;
8223 return Sema::Compatible;
8224 }
8225 if (RHSType->isObjCBuiltinType()) {
8226 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8227 !LHSType->isObjCQualifiedClassType())
8228 return Sema::IncompatiblePointer;
8229 return Sema::Compatible;
8230 }
8231 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8232 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8233
8234 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8235 // make an exception for id<P>
8236 !LHSType->isObjCQualifiedIdType())
8237 return Sema::CompatiblePointerDiscardsQualifiers;
8238
8239 if (S.Context.typesAreCompatible(LHSType, RHSType))
8240 return Sema::Compatible;
8241 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8242 return Sema::IncompatibleObjCQualifiedId;
8243 return Sema::IncompatiblePointer;
8244}
8245
8246Sema::AssignConvertType
8247Sema::CheckAssignmentConstraints(SourceLocation Loc,
8248 QualType LHSType, QualType RHSType) {
8249 // Fake up an opaque expression. We don't actually care about what
8250 // cast operations are required, so if CheckAssignmentConstraints
8251 // adds casts to this they'll be wasted, but fortunately that doesn't
8252 // usually happen on valid code.
8253 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8254 ExprResult RHSPtr = &RHSExpr;
8255 CastKind K;
8256
8257 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8258}
8259
8260/// This helper function returns true if QT is a vector type that has element
8261/// type ElementType.
8262static bool isVector(QualType QT, QualType ElementType) {
8263 if (const VectorType *VT = QT->getAs<VectorType>())
8264 return VT->getElementType() == ElementType;
8265 return false;
8266}
8267
8268/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8269/// has code to accommodate several GCC extensions when type checking
8270/// pointers. Here are some objectionable examples that GCC considers warnings:
8271///
8272/// int a, *pint;
8273/// short *pshort;
8274/// struct foo *pfoo;
8275///
8276/// pint = pshort; // warning: assignment from incompatible pointer type
8277/// a = pint; // warning: assignment makes integer from pointer without a cast
8278/// pint = a; // warning: assignment makes pointer from integer without a cast
8279/// pint = pfoo; // warning: assignment from incompatible pointer type
8280///
8281/// As a result, the code for dealing with pointers is more complex than the
8282/// C99 spec dictates.
8283///
8284/// Sets 'Kind' for any result kind except Incompatible.
8285Sema::AssignConvertType
8286Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
8287 CastKind &Kind, bool ConvertRHS) {
8288 QualType RHSType = RHS.get()->getType();
8289 QualType OrigLHSType = LHSType;
8290
8291 // Get canonical types. We're not formatting these types, just comparing
8292 // them.
8293 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
8294 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
8295
8296 // Common case: no conversion required.
8297 if (LHSType == RHSType) {
8298 Kind = CK_NoOp;
8299 return Compatible;
8300 }
8301
8302 // If we have an atomic type, try a non-atomic assignment, then just add an
8303 // atomic qualification step.
8304 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
8305 Sema::AssignConvertType result =
8306 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
8307 if (result != Compatible)
8308 return result;
8309 if (Kind != CK_NoOp && ConvertRHS)
8310 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
8311 Kind = CK_NonAtomicToAtomic;
8312 return Compatible;
8313 }
8314
8315 // If the left-hand side is a reference type, then we are in a
8316 // (rare!) case where we've allowed the use of references in C,
8317 // e.g., as a parameter type in a built-in function. In this case,
8318 // just make sure that the type referenced is compatible with the
8319 // right-hand side type. The caller is responsible for adjusting
8320 // LHSType so that the resulting expression does not have reference
8321 // type.
8322 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
8323 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
8324 Kind = CK_LValueBitCast;
8325 return Compatible;
8326 }
8327 return Incompatible;
8328 }
8329
8330 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
8331 // to the same ExtVector type.
8332 if (LHSType->isExtVectorType()) {
8333 if (RHSType->isExtVectorType())
8334 return Incompatible;
8335 if (RHSType->isArithmeticType()) {
8336 // CK_VectorSplat does T -> vector T, so first cast to the element type.
8337 if (ConvertRHS)
8338 RHS = prepareVectorSplat(LHSType, RHS.get());
8339 Kind = CK_VectorSplat;
8340 return Compatible;
8341 }
8342 }
8343
8344 // Conversions to or from vector type.
8345 if (LHSType->isVectorType() || RHSType->isVectorType()) {
8346 if (LHSType->isVectorType() && RHSType->isVectorType()) {
8347 // Allow assignments of an AltiVec vector type to an equivalent GCC
8348 // vector type and vice versa
8349 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8350 Kind = CK_BitCast;
8351 return Compatible;
8352 }
8353
8354 // If we are allowing lax vector conversions, and LHS and RHS are both
8355 // vectors, the total size only needs to be the same. This is a bitcast;
8356 // no bits are changed but the result type is different.
8357 if (isLaxVectorConversion(RHSType, LHSType)) {
8358 Kind = CK_BitCast;
8359 return IncompatibleVectors;
8360 }
8361 }
8362
8363 // When the RHS comes from another lax conversion (e.g. binops between
8364 // scalars and vectors) the result is canonicalized as a vector. When the
8365 // LHS is also a vector, the lax is allowed by the condition above. Handle
8366 // the case where LHS is a scalar.
8367 if (LHSType->isScalarType()) {
8368 const VectorType *VecType = RHSType->getAs<VectorType>();
8369 if (VecType && VecType->getNumElements() == 1 &&
8370 isLaxVectorConversion(RHSType, LHSType)) {
8371 ExprResult *VecExpr = &RHS;
8372 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8373 Kind = CK_BitCast;
8374 return Compatible;
8375 }
8376 }
8377
8378 return Incompatible;
8379 }
8380
8381 // Diagnose attempts to convert between __float128 and long double where
8382 // such conversions currently can't be handled.
8383 if (unsupportedTypeConversion(*this, LHSType, RHSType))
8384 return Incompatible;
8385
8386 // Disallow assigning a _Complex to a real type in C++ mode since it simply
8387 // discards the imaginary part.
8388 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8389 !LHSType->getAs<ComplexType>())
8390 return Incompatible;
8391
8392 // Arithmetic conversions.
8393 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8394 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8395 if (ConvertRHS)
8396 Kind = PrepareScalarCast(RHS, LHSType);
8397 return Compatible;
8398 }
8399
8400 // Conversions to normal pointers.
8401 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8402 // U* -> T*
8403 if (isa<PointerType>(RHSType)) {
8404 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8405 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8406 if (AddrSpaceL != AddrSpaceR)
8407 Kind = CK_AddressSpaceConversion;
8408 else if (Context.hasCvrSimilarType(RHSType, LHSType))
8409 Kind = CK_NoOp;
8410 else
8411 Kind = CK_BitCast;
8412 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8413 }
8414
8415 // int -> T*
8416 if (RHSType->isIntegerType()) {
8417 Kind = CK_IntegralToPointer; // FIXME: null?
8418 return IntToPointer;
8419 }
8420
8421 // C pointers are not compatible with ObjC object pointers,
8422 // with two exceptions:
8423 if (isa<ObjCObjectPointerType>(RHSType)) {
8424 // - conversions to void*
8425 if (LHSPointer->getPointeeType()->isVoidType()) {
8426 Kind = CK_BitCast;
8427 return Compatible;
8428 }
8429
8430 // - conversions from 'Class' to the redefinition type
8431 if (RHSType->isObjCClassType() &&
8432 Context.hasSameType(LHSType,
8433 Context.getObjCClassRedefinitionType())) {
8434 Kind = CK_BitCast;
8435 return Compatible;
8436 }
8437
8438 Kind = CK_BitCast;
8439 return IncompatiblePointer;
8440 }
8441
8442 // U^ -> void*
8443 if (RHSType->getAs<BlockPointerType>()) {
8444 if (LHSPointer->getPointeeType()->isVoidType()) {
8445 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8446 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8447 ->getPointeeType()
8448 .getAddressSpace();
8449 Kind =
8450 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8451 return Compatible;
8452 }
8453 }
8454
8455 return Incompatible;
8456 }
8457
8458 // Conversions to block pointers.
8459 if (isa<BlockPointerType>(LHSType)) {
8460 // U^ -> T^
8461 if (RHSType->isBlockPointerType()) {
8462 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8463 ->getPointeeType()
8464 .getAddressSpace();
8465 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8466 ->getPointeeType()
8467 .getAddressSpace();
8468 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8469 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8470 }
8471
8472 // int or null -> T^
8473 if (RHSType->isIntegerType()) {
8474 Kind = CK_IntegralToPointer; // FIXME: null
8475 return IntToBlockPointer;
8476 }
8477
8478 // id -> T^
8479 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8480 Kind = CK_AnyPointerToBlockPointerCast;
8481 return Compatible;
8482 }
8483
8484 // void* -> T^
8485 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8486 if (RHSPT->getPointeeType()->isVoidType()) {
8487 Kind = CK_AnyPointerToBlockPointerCast;
8488 return Compatible;
8489 }
8490
8491 return Incompatible;
8492 }
8493
8494 // Conversions to Objective-C pointers.
8495 if (isa<ObjCObjectPointerType>(LHSType)) {
8496 // A* -> B*
8497 if (RHSType->isObjCObjectPointerType()) {
8498 Kind = CK_BitCast;
8499 Sema::AssignConvertType result =
8500 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8501 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8502 result == Compatible &&
8503 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8504 result = IncompatibleObjCWeakRef;
8505 return result;
8506 }
8507
8508 // int or null -> A*
8509 if (RHSType->isIntegerType()) {
8510 Kind = CK_IntegralToPointer; // FIXME: null
8511 return IntToPointer;
8512 }
8513
8514 // In general, C pointers are not compatible with ObjC object pointers,
8515 // with two exceptions:
8516 if (isa<PointerType>(RHSType)) {
8517 Kind = CK_CPointerToObjCPointerCast;
8518
8519 // - conversions from 'void*'
8520 if (RHSType->isVoidPointerType()) {
8521 return Compatible;
8522 }
8523
8524 // - conversions to 'Class' from its redefinition type
8525 if (LHSType->isObjCClassType() &&
8526 Context.hasSameType(RHSType,
8527 Context.getObjCClassRedefinitionType())) {
8528 return Compatible;
8529 }
8530
8531 return IncompatiblePointer;
8532 }
8533
8534 // Only under strict condition T^ is compatible with an Objective-C pointer.
8535 if (RHSType->isBlockPointerType() &&
8536 LHSType->isBlockCompatibleObjCPointerType(Context)) {
8537 if (ConvertRHS)
8538 maybeExtendBlockObject(RHS);
8539 Kind = CK_BlockPointerToObjCPointerCast;
8540 return Compatible;
8541 }
8542
8543 return Incompatible;
8544 }
8545
8546 // Conversions from pointers that are not covered by the above.
8547 if (isa<PointerType>(RHSType)) {
8548 // T* -> _Bool
8549 if (LHSType == Context.BoolTy) {
8550 Kind = CK_PointerToBoolean;
8551 return Compatible;
8552 }
8553
8554 // T* -> int
8555 if (LHSType->isIntegerType()) {
8556 Kind = CK_PointerToIntegral;
8557 return PointerToInt;
8558 }
8559
8560 return Incompatible;
8561 }
8562
8563 // Conversions from Objective-C pointers that are not covered by the above.
8564 if (isa<ObjCObjectPointerType>(RHSType)) {
8565 // T* -> _Bool
8566 if (LHSType == Context.BoolTy) {
8567 Kind = CK_PointerToBoolean;
8568 return Compatible;
8569 }
8570
8571 // T* -> int
8572 if (LHSType->isIntegerType()) {
8573 Kind = CK_PointerToIntegral;
8574 return PointerToInt;
8575 }
8576
8577 return Incompatible;
8578 }
8579
8580 // struct A -> struct B
8581 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8582 if (Context.typesAreCompatible(LHSType, RHSType)) {
8583 Kind = CK_NoOp;
8584 return Compatible;
8585 }
8586 }
8587
8588 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8589 Kind = CK_IntToOCLSampler;
8590 return Compatible;
8591 }
8592
8593 return Incompatible;
8594}
8595
8596/// Constructs a transparent union from an expression that is
8597/// used to initialize the transparent union.
8598static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8599 ExprResult &EResult, QualType UnionType,
8600 FieldDecl *Field) {
8601 // Build an initializer list that designates the appropriate member
8602 // of the transparent union.
8603 Expr *E = EResult.get();
8604 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8605 E, SourceLocation());
8606 Initializer->setType(UnionType);
8607 Initializer->setInitializedFieldInUnion(Field);
8608
8609 // Build a compound literal constructing a value of the transparent
8610 // union type from this initializer list.
8611 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8612 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8613 VK_RValue, Initializer, false);
8614}
8615
8616Sema::AssignConvertType
8617Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8618 ExprResult &RHS) {
8619 QualType RHSType = RHS.get()->getType();
8620
8621 // If the ArgType is a Union type, we want to handle a potential
8622 // transparent_union GCC extension.
8623 const RecordType *UT = ArgType->getAsUnionType();
8624 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8625 return Incompatible;
8626
8627 // The field to initialize within the transparent union.
8628 RecordDecl *UD = UT->getDecl();
8629 FieldDecl *InitField = nullptr;
8630 // It's compatible if the expression matches any of the fields.
8631 for (auto *it : UD->fields()) {
8632 if (it->getType()->isPointerType()) {
8633 // If the transparent union contains a pointer type, we allow:
8634 // 1) void pointer
8635 // 2) null pointer constant
8636 if (RHSType->isPointerType())
8637 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8638 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8639 InitField = it;
8640 break;
8641 }
8642
8643 if (RHS.get()->isNullPointerConstant(Context,
8644 Expr::NPC_ValueDependentIsNull)) {
8645 RHS = ImpCastExprToType(RHS.get(), it->getType(),
8646 CK_NullToPointer);
8647 InitField = it;
8648 break;
8649 }
8650 }
8651
8652 CastKind Kind;
8653 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8654 == Compatible) {
8655 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8656 InitField = it;
8657 break;
8658 }
8659 }
8660
8661 if (!InitField)
8662 return Incompatible;
8663
8664 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8665 return Compatible;
8666}
8667
8668Sema::AssignConvertType
8669Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8670 bool Diagnose,
8671 bool DiagnoseCFAudited,
8672 bool ConvertRHS) {
8673 // We need to be able to tell the caller whether we diagnosed a problem, if
8674 // they ask us to issue diagnostics.
8675 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed")(((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed"
) ? static_cast<void> (0) : __assert_fail ("(ConvertRHS || !Diagnose) && \"can't indicate whether we diagnosed\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 8675, __PRETTY_FUNCTION__))
;
8676
8677 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8678 // we can't avoid *all* modifications at the moment, so we need some somewhere
8679 // to put the updated value.
8680 ExprResult LocalRHS = CallerRHS;
8681 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8682
8683 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8684 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8685 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8686 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8687 Diag(RHS.get()->getExprLoc(),
8688 diag::warn_noderef_to_dereferenceable_pointer)
8689 << RHS.get()->getSourceRange();
8690 }
8691 }
8692 }
8693
8694 if (getLangOpts().CPlusPlus) {
8695 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8696 // C++ 5.17p3: If the left operand is not of class type, the
8697 // expression is implicitly converted (C++ 4) to the
8698 // cv-unqualified type of the left operand.
8699 QualType RHSType = RHS.get()->getType();
8700 if (Diagnose) {
8701 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8702 AA_Assigning);
8703 } else {
8704 ImplicitConversionSequence ICS =
8705 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8706 /*SuppressUserConversions=*/false,
8707 AllowedExplicit::None,
8708 /*InOverloadResolution=*/false,
8709 /*CStyle=*/false,
8710 /*AllowObjCWritebackConversion=*/false);
8711 if (ICS.isFailure())
8712 return Incompatible;
8713 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8714 ICS, AA_Assigning);
8715 }
8716 if (RHS.isInvalid())
8717 return Incompatible;
8718 Sema::AssignConvertType result = Compatible;
8719 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8720 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8721 result = IncompatibleObjCWeakRef;
8722 return result;
8723 }
8724
8725 // FIXME: Currently, we fall through and treat C++ classes like C
8726 // structures.
8727 // FIXME: We also fall through for atomics; not sure what should
8728 // happen there, though.
8729 } else if (RHS.get()->getType() == Context.OverloadTy) {
8730 // As a set of extensions to C, we support overloading on functions. These
8731 // functions need to be resolved here.
8732 DeclAccessPair DAP;
8733 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8734 RHS.get(), LHSType, /*Complain=*/false, DAP))
8735 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8736 else
8737 return Incompatible;
8738 }
8739
8740 // C99 6.5.16.1p1: the left operand is a pointer and the right is
8741 // a null pointer constant.
8742 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8743 LHSType->isBlockPointerType()) &&
8744 RHS.get()->isNullPointerConstant(Context,
8745 Expr::NPC_ValueDependentIsNull)) {
8746 if (Diagnose || ConvertRHS) {
8747 CastKind Kind;
8748 CXXCastPath Path;
8749 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8750 /*IgnoreBaseAccess=*/false, Diagnose);
8751 if (ConvertRHS)
8752 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8753 }
8754 return Compatible;
8755 }
8756
8757 // OpenCL queue_t type assignment.
8758 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8759 Context, Expr::NPC_ValueDependentIsNull)) {
8760 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8761 return Compatible;
8762 }
8763
8764 // This check seems unnatural, however it is necessary to ensure the proper
8765 // conversion of functions/arrays. If the conversion were done for all
8766 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8767 // expressions that suppress this implicit conversion (&, sizeof).
8768 //
8769 // Suppress this for references: C++ 8.5.3p5.
8770 if (!LHSType->isReferenceType()) {
8771 // FIXME: We potentially allocate here even if ConvertRHS is false.
8772 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8773 if (RHS.isInvalid())
8774 return Incompatible;
8775 }
8776 CastKind Kind;
8777 Sema::AssignConvertType result =
8778 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8779
8780 // C99 6.5.16.1p2: The value of the right operand is converted to the
8781 // type of the assignment expression.
8782 // CheckAssignmentConstraints allows the left-hand side to be a reference,
8783 // so that we can use references in built-in functions even in C.
8784 // The getNonReferenceType() call makes sure that the resulting expression
8785 // does not have reference type.
8786 if (result != Incompatible && RHS.get()->getType() != LHSType) {
8787 QualType Ty = LHSType.getNonLValueExprType(Context);
8788 Expr *E = RHS.get();
8789
8790 // Check for various Objective-C errors. If we are not reporting
8791 // diagnostics and just checking for errors, e.g., during overload
8792 // resolution, return Incompatible to indicate the failure.
8793 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8794 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8795 Diagnose, DiagnoseCFAudited) != ACR_okay) {
8796 if (!Diagnose)
8797 return Incompatible;
8798 }
8799 if (getLangOpts().ObjC &&
8800 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8801 E->getType(), E, Diagnose) ||
8802 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8803 if (!Diagnose)
8804 return Incompatible;
8805 // Replace the expression with a corrected version and continue so we
8806 // can find further errors.
8807 RHS = E;
8808 return Compatible;
8809 }
8810
8811 if (ConvertRHS)
8812 RHS = ImpCastExprToType(E, Ty, Kind);
8813 }
8814
8815 return result;
8816}
8817
8818namespace {
8819/// The original operand to an operator, prior to the application of the usual
8820/// arithmetic conversions and converting the arguments of a builtin operator
8821/// candidate.
8822struct OriginalOperand {
8823 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8824 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8825 Op = MTE->getSubExpr();
8826 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8827 Op = BTE->getSubExpr();
8828 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8829 Orig = ICE->getSubExprAsWritten();
8830 Conversion = ICE->getConversionFunction();
8831 }
8832 }
8833
8834 QualType getType() const { return Orig->getType(); }
8835
8836 Expr *Orig;
8837 NamedDecl *Conversion;
8838};
8839}
8840
8841QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8842 ExprResult &RHS) {
8843 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8844
8845 Diag(Loc, diag::err_typecheck_invalid_operands)
8846 << OrigLHS.getType() << OrigRHS.getType()
8847 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8848
8849 // If a user-defined conversion was applied to either of the operands prior
8850 // to applying the built-in operator rules, tell the user about it.
8851 if (OrigLHS.Conversion) {
8852 Diag(OrigLHS.Conversion->getLocation(),
8853 diag::note_typecheck_invalid_operands_converted)
8854 << 0 << LHS.get()->getType();
8855 }
8856 if (OrigRHS.Conversion) {
8857 Diag(OrigRHS.Conversion->getLocation(),
8858 diag::note_typecheck_invalid_operands_converted)
8859 << 1 << RHS.get()->getType();
8860 }
8861
8862 return QualType();
8863}
8864
8865// Diagnose cases where a scalar was implicitly converted to a vector and
8866// diagnose the underlying types. Otherwise, diagnose the error
8867// as invalid vector logical operands for non-C++ cases.
8868QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8869 ExprResult &RHS) {
8870 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8871 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8872
8873 bool LHSNatVec = LHSType->isVectorType();
8874 bool RHSNatVec = RHSType->isVectorType();
8875
8876 if (!(LHSNatVec && RHSNatVec)) {
8877 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8878 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8879 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8880 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8881 << Vector->getSourceRange();
8882 return QualType();
8883 }
8884
8885 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8886 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8887 << RHS.get()->getSourceRange();
8888
8889 return QualType();
8890}
8891
8892/// Try to convert a value of non-vector type to a vector type by converting
8893/// the type to the element type of the vector and then performing a splat.
8894/// If the language is OpenCL, we only use conversions that promote scalar
8895/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8896/// for float->int.
8897///
8898/// OpenCL V2.0 6.2.6.p2:
8899/// An error shall occur if any scalar operand type has greater rank
8900/// than the type of the vector element.
8901///
8902/// \param scalar - if non-null, actually perform the conversions
8903/// \return true if the operation fails (but without diagnosing the failure)
8904static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8905 QualType scalarTy,
8906 QualType vectorEltTy,
8907 QualType vectorTy,
8908 unsigned &DiagID) {
8909 // The conversion to apply to the scalar before splatting it,
8910 // if necessary.
8911 CastKind scalarCast = CK_NoOp;
8912
8913 if (vectorEltTy->isIntegralType(S.Context)) {
8914 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8915 (scalarTy->isIntegerType() &&
8916 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8917 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8918 return true;
8919 }
8920 if (!scalarTy->isIntegralType(S.Context))
8921 return true;
8922 scalarCast = CK_IntegralCast;
8923 } else if (vectorEltTy->isRealFloatingType()) {
8924 if (scalarTy->isRealFloatingType()) {
8925 if (S.getLangOpts().OpenCL &&
8926 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8927 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8928 return true;
8929 }
8930 scalarCast = CK_FloatingCast;
8931 }
8932 else if (scalarTy->isIntegralType(S.Context))
8933 scalarCast = CK_IntegralToFloating;
8934 else
8935 return true;
8936 } else {
8937 return true;
8938 }
8939
8940 // Adjust scalar if desired.
8941 if (scalar) {
8942 if (scalarCast != CK_NoOp)
8943 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8944 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8945 }
8946 return false;
8947}
8948
8949/// Convert vector E to a vector with the same number of elements but different
8950/// element type.
8951static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8952 const auto *VecTy = E->getType()->getAs<VectorType>();
8953 assert(VecTy && "Expression E must be a vector")((VecTy && "Expression E must be a vector") ? static_cast
<void> (0) : __assert_fail ("VecTy && \"Expression E must be a vector\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 8953, __PRETTY_FUNCTION__))
;
8954 QualType NewVecTy = S.Context.getVectorType(ElementType,
8955 VecTy->getNumElements(),
8956 VecTy->getVectorKind());
8957
8958 // Look through the implicit cast. Return the subexpression if its type is
8959 // NewVecTy.
8960 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8961 if (ICE->getSubExpr()->getType() == NewVecTy)
8962 return ICE->getSubExpr();
8963
8964 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8965 return S.ImpCastExprToType(E, NewVecTy, Cast);
8966}
8967
8968/// Test if a (constant) integer Int can be casted to another integer type
8969/// IntTy without losing precision.
8970static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8971 QualType OtherIntTy) {
8972 QualType IntTy = Int->get()->getType().getUnqualifiedType();
8973
8974 // Reject cases where the value of the Int is unknown as that would
8975 // possibly cause truncation, but accept cases where the scalar can be
8976 // demoted without loss of precision.
8977 Expr::EvalResult EVResult;
8978 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8979 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8980 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8981 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8982
8983 if (CstInt) {
8984 // If the scalar is constant and is of a higher order and has more active
8985 // bits that the vector element type, reject it.
8986 llvm::APSInt Result = EVResult.Val.getInt();
8987 unsigned NumBits = IntSigned
8988 ? (Result.isNegative() ? Result.getMinSignedBits()
8989 : Result.getActiveBits())
8990 : Result.getActiveBits();
8991 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8992 return true;
8993
8994 // If the signedness of the scalar type and the vector element type
8995 // differs and the number of bits is greater than that of the vector
8996 // element reject it.
8997 return (IntSigned != OtherIntSigned &&
8998 NumBits > S.Context.getIntWidth(OtherIntTy));
8999 }
9000
9001 // Reject cases where the value of the scalar is not constant and it's
9002 // order is greater than that of the vector element type.
9003 return (Order < 0);
9004}
9005
9006/// Test if a (constant) integer Int can be casted to floating point type
9007/// FloatTy without losing precision.
9008static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9009 QualType FloatTy) {
9010 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9011
9012 // Determine if the integer constant can be expressed as a floating point
9013 // number of the appropriate type.
9014 Expr::EvalResult EVResult;
9015 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9016
9017 uint64_t Bits = 0;
9018 if (CstInt) {
9019 // Reject constants that would be truncated if they were converted to
9020 // the floating point type. Test by simple to/from conversion.
9021 // FIXME: Ideally the conversion to an APFloat and from an APFloat
9022 // could be avoided if there was a convertFromAPInt method
9023 // which could signal back if implicit truncation occurred.
9024 llvm::APSInt Result = EVResult.Val.getInt();
9025 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9026 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9027 llvm::APFloat::rmTowardZero);
9028 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9029 !IntTy->hasSignedIntegerRepresentation());
9030 bool Ignored = false;
9031 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9032 &Ignored);
9033 if (Result != ConvertBack)
9034 return true;
9035 } else {
9036 // Reject types that cannot be fully encoded into the mantissa of
9037 // the float.
9038 Bits = S.Context.getTypeSize(IntTy);
9039 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9040 S.Context.getFloatTypeSemantics(FloatTy));
9041 if (Bits > FloatPrec)
9042 return true;
9043 }
9044
9045 return false;
9046}
9047
9048/// Attempt to convert and splat Scalar into a vector whose types matches
9049/// Vector following GCC conversion rules. The rule is that implicit
9050/// conversion can occur when Scalar can be casted to match Vector's element
9051/// type without causing truncation of Scalar.
9052static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9053 ExprResult *Vector) {
9054 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9055 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9056 const VectorType *VT = VectorTy->getAs<VectorType>();
9057
9058 assert(!isa<ExtVectorType>(VT) &&((!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 9059, __PRETTY_FUNCTION__))
9059 "ExtVectorTypes should not be handled here!")((!isa<ExtVectorType>(VT) && "ExtVectorTypes should not be handled here!"
) ? static_cast<void> (0) : __assert_fail ("!isa<ExtVectorType>(VT) && \"ExtVectorTypes should not be handled here!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 9059, __PRETTY_FUNCTION__))
;
9060
9061 QualType VectorEltTy = VT->getElementType();
9062
9063 // Reject cases where the vector element type or the scalar element type are
9064 // not integral or floating point types.
9065 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9066 return true;
9067
9068 // The conversion to apply to the scalar before splatting it,
9069 // if necessary.
9070 CastKind ScalarCast = CK_NoOp;
9071
9072 // Accept cases where the vector elements are integers and the scalar is
9073 // an integer.
9074 // FIXME: Notionally if the scalar was a floating point value with a precise
9075 // integral representation, we could cast it to an appropriate integer
9076 // type and then perform the rest of the checks here. GCC will perform
9077 // this conversion in some cases as determined by the input language.
9078 // We should accept it on a language independent basis.
9079 if (VectorEltTy->isIntegralType(S.Context) &&
9080 ScalarTy->isIntegralType(S.Context) &&
9081 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9082
9083 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9084 return true;
9085
9086 ScalarCast = CK_IntegralCast;
9087 } else if (VectorEltTy->isIntegralType(S.Context) &&
9088 ScalarTy->isRealFloatingType()) {
9089 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9090 ScalarCast = CK_FloatingToIntegral;
9091 else
9092 return true;
9093 } else if (VectorEltTy->isRealFloatingType()) {
9094 if (ScalarTy->isRealFloatingType()) {
9095
9096 // Reject cases where the scalar type is not a constant and has a higher
9097 // Order than the vector element type.
9098 llvm::APFloat Result(0.0);
9099 bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
9100 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9101 if (!CstScalar && Order < 0)
9102 return true;
9103
9104 // If the scalar cannot be safely casted to the vector element type,
9105 // reject it.
9106 if (CstScalar) {
9107 bool Truncated = false;
9108 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9109 llvm::APFloat::rmNearestTiesToEven, &Truncated);
9110 if (Truncated)
9111 return true;
9112 }
9113
9114 ScalarCast = CK_FloatingCast;
9115 } else if (ScalarTy->isIntegralType(S.Context)) {
9116 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9117 return true;
9118
9119 ScalarCast = CK_IntegralToFloating;
9120 } else
9121 return true;
9122 }
9123
9124 // Adjust scalar if desired.
9125 if (Scalar) {
9126 if (ScalarCast != CK_NoOp)
9127 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9128 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9129 }
9130 return false;
9131}
9132
9133QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9134 SourceLocation Loc, bool IsCompAssign,
9135 bool AllowBothBool,
9136 bool AllowBoolConversions) {
9137 if (!IsCompAssign) {
9138 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9139 if (LHS.isInvalid())
9140 return QualType();
9141 }
9142 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9143 if (RHS.isInvalid())
9144 return QualType();
9145
9146 // For conversion purposes, we ignore any qualifiers.
9147 // For example, "const float" and "float" are equivalent.
9148 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9149 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9150
9151 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9152 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9153 assert(LHSVecType || RHSVecType)((LHSVecType || RHSVecType) ? static_cast<void> (0) : __assert_fail
("LHSVecType || RHSVecType", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 9153, __PRETTY_FUNCTION__))
;
9154
9155 // AltiVec-style "vector bool op vector bool" combinations are allowed
9156 // for some operators but not others.
9157 if (!AllowBothBool &&
9158 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9159 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9160 return InvalidOperands(Loc, LHS, RHS);
9161
9162 // If the vector types are identical, return.
9163 if (Context.hasSameType(LHSType, RHSType))
9164 return LHSType;
9165
9166 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9167 if (LHSVecType && RHSVecType &&
9168 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9169 if (isa<ExtVectorType>(LHSVecType)) {
9170 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9171 return LHSType;
9172 }
9173
9174 if (!IsCompAssign)
9175 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9176 return RHSType;
9177 }
9178
9179 // AllowBoolConversions says that bool and non-bool AltiVec vectors
9180 // can be mixed, with the result being the non-bool type. The non-bool
9181 // operand must have integer element type.
9182 if (AllowBoolConversions && LHSVecType && RHSVecType &&
9183 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9184 (Context.getTypeSize(LHSVecType->getElementType()) ==
9185 Context.getTypeSize(RHSVecType->getElementType()))) {
9186 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9187 LHSVecType->getElementType()->isIntegerType() &&
9188 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9189 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9190 return LHSType;
9191 }
9192 if (!IsCompAssign &&
9193 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9194 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9195 RHSVecType->getElementType()->isIntegerType()) {
9196 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9197 return RHSType;
9198 }
9199 }
9200
9201 // If there's a vector type and a scalar, try to convert the scalar to
9202 // the vector element type and splat.
9203 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9204 if (!RHSVecType) {
9205 if (isa<ExtVectorType>(LHSVecType)) {
9206 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9207 LHSVecType->getElementType(), LHSType,
9208 DiagID))
9209 return LHSType;
9210 } else {
9211 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9212 return LHSType;
9213 }
9214 }
9215 if (!LHSVecType) {
9216 if (isa<ExtVectorType>(RHSVecType)) {
9217 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9218 LHSType, RHSVecType->getElementType(),
9219 RHSType, DiagID))
9220 return RHSType;
9221 } else {
9222 if (LHS.get()->getValueKind() == VK_LValue ||
9223 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
9224 return RHSType;
9225 }
9226 }
9227
9228 // FIXME: The code below also handles conversion between vectors and
9229 // non-scalars, we should break this down into fine grained specific checks
9230 // and emit proper diagnostics.
9231 QualType VecType = LHSVecType ? LHSType : RHSType;
9232 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
9233 QualType OtherType = LHSVecType ? RHSType : LHSType;
9234 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
9235 if (isLaxVectorConversion(OtherType, VecType)) {
9236 // If we're allowing lax vector conversions, only the total (data) size
9237 // needs to be the same. For non compound assignment, if one of the types is
9238 // scalar, the result is always the vector type.
9239 if (!IsCompAssign) {
9240 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
9241 return VecType;
9242 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
9243 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
9244 // type. Note that this is already done by non-compound assignments in
9245 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
9246 // <1 x T> -> T. The result is also a vector type.
9247 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
9248 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
9249 ExprResult *RHSExpr = &RHS;
9250 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
9251 return VecType;
9252 }
9253 }
9254
9255 // Okay, the expression is invalid.
9256
9257 // If there's a non-vector, non-real operand, diagnose that.
9258 if ((!RHSVecType && !RHSType->isRealType()) ||
9259 (!LHSVecType && !LHSType->isRealType())) {
9260 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
9261 << LHSType << RHSType
9262 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9263 return QualType();
9264 }
9265
9266 // OpenCL V1.1 6.2.6.p1:
9267 // If the operands are of more than one vector type, then an error shall
9268 // occur. Implicit conversions between vector types are not permitted, per
9269 // section 6.2.1.
9270 if (getLangOpts().OpenCL &&
9271 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
9272 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
9273 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
9274 << RHSType;
9275 return QualType();
9276 }
9277
9278
9279 // If there is a vector type that is not a ExtVector and a scalar, we reach
9280 // this point if scalar could not be converted to the vector's element type
9281 // without truncation.
9282 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
9283 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
9284 QualType Scalar = LHSVecType ? RHSType : LHSType;
9285 QualType Vector = LHSVecType ? LHSType : RHSType;
9286 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
9287 Diag(Loc,
9288 diag::err_typecheck_vector_not_convertable_implict_truncation)
9289 << ScalarOrVector << Scalar << Vector;
9290
9291 return QualType();
9292 }
9293
9294 // Otherwise, use the generic diagnostic.
9295 Diag(Loc, DiagID)
9296 << LHSType << RHSType
9297 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9298 return QualType();
9299}
9300
9301// checkArithmeticNull - Detect when a NULL constant is used improperly in an
9302// expression. These are mainly cases where the null pointer is used as an
9303// integer instead of a pointer.
9304static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
9305 SourceLocation Loc, bool IsCompare) {
9306 // The canonical way to check for a GNU null is with isNullPointerConstant,
9307 // but we use a bit of a hack here for speed; this is a relatively
9308 // hot path, and isNullPointerConstant is slow.
9309 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
9310 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
9311
9312 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
9313
9314 // Avoid analyzing cases where the result will either be invalid (and
9315 // diagnosed as such) or entirely valid and not something to warn about.
9316 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
9317 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
9318 return;
9319
9320 // Comparison operations would not make sense with a null pointer no matter
9321 // what the other expression is.
9322 if (!IsCompare) {
9323 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
9324 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
9325 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
9326 return;
9327 }
9328
9329 // The rest of the operations only make sense with a null pointer
9330 // if the other expression is a pointer.
9331 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
9332 NonNullType->canDecayToPointerType())
9333 return;
9334
9335 S.Diag(Loc, diag::warn_null_in_comparison_operation)
9336 << LHSNull /* LHS is NULL */ << NonNullType
9337 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9338}
9339
9340static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
9341 SourceLocation Loc) {
9342 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
9343 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9344 if (!LUE || !RUE)
9345 return;
9346 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9347 RUE->getKind() != UETT_SizeOf)
9348 return;
9349
9350 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
9351 QualType LHSTy = LHSArg->getType();
9352 QualType RHSTy;
9353
9354 if (RUE->isArgumentType())
9355 RHSTy = RUE->getArgumentType();
9356 else
9357 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9358
9359 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
9360 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
9361 return;
9362
9363 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9364 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9365 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9366 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
9367 << LHSArgDecl;
9368 }
9369 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
9370 QualType ArrayElemTy = ArrayTy->getElementType();
9371 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
9372 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
9373 ArrayElemTy->isCharType() ||
9374 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
9375 return;
9376 S.Diag(Loc, diag::warn_division_sizeof_array)
9377 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
9378 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
9379 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
9380 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
9381 << LHSArgDecl;
9382 }
9383
9384 S.Diag(Loc, diag::note_precedence_silence) << RHS;
9385 }
9386}
9387
9388static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9389 ExprResult &RHS,
9390 SourceLocation Loc, bool IsDiv) {
9391 // Check for division/remainder by zero.
9392 Expr::EvalResult RHSValue;
9393 if (!RHS.get()->isValueDependent() &&
9394 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9395 RHSValue.Val.getInt() == 0)
9396 S.DiagRuntimeBehavior(Loc, RHS.get(),
9397 S.PDiag(diag::warn_remainder_division_by_zero)
9398 << IsDiv << RHS.get()->getSourceRange());
9399}
9400
9401QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9402 SourceLocation Loc,
9403 bool IsCompAssign, bool IsDiv) {
9404 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9405
9406 if (LHS.get()->getType()->isVectorType() ||
9407 RHS.get()->getType()->isVectorType())
9408 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9409 /*AllowBothBool*/getLangOpts().AltiVec,
9410 /*AllowBoolConversions*/false);
9411
9412 QualType compType = UsualArithmeticConversions(
9413 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9414 if (LHS.isInvalid() || RHS.isInvalid())
9415 return QualType();
9416
9417
9418 if (compType.isNull() || !compType->isArithmeticType())
9419 return InvalidOperands(Loc, LHS, RHS);
9420 if (IsDiv) {
9421 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9422 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
9423 }
9424 return compType;
9425}
9426
9427QualType Sema::CheckRemainderOperands(
9428 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9429 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9430
9431 if (LHS.get()->getType()->isVectorType() ||
9432 RHS.get()->getType()->isVectorType()) {
9433 if (LHS.get()->getType()->hasIntegerRepresentation() &&
9434 RHS.get()->getType()->hasIntegerRepresentation())
9435 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9436 /*AllowBothBool*/getLangOpts().AltiVec,
9437 /*AllowBoolConversions*/false);
9438 return InvalidOperands(Loc, LHS, RHS);
9439 }
9440
9441 QualType compType = UsualArithmeticConversions(
9442 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
9443 if (LHS.isInvalid() || RHS.isInvalid())
9444 return QualType();
9445
9446 if (compType.isNull() || !compType->isIntegerType())
9447 return InvalidOperands(Loc, LHS, RHS);
9448 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9449 return compType;
9450}
9451
9452/// Diagnose invalid arithmetic on two void pointers.
9453static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9454 Expr *LHSExpr, Expr *RHSExpr) {
9455 S.Diag(Loc, S.getLangOpts().CPlusPlus
9456 ? diag::err_typecheck_pointer_arith_void_type
9457 : diag::ext_gnu_void_ptr)
9458 << 1 /* two pointers */ << LHSExpr->getSourceRange()
9459 << RHSExpr->getSourceRange();
9460}
9461
9462/// Diagnose invalid arithmetic on a void pointer.
9463static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9464 Expr *Pointer) {
9465 S.Diag(Loc, S.getLangOpts().CPlusPlus
9466 ? diag::err_typecheck_pointer_arith_void_type
9467 : diag::ext_gnu_void_ptr)
9468 << 0 /* one pointer */ << Pointer->getSourceRange();
9469}
9470
9471/// Diagnose invalid arithmetic on a null pointer.
9472///
9473/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9474/// idiom, which we recognize as a GNU extension.
9475///
9476static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9477 Expr *Pointer, bool IsGNUIdiom) {
9478 if (IsGNUIdiom)
9479 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9480 << Pointer->getSourceRange();
9481 else
9482 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9483 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9484}
9485
9486/// Diagnose invalid arithmetic on two function pointers.
9487static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9488 Expr *LHS, Expr *RHS) {
9489 assert(LHS->getType()->isAnyPointerType())((LHS->getType()->isAnyPointerType()) ? static_cast<
void> (0) : __assert_fail ("LHS->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 9489, __PRETTY_FUNCTION__))
;
9490 assert(RHS->getType()->isAnyPointerType())((RHS->getType()->isAnyPointerType()) ? static_cast<
void> (0) : __assert_fail ("RHS->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 9490, __PRETTY_FUNCTION__))
;
9491 S.Diag(Loc, S.getLangOpts().CPlusPlus
9492 ? diag::err_typecheck_pointer_arith_function_type
9493 : diag::ext_gnu_ptr_func_arith)
9494 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9495 // We only show the second type if it differs from the first.
9496 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9497 RHS->getType())
9498 << RHS->getType()->getPointeeType()
9499 << LHS->getSourceRange() << RHS->getSourceRange();
9500}
9501
9502/// Diagnose invalid arithmetic on a function pointer.
9503static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9504 Expr *Pointer) {
9505 assert(Pointer->getType()->isAnyPointerType())((Pointer->getType()->isAnyPointerType()) ? static_cast
<void> (0) : __assert_fail ("Pointer->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 9505, __PRETTY_FUNCTION__))
;
9506 S.Diag(Loc, S.getLangOpts().CPlusPlus
9507 ? diag::err_typecheck_pointer_arith_function_type
9508 : diag::ext_gnu_ptr_func_arith)
9509 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9510 << 0 /* one pointer, so only one type */
9511 << Pointer->getSourceRange();
9512}
9513
9514/// Emit error if Operand is incomplete pointer type
9515///
9516/// \returns True if pointer has incomplete type
9517static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
9518 Expr *Operand) {
9519 QualType ResType = Operand->getType();
9520 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9521 ResType = ResAtomicType->getValueType();
9522
9523 assert(ResType->isAnyPointerType() && !ResType->isDependentType())((ResType->isAnyPointerType() && !ResType->isDependentType
()) ? static_cast<void> (0) : __assert_fail ("ResType->isAnyPointerType() && !ResType->isDependentType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 9523, __PRETTY_FUNCTION__))
;
9524 QualType PointeeTy = ResType->getPointeeType();
9525 return S.RequireCompleteType(Loc, PointeeTy,
9526 diag::err_typecheck_arithmetic_incomplete_type,
9527 PointeeTy, Operand->getSourceRange());
9528}
9529
9530/// Check the validity of an arithmetic pointer operand.
9531///
9532/// If the operand has pointer type, this code will check for pointer types
9533/// which are invalid in arithmetic operations. These will be diagnosed
9534/// appropriately, including whether or not the use is supported as an
9535/// extension.
9536///
9537/// \returns True when the operand is valid to use (even if as an extension).
9538static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9539 Expr *Operand) {
9540 QualType ResType = Operand->getType();
9541 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9542 ResType = ResAtomicType->getValueType();
9543
9544 if (!ResType->isAnyPointerType()) return true;
9545
9546 QualType PointeeTy = ResType->getPointeeType();
9547 if (PointeeTy->isVoidType()) {
9548 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9549 return !S.getLangOpts().CPlusPlus;
9550 }
9551 if (PointeeTy->isFunctionType()) {
9552 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9553 return !S.getLangOpts().CPlusPlus;
9554 }
9555
9556 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9557
9558 return true;
9559}
9560
9561/// Check the validity of a binary arithmetic operation w.r.t. pointer
9562/// operands.
9563///
9564/// This routine will diagnose any invalid arithmetic on pointer operands much
9565/// like \see checkArithmeticOpPointerOperand. However, it has special logic
9566/// for emitting a single diagnostic even for operations where both LHS and RHS
9567/// are (potentially problematic) pointers.
9568///
9569/// \returns True when the operand is valid to use (even if as an extension).
9570static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9571 Expr *LHSExpr, Expr *RHSExpr) {
9572 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9573 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9574 if (!isLHSPointer && !isRHSPointer) return true;
9575
9576 QualType LHSPointeeTy, RHSPointeeTy;
9577 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9578 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9579
9580 // if both are pointers check if operation is valid wrt address spaces
9581 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9582 const PointerType *lhsPtr = LHSExpr->getType()->castAs<PointerType>();
9583 const PointerType *rhsPtr = RHSExpr->getType()->castAs<PointerType>();
9584 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9585 S.Diag(Loc,
9586 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9587 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9588 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9589 return false;
9590 }
9591 }
9592
9593 // Check for arithmetic on pointers to incomplete types.
9594 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9595 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9596 if (isLHSVoidPtr || isRHSVoidPtr) {
9597 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9598 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9599 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9600
9601 return !S.getLangOpts().CPlusPlus;
9602 }
9603
9604 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9605 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9606 if (isLHSFuncPtr || isRHSFuncPtr) {
9607 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9608 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9609 RHSExpr);
9610 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9611
9612 return !S.getLangOpts().CPlusPlus;
9613 }
9614
9615 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9616 return false;
9617 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9618 return false;
9619
9620 return true;
9621}
9622
9623/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9624/// literal.
9625static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9626 Expr *LHSExpr, Expr *RHSExpr) {
9627 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9628 Expr* IndexExpr = RHSExpr;
9629 if (!StrExpr) {
9630 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9631 IndexExpr = LHSExpr;
9632 }
9633
9634 bool IsStringPlusInt = StrExpr &&
9635 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9636 if (!IsStringPlusInt || IndexExpr->isValueDependent())
9637 return;
9638
9639 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9640 Self.Diag(OpLoc, diag::warn_string_plus_int)
9641 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9642
9643 // Only print a fixit for "str" + int, not for int + "str".
9644 if (IndexExpr == RHSExpr) {
9645 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9646 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9647 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9648 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9649 << FixItHint::CreateInsertion(EndLoc, "]");
9650 } else
9651 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9652}
9653
9654/// Emit a warning when adding a char literal to a string.
9655static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9656 Expr *LHSExpr, Expr *RHSExpr) {
9657 const Expr *StringRefExpr = LHSExpr;
9658 const CharacterLiteral *CharExpr =
9659 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9660
9661 if (!CharExpr) {
9662 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9663 StringRefExpr = RHSExpr;
9664 }
9665
9666 if (!CharExpr || !StringRefExpr)
9667 return;
9668
9669 const QualType StringType = StringRefExpr->getType();
9670
9671 // Return if not a PointerType.
9672 if (!StringType->isAnyPointerType())
9673 return;
9674
9675 // Return if not a CharacterType.
9676 if (!StringType->getPointeeType()->isAnyCharacterType())
9677 return;
9678
9679 ASTContext &Ctx = Self.getASTContext();
9680 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9681
9682 const QualType CharType = CharExpr->getType();
9683 if (!CharType->isAnyCharacterType() &&
9684 CharType->isIntegerType() &&
9685 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9686 Self.Diag(OpLoc, diag::warn_string_plus_char)
9687 << DiagRange << Ctx.CharTy;
9688 } else {
9689 Self.Diag(OpLoc, diag::warn_string_plus_char)
9690 << DiagRange << CharExpr->getType();
9691 }
9692
9693 // Only print a fixit for str + char, not for char + str.
9694 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9695 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9696 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9697 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9698 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9699 << FixItHint::CreateInsertion(EndLoc, "]");
9700 } else {
9701 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9702 }
9703}
9704
9705/// Emit error when two pointers are incompatible.
9706static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9707 Expr *LHSExpr, Expr *RHSExpr) {
9708 assert(LHSExpr->getType()->isAnyPointerType())((LHSExpr->getType()->isAnyPointerType()) ? static_cast
<void> (0) : __assert_fail ("LHSExpr->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 9708, __PRETTY_FUNCTION__))
;
9709 assert(RHSExpr->getType()->isAnyPointerType())((RHSExpr->getType()->isAnyPointerType()) ? static_cast
<void> (0) : __assert_fail ("RHSExpr->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 9709, __PRETTY_FUNCTION__))
;
9710 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9711 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9712 << RHSExpr->getSourceRange();
9713}
9714
9715// C99 6.5.6
9716QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9717 SourceLocation Loc, BinaryOperatorKind Opc,
9718 QualType* CompLHSTy) {
9719 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9720
9721 if (LHS.get()->getType()->isVectorType() ||
9722 RHS.get()->getType()->isVectorType()) {
9723 QualType compType = CheckVectorOperands(
9724 LHS, RHS, Loc, CompLHSTy,
9725 /*AllowBothBool*/getLangOpts().AltiVec,
9726 /*AllowBoolConversions*/getLangOpts().ZVector);
9727 if (CompLHSTy) *CompLHSTy = compType;
9728 return compType;
9729 }
9730
9731 QualType compType = UsualArithmeticConversions(
9732 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
9733 if (LHS.isInvalid() || RHS.isInvalid())
9734 return QualType();
9735
9736 // Diagnose "string literal" '+' int and string '+' "char literal".
9737 if (Opc == BO_Add) {
9738 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9739 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9740 }
9741
9742 // handle the common case first (both operands are arithmetic).
9743 if (!compType.isNull() && compType->isArithmeticType()) {
9744 if (CompLHSTy) *CompLHSTy = compType;
9745 return compType;
9746 }
9747
9748 // Type-checking. Ultimately the pointer's going to be in PExp;
9749 // note that we bias towards the LHS being the pointer.
9750 Expr *PExp = LHS.get(), *IExp = RHS.get();
9751
9752 bool isObjCPointer;
9753 if (PExp->getType()->isPointerType()) {
9754 isObjCPointer = false;
9755 } else if (PExp->getType()->isObjCObjectPointerType()) {
9756 isObjCPointer = true;
9757 } else {
9758 std::swap(PExp, IExp);
9759 if (PExp->getType()->isPointerType()) {
9760 isObjCPointer = false;
9761 } else if (PExp->getType()->isObjCObjectPointerType()) {
9762 isObjCPointer = true;
9763 } else {
9764 return InvalidOperands(Loc, LHS, RHS);
9765 }
9766 }
9767 assert(PExp->getType()->isAnyPointerType())((PExp->getType()->isAnyPointerType()) ? static_cast<
void> (0) : __assert_fail ("PExp->getType()->isAnyPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 9767, __PRETTY_FUNCTION__))
;
9768
9769 if (!IExp->getType()->isIntegerType())
9770 return InvalidOperands(Loc, LHS, RHS);
9771
9772 // Adding to a null pointer results in undefined behavior.
9773 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9774 Context, Expr::NPC_ValueDependentIsNotNull)) {
9775 // In C++ adding zero to a null pointer is defined.
9776 Expr::EvalResult KnownVal;
9777 if (!getLangOpts().CPlusPlus ||
9778 (!IExp->isValueDependent() &&
9779 (!IExp->EvaluateAsInt(KnownVal, Context) ||
9780 KnownVal.Val.getInt() != 0))) {
9781 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9782 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9783 Context, BO_Add, PExp, IExp);
9784 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9785 }
9786 }
9787
9788 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9789 return QualType();
9790
9791 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9792 return QualType();
9793
9794 // Check array bounds for pointer arithemtic
9795 CheckArrayAccess(PExp, IExp);
9796
9797 if (CompLHSTy) {
9798 QualType LHSTy = Context.isPromotableBitField(LHS.get());
9799 if (LHSTy.isNull()) {
9800 LHSTy = LHS.get()->getType();
9801 if (LHSTy->isPromotableIntegerType())
9802 LHSTy = Context.getPromotedIntegerType(LHSTy);
9803 }
9804 *CompLHSTy = LHSTy;
9805 }
9806
9807 return PExp->getType();
9808}
9809
9810// C99 6.5.6
9811QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9812 SourceLocation Loc,
9813 QualType* CompLHSTy) {
9814 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
9815
9816 if (LHS.get()->getType()->isVectorType() ||
9817 RHS.get()->getType()->isVectorType()) {
9818 QualType compType = CheckVectorOperands(
9819 LHS, RHS, Loc, CompLHSTy,
9820 /*AllowBothBool*/getLangOpts().AltiVec,
9821 /*AllowBoolConversions*/getLangOpts().ZVector);
9822 if (CompLHSTy) *CompLHSTy = compType;
9823 return compType;
9824 }
9825
9826 QualType compType = UsualArithmeticConversions(
9827 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
9828 if (LHS.isInvalid() || RHS.isInvalid())
9829 return QualType();
9830
9831 // Enforce type constraints: C99 6.5.6p3.
9832
9833 // Handle the common case first (both operands are arithmetic).
9834 if (!compType.isNull() && compType->isArithmeticType()) {
9835 if (CompLHSTy) *CompLHSTy = compType;
9836 return compType;
9837 }
9838
9839 // Either ptr - int or ptr - ptr.
9840 if (LHS.get()->getType()->isAnyPointerType()) {
9841 QualType lpointee = LHS.get()->getType()->getPointeeType();
9842
9843 // Diagnose bad cases where we step over interface counts.
9844 if (LHS.get()->getType()->isObjCObjectPointerType() &&
9845 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9846 return QualType();
9847
9848 // The result type of a pointer-int computation is the pointer type.
9849 if (RHS.get()->getType()->isIntegerType()) {
9850 // Subtracting from a null pointer should produce a warning.
9851 // The last argument to the diagnose call says this doesn't match the
9852 // GNU int-to-pointer idiom.
9853 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9854 Expr::NPC_ValueDependentIsNotNull)) {
9855 // In C++ adding zero to a null pointer is defined.
9856 Expr::EvalResult KnownVal;
9857 if (!getLangOpts().CPlusPlus ||
9858 (!RHS.get()->isValueDependent() &&
9859 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9860 KnownVal.Val.getInt() != 0))) {
9861 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9862 }
9863 }
9864
9865 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9866 return QualType();
9867
9868 // Check array bounds for pointer arithemtic
9869 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9870 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9871
9872 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9873 return LHS.get()->getType();
9874 }
9875
9876 // Handle pointer-pointer subtractions.
9877 if (const PointerType *RHSPTy
9878 = RHS.get()->getType()->getAs<PointerType>()) {
9879 QualType rpointee = RHSPTy->getPointeeType();
9880
9881 if (getLangOpts().CPlusPlus) {
9882 // Pointee types must be the same: C++ [expr.add]
9883 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9884 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9885 }
9886 } else {
9887 // Pointee types must be compatible C99 6.5.6p3
9888 if (!Context.typesAreCompatible(
9889 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9890 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9891 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9892 return QualType();
9893 }
9894 }
9895
9896 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9897 LHS.get(), RHS.get()))
9898 return QualType();
9899
9900 // FIXME: Add warnings for nullptr - ptr.
9901
9902 // The pointee type may have zero size. As an extension, a structure or
9903 // union may have zero size or an array may have zero length. In this
9904 // case subtraction does not make sense.
9905 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9906 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9907 if (ElementSize.isZero()) {
9908 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9909 << rpointee.getUnqualifiedType()
9910 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9911 }
9912 }
9913
9914 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9915 return Context.getPointerDiffType();
9916 }
9917 }
9918
9919 return InvalidOperands(Loc, LHS, RHS);
9920}
9921
9922static bool isScopedEnumerationType(QualType T) {
9923 if (const EnumType *ET = T->getAs<EnumType>())
9924 return ET->getDecl()->isScoped();
9925 return false;
9926}
9927
9928static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9929 SourceLocation Loc, BinaryOperatorKind Opc,
9930 QualType LHSType) {
9931 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9932 // so skip remaining warnings as we don't want to modify values within Sema.
9933 if (S.getLangOpts().OpenCL)
9934 return;
9935
9936 // Check right/shifter operand
9937 Expr::EvalResult RHSResult;
9938 if (RHS.get()->isValueDependent() ||
9939 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9940 return;
9941 llvm::APSInt Right = RHSResult.Val.getInt();
9942
9943 if (Right.isNegative()) {
9944 S.DiagRuntimeBehavior(Loc, RHS.get(),
9945 S.PDiag(diag::warn_shift_negative)
9946 << RHS.get()->getSourceRange());
9947 return;
9948 }
9949 llvm::APInt LeftBits(Right.getBitWidth(),
9950 S.Context.getTypeSize(LHS.get()->getType()));
9951 if (Right.uge(LeftBits)) {
9952 S.DiagRuntimeBehavior(Loc, RHS.get(),
9953 S.PDiag(diag::warn_shift_gt_typewidth)
9954 << RHS.get()->getSourceRange());
9955 return;
9956 }
9957 if (Opc != BO_Shl)
9958 return;
9959
9960 // When left shifting an ICE which is signed, we can check for overflow which
9961 // according to C++ standards prior to C++2a has undefined behavior
9962 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
9963 // more than the maximum value representable in the result type, so never
9964 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
9965 // expression is still probably a bug.)
9966 Expr::EvalResult LHSResult;
9967 if (LHS.get()->isValueDependent() ||
9968 LHSType->hasUnsignedIntegerRepresentation() ||
9969 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9970 return;
9971 llvm::APSInt Left = LHSResult.Val.getInt();
9972
9973 // If LHS does not have a signed type and non-negative value
9974 // then, the behavior is undefined before C++2a. Warn about it.
9975 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
9976 !S.getLangOpts().CPlusPlus2a) {
9977 S.DiagRuntimeBehavior(Loc, LHS.get(),
9978 S.PDiag(diag::warn_shift_lhs_negative)
9979 << LHS.get()->getSourceRange());
9980 return;
9981 }
9982
9983 llvm::APInt ResultBits =
9984 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9985 if (LeftBits.uge(ResultBits))
9986 return;
9987 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9988 Result = Result.shl(Right);
9989
9990 // Print the bit representation of the signed integer as an unsigned
9991 // hexadecimal number.
9992 SmallString<40> HexResult;
9993 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9994
9995 // If we are only missing a sign bit, this is less likely to result in actual
9996 // bugs -- if the result is cast back to an unsigned type, it will have the
9997 // expected value. Thus we place this behind a different warning that can be
9998 // turned off separately if needed.
9999 if (LeftBits == ResultBits - 1) {
10000 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10001 << HexResult << LHSType
10002 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10003 return;
10004 }
10005
10006 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10007 << HexResult.str() << Result.getMinSignedBits() << LHSType
10008 << Left.getBitWidth() << LHS.get()->getSourceRange()
10009 << RHS.get()->getSourceRange();
10010}
10011
10012/// Return the resulting type when a vector is shifted
10013/// by a scalar or vector shift amount.
10014static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10015 SourceLocation Loc, bool IsCompAssign) {
10016 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10017 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10018 !LHS.get()->getType()->isVectorType()) {
10019 S.Diag(Loc, diag::err_shift_rhs_only_vector)
10020 << RHS.get()->getType() << LHS.get()->getType()
10021 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10022 return QualType();
10023 }
10024
10025 if (!IsCompAssign) {
10026 LHS = S.UsualUnaryConversions(LHS.get());
10027 if (LHS.isInvalid()) return QualType();
10028 }
10029
10030 RHS = S.UsualUnaryConversions(RHS.get());
10031 if (RHS.isInvalid()) return QualType();
10032
10033 QualType LHSType = LHS.get()->getType();
10034 // Note that LHS might be a scalar because the routine calls not only in
10035 // OpenCL case.
10036 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10037 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10038
10039 // Note that RHS might not be a vector.
10040 QualType RHSType = RHS.get()->getType();
10041 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10042 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10043
10044 // The operands need to be integers.
10045 if (!LHSEleType->isIntegerType()) {
10046 S.Diag(Loc, diag::err_typecheck_expect_int)
10047 << LHS.get()->getType() << LHS.get()->getSourceRange();
10048 return QualType();
10049 }
10050
10051 if (!RHSEleType->isIntegerType()) {
10052 S.Diag(Loc, diag::err_typecheck_expect_int)
10053 << RHS.get()->getType() << RHS.get()->getSourceRange();
10054 return QualType();
10055 }
10056
10057 if (!LHSVecTy) {
10058 assert(RHSVecTy)((RHSVecTy) ? static_cast<void> (0) : __assert_fail ("RHSVecTy"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 10058, __PRETTY_FUNCTION__))
;
10059 if (IsCompAssign)
10060 return RHSType;
10061 if (LHSEleType != RHSEleType) {
10062 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10063 LHSEleType = RHSEleType;
10064 }
10065 QualType VecTy =
10066 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10067 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10068 LHSType = VecTy;
10069 } else if (RHSVecTy) {
10070 // OpenCL v1.1 s6.3.j says that for vector types, the operators
10071 // are applied component-wise. So if RHS is a vector, then ensure
10072 // that the number of elements is the same as LHS...
10073 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10074 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10075 << LHS.get()->getType() << RHS.get()->getType()
10076 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10077 return QualType();
10078 }
10079 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10080 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10081 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10082 if (LHSBT != RHSBT &&
10083 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10084 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10085 << LHS.get()->getType() << RHS.get()->getType()
10086 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10087 }
10088 }
10089 } else {
10090 // ...else expand RHS to match the number of elements in LHS.
10091 QualType VecTy =
10092 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10093 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10094 }
10095
10096 return LHSType;
10097}
10098
10099// C99 6.5.7
10100QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10101 SourceLocation Loc, BinaryOperatorKind Opc,
10102 bool IsCompAssign) {
10103 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10104
10105 // Vector shifts promote their scalar inputs to vector type.
10106 if (LHS.get()->getType()->isVectorType() ||
10107 RHS.get()->getType()->isVectorType()) {
10108 if (LangOpts.ZVector) {
10109 // The shift operators for the z vector extensions work basically
10110 // like general shifts, except that neither the LHS nor the RHS is
10111 // allowed to be a "vector bool".
10112 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10113 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10114 return InvalidOperands(Loc, LHS, RHS);
10115 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10116 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10117 return InvalidOperands(Loc, LHS, RHS);
10118 }
10119 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10120 }
10121
10122 // Shifts don't perform usual arithmetic conversions, they just do integer
10123 // promotions on each operand. C99 6.5.7p3
10124
10125 // For the LHS, do usual unary conversions, but then reset them away
10126 // if this is a compound assignment.
10127 ExprResult OldLHS = LHS;
10128 LHS = UsualUnaryConversions(LHS.get());
10129 if (LHS.isInvalid())
10130 return QualType();
10131 QualType LHSType = LHS.get()->getType();
10132 if (IsCompAssign) LHS = OldLHS;
10133
10134 // The RHS is simpler.
10135 RHS = UsualUnaryConversions(RHS.get());
10136 if (RHS.isInvalid())
10137 return QualType();
10138 QualType RHSType = RHS.get()->getType();
10139
10140 // C99 6.5.7p2: Each of the operands shall have integer type.
10141 if (!LHSType->hasIntegerRepresentation() ||
10142 !RHSType->hasIntegerRepresentation())
10143 return InvalidOperands(Loc, LHS, RHS);
10144
10145 // C++0x: Don't allow scoped enums. FIXME: Use something better than
10146 // hasIntegerRepresentation() above instead of this.
10147 if (isScopedEnumerationType(LHSType) ||
10148 isScopedEnumerationType(RHSType)) {
10149 return InvalidOperands(Loc, LHS, RHS);
10150 }
10151 // Sanity-check shift operands
10152 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10153
10154 // "The type of the result is that of the promoted left operand."
10155 return LHSType;
10156}
10157
10158/// Diagnose bad pointer comparisons.
10159static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10160 ExprResult &LHS, ExprResult &RHS,
10161 bool IsError) {
10162 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10163 : diag::ext_typecheck_comparison_of_distinct_pointers)
10164 << LHS.get()->getType() << RHS.get()->getType()
10165 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10166}
10167
10168/// Returns false if the pointers are converted to a composite type,
10169/// true otherwise.
10170static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10171 ExprResult &LHS, ExprResult &RHS) {
10172 // C++ [expr.rel]p2:
10173 // [...] Pointer conversions (4.10) and qualification
10174 // conversions (4.4) are performed on pointer operands (or on
10175 // a pointer operand and a null pointer constant) to bring
10176 // them to their composite pointer type. [...]
10177 //
10178 // C++ [expr.eq]p1 uses the same notion for (in)equality
10179 // comparisons of pointers.
10180
10181 QualType LHSType = LHS.get()->getType();
10182 QualType RHSType = RHS.get()->getType();
10183 assert(LHSType->isPointerType() || RHSType->isPointerType() ||((LHSType->isPointerType() || RHSType->isPointerType() ||
LHSType->isMemberPointerType() || RHSType->isMemberPointerType
()) ? static_cast<void> (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 10184, __PRETTY_FUNCTION__))
10184 LHSType->isMemberPointerType() || RHSType->isMemberPointerType())((LHSType->isPointerType() || RHSType->isPointerType() ||
LHSType->isMemberPointerType() || RHSType->isMemberPointerType
()) ? static_cast<void> (0) : __assert_fail ("LHSType->isPointerType() || RHSType->isPointerType() || LHSType->isMemberPointerType() || RHSType->isMemberPointerType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 10184, __PRETTY_FUNCTION__))
;
10185
10186 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10187 if (T.isNull()) {
10188 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10189 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10190 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10191 else
10192 S.InvalidOperands(Loc, LHS, RHS);
10193 return true;
10194 }
10195
10196 return false;
10197}
10198
10199static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
10200 ExprResult &LHS,
10201 ExprResult &RHS,
10202 bool IsError) {
10203 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
10204 : diag::ext_typecheck_comparison_of_fptr_to_void)
10205 << LHS.get()->getType() << RHS.get()->getType()
10206 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10207}
10208
10209static bool isObjCObjectLiteral(ExprResult &E) {
10210 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
10211 case Stmt::ObjCArrayLiteralClass:
10212 case Stmt::ObjCDictionaryLiteralClass:
10213 case Stmt::ObjCStringLiteralClass:
10214 case Stmt::ObjCBoxedExprClass:
10215 return true;
10216 default:
10217 // Note that ObjCBoolLiteral is NOT an object literal!
10218 return false;
10219 }
10220}
10221
10222static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
10223 const ObjCObjectPointerType *Type =
10224 LHS->getType()->getAs<ObjCObjectPointerType>();
10225
10226 // If this is not actually an Objective-C object, bail out.
10227 if (!Type)
10228 return false;
10229
10230 // Get the LHS object's interface type.
10231 QualType InterfaceType = Type->getPointeeType();
10232
10233 // If the RHS isn't an Objective-C object, bail out.
10234 if (!RHS->getType()->isObjCObjectPointerType())
10235 return false;
10236
10237 // Try to find the -isEqual: method.
10238 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
10239 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
10240 InterfaceType,
10241 /*IsInstance=*/true);
10242 if (!Method) {
10243 if (Type->isObjCIdType()) {
10244 // For 'id', just check the global pool.
10245 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
10246 /*receiverId=*/true);
10247 } else {
10248 // Check protocols.
10249 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
10250 /*IsInstance=*/true);
10251 }
10252 }
10253
10254 if (!Method)
10255 return false;
10256
10257 QualType T = Method->parameters()[0]->getType();
10258 if (!T->isObjCObjectPointerType())
10259 return false;
10260
10261 QualType R = Method->getReturnType();
10262 if (!R->isScalarType())
10263 return false;
10264
10265 return true;
10266}
10267
10268Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
10269 FromE = FromE->IgnoreParenImpCasts();
10270 switch (FromE->getStmtClass()) {
10271 default:
10272 break;
10273 case Stmt::ObjCStringLiteralClass:
10274 // "string literal"
10275 return LK_String;
10276 case Stmt::ObjCArrayLiteralClass:
10277 // "array literal"
10278 return LK_Array;
10279 case Stmt::ObjCDictionaryLiteralClass:
10280 // "dictionary literal"
10281 return LK_Dictionary;
10282 case Stmt::BlockExprClass:
10283 return LK_Block;
10284 case Stmt::ObjCBoxedExprClass: {
10285 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
10286 switch (Inner->getStmtClass()) {
10287 case Stmt::IntegerLiteralClass:
10288 case Stmt::FloatingLiteralClass:
10289 case Stmt::CharacterLiteralClass:
10290 case Stmt::ObjCBoolLiteralExprClass:
10291 case Stmt::CXXBoolLiteralExprClass:
10292 // "numeric literal"
10293 return LK_Numeric;
10294 case Stmt::ImplicitCastExprClass: {
10295 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
10296 // Boolean literals can be represented by implicit casts.
10297 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
10298 return LK_Numeric;
10299 break;
10300 }
10301 default:
10302 break;
10303 }
10304 return LK_Boxed;
10305 }
10306 }
10307 return LK_None;
10308}
10309
10310static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
10311 ExprResult &LHS, ExprResult &RHS,
10312 BinaryOperator::Opcode Opc){
10313 Expr *Literal;
10314 Expr *Other;
10315 if (isObjCObjectLiteral(LHS)) {
10316 Literal = LHS.get();
10317 Other = RHS.get();
10318 } else {
10319 Literal = RHS.get();
10320 Other = LHS.get();
10321 }
10322
10323 // Don't warn on comparisons against nil.
10324 Other = Other->IgnoreParenCasts();
10325 if (Other->isNullPointerConstant(S.getASTContext(),
10326 Expr::NPC_ValueDependentIsNotNull))
10327 return;
10328
10329 // This should be kept in sync with warn_objc_literal_comparison.
10330 // LK_String should always be after the other literals, since it has its own
10331 // warning flag.
10332 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
10333 assert(LiteralKind != Sema::LK_Block)((LiteralKind != Sema::LK_Block) ? static_cast<void> (0
) : __assert_fail ("LiteralKind != Sema::LK_Block", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 10333, __PRETTY_FUNCTION__))
;
10334 if (LiteralKind == Sema::LK_None) {
10335 llvm_unreachable("Unknown Objective-C object literal kind")::llvm::llvm_unreachable_internal("Unknown Objective-C object literal kind"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 10335)
;
10336 }
10337
10338 if (LiteralKind == Sema::LK_String)
10339 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
10340 << Literal->getSourceRange();
10341 else
10342 S.Diag(Loc, diag::warn_objc_literal_comparison)
10343 << LiteralKind << Literal->getSourceRange();
10344
10345 if (BinaryOperator::isEqualityOp(Opc) &&
10346 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10347 SourceLocation Start = LHS.get()->getBeginLoc();
10348 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10349 CharSourceRange OpRange =
10350 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10351
10352 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10353 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10354 << FixItHint::CreateReplacement(OpRange, " isEqual:")
10355 << FixItHint::CreateInsertion(End, "]");
10356 }
10357}
10358
10359/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10360static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10361 ExprResult &RHS, SourceLocation Loc,
10362 BinaryOperatorKind Opc) {
10363 // Check that left hand side is !something.
10364 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10365 if (!UO || UO->getOpcode() != UO_LNot) return;
10366
10367 // Only check if the right hand side is non-bool arithmetic type.
10368 if (RHS.get()->isKnownToHaveBooleanValue()) return;
10369
10370 // Make sure that the something in !something is not bool.
10371 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10372 if (SubExpr->isKnownToHaveBooleanValue()) return;
10373
10374 // Emit warning.
10375 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10376 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10377 << Loc << IsBitwiseOp;
10378
10379 // First note suggest !(x < y)
10380 SourceLocation FirstOpen = SubExpr->getBeginLoc();
10381 SourceLocation FirstClose = RHS.get()->getEndLoc();
10382 FirstClose = S.getLocForEndOfToken(FirstClose);
10383 if (FirstClose.isInvalid())
10384 FirstOpen = SourceLocation();
10385 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10386 << IsBitwiseOp
10387 << FixItHint::CreateInsertion(FirstOpen, "(")
10388 << FixItHint::CreateInsertion(FirstClose, ")");
10389
10390 // Second note suggests (!x) < y
10391 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10392 SourceLocation SecondClose = LHS.get()->getEndLoc();
10393 SecondClose = S.getLocForEndOfToken(SecondClose);
10394 if (SecondClose.isInvalid())
10395 SecondOpen = SourceLocation();
10396 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10397 << FixItHint::CreateInsertion(SecondOpen, "(")
10398 << FixItHint::CreateInsertion(SecondClose, ")");
10399}
10400
10401// Returns true if E refers to a non-weak array.
10402static bool checkForArray(const Expr *E) {
10403 const ValueDecl *D = nullptr;
10404 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
10405 D = DR->getDecl();
10406 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10407 if (Mem->isImplicitAccess())
10408 D = Mem->getMemberDecl();
10409 }
10410 if (!D)
10411 return false;
10412 return D->getType()->isArrayType() && !D->isWeak();
10413}
10414
10415/// Diagnose some forms of syntactically-obvious tautological comparison.
10416static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10417 Expr *LHS, Expr *RHS,
10418 BinaryOperatorKind Opc) {
10419 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10420 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10421
10422 QualType LHSType = LHS->getType();
10423 QualType RHSType = RHS->getType();
10424 if (LHSType->hasFloatingRepresentation() ||
10425 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10426 S.inTemplateInstantiation())
10427 return;
10428
10429 // Comparisons between two array types are ill-formed for operator<=>, so
10430 // we shouldn't emit any additional warnings about it.
10431 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10432 return;
10433
10434 // For non-floating point types, check for self-comparisons of the form
10435 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
10436 // often indicate logic errors in the program.
10437 //
10438 // NOTE: Don't warn about comparison expressions resulting from macro
10439 // expansion. Also don't warn about comparisons which are only self
10440 // comparisons within a template instantiation. The warnings should catch
10441 // obvious cases in the definition of the template anyways. The idea is to
10442 // warn when the typed comparison operator will always evaluate to the same
10443 // result.
10444
10445 // Used for indexing into %select in warn_comparison_always
10446 enum {
10447 AlwaysConstant,
10448 AlwaysTrue,
10449 AlwaysFalse,
10450 AlwaysEqual, // std::strong_ordering::equal from operator<=>
10451 };
10452
10453 // C++2a [depr.array.comp]:
10454 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
10455 // operands of array type are deprecated.
10456 if (S.getLangOpts().CPlusPlus2a && LHSStripped->getType()->isArrayType() &&
10457 RHSStripped->getType()->isArrayType()) {
10458 S.Diag(Loc, diag::warn_depr_array_comparison)
10459 << LHS->getSourceRange() << RHS->getSourceRange()
10460 << LHSStripped->getType() << RHSStripped->getType();
10461 // Carry on to produce the tautological comparison warning, if this
10462 // expression is potentially-evaluated, we can resolve the array to a
10463 // non-weak declaration, and so on.
10464 }
10465
10466 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
10467 if (Expr::isSameComparisonOperand(LHS, RHS)) {
10468 unsigned Result;
10469 switch (Opc) {
10470 case BO_EQ:
10471 case BO_LE:
10472 case BO_GE:
10473 Result = AlwaysTrue;
10474 break;
10475 case BO_NE:
10476 case BO_LT:
10477 case BO_GT:
10478 Result = AlwaysFalse;
10479 break;
10480 case BO_Cmp:
10481 Result = AlwaysEqual;
10482 break;
10483 default:
10484 Result = AlwaysConstant;
10485 break;
10486 }
10487 S.DiagRuntimeBehavior(Loc, nullptr,
10488 S.PDiag(diag::warn_comparison_always)
10489 << 0 /*self-comparison*/
10490 << Result);
10491 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
10492 // What is it always going to evaluate to?
10493 unsigned Result;
10494 switch (Opc) {
10495 case BO_EQ: // e.g. array1 == array2
10496 Result = AlwaysFalse;
10497 break;
10498 case BO_NE: // e.g. array1 != array2
10499 Result = AlwaysTrue;
10500 break;
10501 default: // e.g. array1 <= array2
10502 // The best we can say is 'a constant'
10503 Result = AlwaysConstant;
10504 break;
10505 }
10506 S.DiagRuntimeBehavior(Loc, nullptr,
10507 S.PDiag(diag::warn_comparison_always)
10508 << 1 /*array comparison*/
10509 << Result);
10510 }
10511 }
10512
10513 if (isa<CastExpr>(LHSStripped))
10514 LHSStripped = LHSStripped->IgnoreParenCasts();
10515 if (isa<CastExpr>(RHSStripped))
10516 RHSStripped = RHSStripped->IgnoreParenCasts();
10517
10518 // Warn about comparisons against a string constant (unless the other
10519 // operand is null); the user probably wants string comparison function.
10520 Expr *LiteralString = nullptr;
10521 Expr *LiteralStringStripped = nullptr;
10522 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10523 !RHSStripped->isNullPointerConstant(S.Context,
10524 Expr::NPC_ValueDependentIsNull)) {
10525 LiteralString = LHS;
10526 LiteralStringStripped = LHSStripped;
10527 } else if ((isa<StringLiteral>(RHSStripped) ||
10528 isa<ObjCEncodeExpr>(RHSStripped)) &&
10529 !LHSStripped->isNullPointerConstant(S.Context,
10530 Expr::NPC_ValueDependentIsNull)) {
10531 LiteralString = RHS;
10532 LiteralStringStripped = RHSStripped;
10533 }
10534
10535 if (LiteralString) {
10536 S.DiagRuntimeBehavior(Loc, nullptr,
10537 S.PDiag(diag::warn_stringcompare)
10538 << isa<ObjCEncodeExpr>(LiteralStringStripped)
10539 << LiteralString->getSourceRange());
10540 }
10541}
10542
10543static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10544 switch (CK) {
10545 default: {
10546#ifndef NDEBUG
10547 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10548 << "\n";
10549#endif
10550 llvm_unreachable("unhandled cast kind")::llvm::llvm_unreachable_internal("unhandled cast kind", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 10550)
;
10551 }
10552 case CK_UserDefinedConversion:
10553 return ICK_Identity;
10554 case CK_LValueToRValue:
10555 return ICK_Lvalue_To_Rvalue;
10556 case CK_ArrayToPointerDecay:
10557 return ICK_Array_To_Pointer;
10558 case CK_FunctionToPointerDecay:
10559 return ICK_Function_To_Pointer;
10560 case CK_IntegralCast:
10561 return ICK_Integral_Conversion;
10562 case CK_FloatingCast:
10563 return ICK_Floating_Conversion;
10564 case CK_IntegralToFloating:
10565 case CK_FloatingToIntegral:
10566 return ICK_Floating_Integral;
10567 case CK_IntegralComplexCast:
10568 case CK_FloatingComplexCast:
10569 case CK_FloatingComplexToIntegralComplex:
10570 case CK_IntegralComplexToFloatingComplex:
10571 return ICK_Complex_Conversion;
10572 case CK_FloatingComplexToReal:
10573 case CK_FloatingRealToComplex:
10574 case CK_IntegralComplexToReal:
10575 case CK_IntegralRealToComplex:
10576 return ICK_Complex_Real;
10577 }
10578}
10579
10580static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10581 QualType FromType,
10582 SourceLocation Loc) {
10583 // Check for a narrowing implicit conversion.
10584 StandardConversionSequence SCS;
10585 SCS.setAsIdentityConversion();
10586 SCS.setToType(0, FromType);
10587 SCS.setToType(1, ToType);
10588 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10589 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10590
10591 APValue PreNarrowingValue;
10592 QualType PreNarrowingType;
10593 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10594 PreNarrowingType,
10595 /*IgnoreFloatToIntegralConversion*/ true)) {
10596 case NK_Dependent_Narrowing:
10597 // Implicit conversion to a narrower type, but the expression is
10598 // value-dependent so we can't tell whether it's actually narrowing.
10599 case NK_Not_Narrowing:
10600 return false;
10601
10602 case NK_Constant_Narrowing:
10603 // Implicit conversion to a narrower type, and the value is not a constant
10604 // expression.
10605 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10606 << /*Constant*/ 1
10607 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10608 return true;
10609
10610 case NK_Variable_Narrowing:
10611 // Implicit conversion to a narrower type, and the value is not a constant
10612 // expression.
10613 case NK_Type_Narrowing:
10614 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10615 << /*Constant*/ 0 << FromType << ToType;
10616 // TODO: It's not a constant expression, but what if the user intended it
10617 // to be? Can we produce notes to help them figure out why it isn't?
10618 return true;
10619 }
10620 llvm_unreachable("unhandled case in switch")::llvm::llvm_unreachable_internal("unhandled case in switch",
"/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 10620)
;
10621}
10622
10623static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10624 ExprResult &LHS,
10625 ExprResult &RHS,
10626 SourceLocation Loc) {
10627 QualType LHSType = LHS.get()->getType();
10628 QualType RHSType = RHS.get()->getType();
10629 // Dig out the original argument type and expression before implicit casts
10630 // were applied. These are the types/expressions we need to check the
10631 // [expr.spaceship] requirements against.
10632 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10633 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10634 QualType LHSStrippedType = LHSStripped.get()->getType();
10635 QualType RHSStrippedType = RHSStripped.get()->getType();
10636
10637 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10638 // other is not, the program is ill-formed.
10639 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10640 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10641 return QualType();
10642 }
10643
10644 // FIXME: Consider combining this with checkEnumArithmeticConversions.
10645 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10646 RHSStrippedType->isEnumeralType();
10647 if (NumEnumArgs == 1) {
10648 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10649 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10650 if (OtherTy->hasFloatingRepresentation()) {
10651 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10652 return QualType();
10653 }
10654 }
10655 if (NumEnumArgs == 2) {
10656 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10657 // type E, the operator yields the result of converting the operands
10658 // to the underlying type of E and applying <=> to the converted operands.
10659 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10660 S.InvalidOperands(Loc, LHS, RHS);
10661 return QualType();
10662 }
10663 QualType IntType =
10664 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
10665 assert(IntType->isArithmeticType())((IntType->isArithmeticType()) ? static_cast<void> (
0) : __assert_fail ("IntType->isArithmeticType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 10665, __PRETTY_FUNCTION__))
;
10666
10667 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10668 // promote the boolean type, and all other promotable integer types, to
10669 // avoid this.
10670 if (IntType->isPromotableIntegerType())
10671 IntType = S.Context.getPromotedIntegerType(IntType);
10672
10673 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10674 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10675 LHSType = RHSType = IntType;
10676 }
10677
10678 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10679 // usual arithmetic conversions are applied to the operands.
10680 QualType Type =
10681 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
10682 if (LHS.isInvalid() || RHS.isInvalid())
10683 return QualType();
10684 if (Type.isNull())
10685 return S.InvalidOperands(Loc, LHS, RHS);
10686
10687 Optional<ComparisonCategoryType> CCT =
10688 getComparisonCategoryForBuiltinCmp(Type);
10689 if (!CCT)
10690 return S.InvalidOperands(Loc, LHS, RHS);
10691
10692 bool HasNarrowing = checkThreeWayNarrowingConversion(
10693 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10694 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10695 RHS.get()->getBeginLoc());
10696 if (HasNarrowing)
10697 return QualType();
10698
10699 assert(!Type.isNull() && "composite type for <=> has not been set")((!Type.isNull() && "composite type for <=> has not been set"
) ? static_cast<void> (0) : __assert_fail ("!Type.isNull() && \"composite type for <=> has not been set\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 10699, __PRETTY_FUNCTION__))
;
10700
10701 return S.CheckComparisonCategoryType(
10702 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
10703}
10704
10705static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10706 ExprResult &RHS,
10707 SourceLocation Loc,
10708 BinaryOperatorKind Opc) {
10709 if (Opc == BO_Cmp)
10710 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10711
10712 // C99 6.5.8p3 / C99 6.5.9p4
10713 QualType Type =
10714 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
10715 if (LHS.isInvalid() || RHS.isInvalid())
10716 return QualType();
10717 if (Type.isNull())
10718 return S.InvalidOperands(Loc, LHS, RHS);
10719 assert(Type->isArithmeticType() || Type->isEnumeralType())((Type->isArithmeticType() || Type->isEnumeralType()) ?
static_cast<void> (0) : __assert_fail ("Type->isArithmeticType() || Type->isEnumeralType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 10719, __PRETTY_FUNCTION__))
;
10720
10721 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10722 return S.InvalidOperands(Loc, LHS, RHS);
10723
10724 // Check for comparisons of floating point operands using != and ==.
10725 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10726 S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10727
10728 // The result of comparisons is 'bool' in C++, 'int' in C.
10729 return S.Context.getLogicalOperationType();
10730}
10731
10732void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
10733 if (!NullE.get()->getType()->isAnyPointerType())
10734 return;
10735 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
10736 if (!E.get()->getType()->isAnyPointerType() &&
10737 E.get()->isNullPointerConstant(Context,
10738 Expr::NPC_ValueDependentIsNotNull) ==
10739 Expr::NPCK_ZeroExpression) {
10740 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
10741 if (CL->getValue() == 0)
10742 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10743 << NullValue
10744 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10745 NullValue ? "NULL" : "(void *)0");
10746 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
10747 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
10748 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
10749 if (T == Context.CharTy)
10750 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
10751 << NullValue
10752 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
10753 NullValue ? "NULL" : "(void *)0");
10754 }
10755 }
10756}
10757
10758// C99 6.5.8, C++ [expr.rel]
10759QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10760 SourceLocation Loc,
10761 BinaryOperatorKind Opc) {
10762 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10763 bool IsThreeWay = Opc == BO_Cmp;
10764 bool IsOrdered = IsRelational || IsThreeWay;
10765 auto IsAnyPointerType = [](ExprResult E) {
10766 QualType Ty = E.get()->getType();
10767 return Ty->isPointerType() || Ty->isMemberPointerType();
10768 };
10769
10770 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10771 // type, array-to-pointer, ..., conversions are performed on both operands to
10772 // bring them to their composite type.
10773 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10774 // any type-related checks.
10775 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10776 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10777 if (LHS.isInvalid())
10778 return QualType();
10779 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10780 if (RHS.isInvalid())
10781 return QualType();
10782 } else {
10783 LHS = DefaultLvalueConversion(LHS.get());
10784 if (LHS.isInvalid())
10785 return QualType();
10786 RHS = DefaultLvalueConversion(RHS.get());
10787 if (RHS.isInvalid())
10788 return QualType();
10789 }
10790
10791 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
10792 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
10793 CheckPtrComparisonWithNullChar(LHS, RHS);
10794 CheckPtrComparisonWithNullChar(RHS, LHS);
10795 }
10796
10797 // Handle vector comparisons separately.
10798 if (LHS.get()->getType()->isVectorType() ||
10799 RHS.get()->getType()->isVectorType())
10800 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10801
10802 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10803 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10804
10805 QualType LHSType = LHS.get()->getType();
10806 QualType RHSType = RHS.get()->getType();
10807 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10808 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10809 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10810
10811 const Expr::NullPointerConstantKind LHSNullKind =
10812 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10813 const Expr::NullPointerConstantKind RHSNullKind =
10814 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10815 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10816 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10817
10818 auto computeResultTy = [&]() {
10819 if (Opc != BO_Cmp)
10820 return Context.getLogicalOperationType();
10821 assert(getLangOpts().CPlusPlus)((getLangOpts().CPlusPlus) ? static_cast<void> (0) : __assert_fail
("getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 10821, __PRETTY_FUNCTION__))
;
10822 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()))((Context.hasSameType(LHS.get()->getType(), RHS.get()->
getType())) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(LHS.get()->getType(), RHS.get()->getType())"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 10822, __PRETTY_FUNCTION__))
;
10823
10824 QualType CompositeTy = LHS.get()->getType();
10825 assert(!CompositeTy->isReferenceType())((!CompositeTy->isReferenceType()) ? static_cast<void>
(0) : __assert_fail ("!CompositeTy->isReferenceType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 10825, __PRETTY_FUNCTION__))
;
10826
10827 Optional<ComparisonCategoryType> CCT =
10828 getComparisonCategoryForBuiltinCmp(CompositeTy);
10829 if (!CCT)
10830 return InvalidOperands(Loc, LHS, RHS);
10831
10832 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
10833 // P0946R0: Comparisons between a null pointer constant and an object
10834 // pointer result in std::strong_equality, which is ill-formed under
10835 // P1959R0.
10836 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
10837 << (LHSIsNull ? LHS.get()->getSourceRange()
10838 : RHS.get()->getSourceRange());
10839 return QualType();
10840 }
10841
10842 return CheckComparisonCategoryType(
10843 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
10844 };
10845
10846 if (!IsOrdered && LHSIsNull != RHSIsNull) {
10847 bool IsEquality = Opc == BO_EQ;
10848 if (RHSIsNull)
10849 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10850 RHS.get()->getSourceRange());
10851 else
10852 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10853 LHS.get()->getSourceRange());
10854 }
10855
10856 if ((LHSType->isIntegerType() && !LHSIsNull) ||
10857 (RHSType->isIntegerType() && !RHSIsNull)) {
10858 // Skip normal pointer conversion checks in this case; we have better
10859 // diagnostics for this below.
10860 } else if (getLangOpts().CPlusPlus) {
10861 // Equality comparison of a function pointer to a void pointer is invalid,
10862 // but we allow it as an extension.
10863 // FIXME: If we really want to allow this, should it be part of composite
10864 // pointer type computation so it works in conditionals too?
10865 if (!IsOrdered &&
10866 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10867 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10868 // This is a gcc extension compatibility comparison.
10869 // In a SFINAE context, we treat this as a hard error to maintain
10870 // conformance with the C++ standard.
10871 diagnoseFunctionPointerToVoidComparison(
10872 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10873
10874 if (isSFINAEContext())
10875 return QualType();
10876
10877 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10878 return computeResultTy();
10879 }
10880
10881 // C++ [expr.eq]p2:
10882 // If at least one operand is a pointer [...] bring them to their
10883 // composite pointer type.
10884 // C++ [expr.spaceship]p6
10885 // If at least one of the operands is of pointer type, [...] bring them
10886 // to their composite pointer type.
10887 // C++ [expr.rel]p2:
10888 // If both operands are pointers, [...] bring them to their composite
10889 // pointer type.
10890 // For <=>, the only valid non-pointer types are arrays and functions, and
10891 // we already decayed those, so this is really the same as the relational
10892 // comparison rule.
10893 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10894 (IsOrdered ? 2 : 1) &&
10895 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10896 RHSType->isObjCObjectPointerType()))) {
10897 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10898 return QualType();
10899 return computeResultTy();
10900 }
10901 } else if (LHSType->isPointerType() &&
10902 RHSType->isPointerType()) { // C99 6.5.8p2
10903 // All of the following pointer-related warnings are GCC extensions, except
10904 // when handling null pointer constants.
10905 QualType LCanPointeeTy =
10906 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10907 QualType RCanPointeeTy =
10908 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10909
10910 // C99 6.5.9p2 and C99 6.5.8p2
10911 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10912 RCanPointeeTy.getUnqualifiedType())) {
10913 // Valid unless a relational comparison of function pointers
10914 if (IsRelational && LCanPointeeTy->isFunctionType()) {
10915 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10916 << LHSType << RHSType << LHS.get()->getSourceRange()
10917 << RHS.get()->getSourceRange();
10918 }
10919 } else if (!IsRelational &&
10920 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10921 // Valid unless comparison between non-null pointer and function pointer
10922 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10923 && !LHSIsNull && !RHSIsNull)
10924 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10925 /*isError*/false);
10926 } else {
10927 // Invalid
10928 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10929 }
10930 if (LCanPointeeTy != RCanPointeeTy) {
10931 // Treat NULL constant as a special case in OpenCL.
10932 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10933 const PointerType *LHSPtr = LHSType->castAs<PointerType>();
10934 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->castAs<PointerType>())) {
10935 Diag(Loc,
10936 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10937 << LHSType << RHSType << 0 /* comparison */
10938 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10939 }
10940 }
10941 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10942 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10943 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10944 : CK_BitCast;
10945 if (LHSIsNull && !RHSIsNull)
10946 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10947 else
10948 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10949 }
10950 return computeResultTy();
10951 }
10952
10953 if (getLangOpts().CPlusPlus) {
10954 // C++ [expr.eq]p4:
10955 // Two operands of type std::nullptr_t or one operand of type
10956 // std::nullptr_t and the other a null pointer constant compare equal.
10957 if (!IsOrdered && LHSIsNull && RHSIsNull) {
10958 if (LHSType->isNullPtrType()) {
10959 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10960 return computeResultTy();
10961 }
10962 if (RHSType->isNullPtrType()) {
10963 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10964 return computeResultTy();
10965 }
10966 }
10967
10968 // Comparison of Objective-C pointers and block pointers against nullptr_t.
10969 // These aren't covered by the composite pointer type rules.
10970 if (!IsOrdered && RHSType->isNullPtrType() &&
10971 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10972 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10973 return computeResultTy();
10974 }
10975 if (!IsOrdered && LHSType->isNullPtrType() &&
10976 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10977 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10978 return computeResultTy();
10979 }
10980
10981 if (IsRelational &&
10982 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10983 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10984 // HACK: Relational comparison of nullptr_t against a pointer type is
10985 // invalid per DR583, but we allow it within std::less<> and friends,
10986 // since otherwise common uses of it break.
10987 // FIXME: Consider removing this hack once LWG fixes std::less<> and
10988 // friends to have std::nullptr_t overload candidates.
10989 DeclContext *DC = CurContext;
10990 if (isa<FunctionDecl>(DC))
10991 DC = DC->getParent();
10992 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10993 if (CTSD->isInStdNamespace() &&
10994 llvm::StringSwitch<bool>(CTSD->getName())
10995 .Cases("less", "less_equal", "greater", "greater_equal", true)
10996 .Default(false)) {
10997 if (RHSType->isNullPtrType())
10998 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10999 else
11000 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11001 return computeResultTy();
11002 }
11003 }
11004 }
11005
11006 // C++ [expr.eq]p2:
11007 // If at least one operand is a pointer to member, [...] bring them to
11008 // their composite pointer type.
11009 if (!IsOrdered &&
11010 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11011 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11012 return QualType();
11013 else
11014 return computeResultTy();
11015 }
11016 }
11017
11018 // Handle block pointer types.
11019 if (!IsOrdered && LHSType->isBlockPointerType() &&
11020 RHSType->isBlockPointerType()) {
11021 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11022 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11023
11024 if (!LHSIsNull && !RHSIsNull &&
11025 !Context.typesAreCompatible(lpointee, rpointee)) {
11026 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11027 << LHSType << RHSType << LHS.get()->getSourceRange()
11028 << RHS.get()->getSourceRange();
11029 }
11030 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11031 return computeResultTy();
11032 }
11033
11034 // Allow block pointers to be compared with null pointer constants.
11035 if (!IsOrdered
11036 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11037 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11038 if (!LHSIsNull && !RHSIsNull) {
11039 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11040 ->getPointeeType()->isVoidType())
11041 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11042 ->getPointeeType()->isVoidType())))
11043 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11044 << LHSType << RHSType << LHS.get()->getSourceRange()
11045 << RHS.get()->getSourceRange();
11046 }
11047 if (LHSIsNull && !RHSIsNull)
11048 LHS = ImpCastExprToType(LHS.get(), RHSType,
11049 RHSType->isPointerType() ? CK_BitCast
11050 : CK_AnyPointerToBlockPointerCast);
11051 else
11052 RHS = ImpCastExprToType(RHS.get(), LHSType,
11053 LHSType->isPointerType() ? CK_BitCast
11054 : CK_AnyPointerToBlockPointerCast);
11055 return computeResultTy();
11056 }
11057
11058 if (LHSType->isObjCObjectPointerType() ||
11059 RHSType->isObjCObjectPointerType()) {
11060 const PointerType *LPT = LHSType->getAs<PointerType>();
11061 const PointerType *RPT = RHSType->getAs<PointerType>();
11062 if (LPT || RPT) {
11063 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11064 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11065
11066 if (!LPtrToVoid && !RPtrToVoid &&
11067 !Context.typesAreCompatible(LHSType, RHSType)) {
11068 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11069 /*isError*/false);
11070 }
11071 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11072 // the RHS, but we have test coverage for this behavior.
11073 // FIXME: Consider using convertPointersToCompositeType in C++.
11074 if (LHSIsNull && !RHSIsNull) {
11075 Expr *E = LHS.get();
11076 if (getLangOpts().ObjCAutoRefCount)
11077 CheckObjCConversion(SourceRange(), RHSType, E,
11078 CCK_ImplicitConversion);
11079 LHS = ImpCastExprToType(E, RHSType,
11080 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11081 }
11082 else {
11083 Expr *E = RHS.get();
11084 if (getLangOpts().ObjCAutoRefCount)
11085 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11086 /*Diagnose=*/true,
11087 /*DiagnoseCFAudited=*/false, Opc);
11088 RHS = ImpCastExprToType(E, LHSType,
11089 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11090 }
11091 return computeResultTy();
11092 }
11093 if (LHSType->isObjCObjectPointerType() &&
11094 RHSType->isObjCObjectPointerType()) {
11095 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11096 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11097 /*isError*/false);
11098 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11099 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11100
11101 if (LHSIsNull && !RHSIsNull)
11102 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11103 else
11104 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11105 return computeResultTy();
11106 }
11107
11108 if (!IsOrdered && LHSType->isBlockPointerType() &&
11109 RHSType->isBlockCompatibleObjCPointerType(Context)) {
11110 LHS = ImpCastExprToType(LHS.get(), RHSType,
11111 CK_BlockPointerToObjCPointerCast);
11112 return computeResultTy();
11113 } else if (!IsOrdered &&
11114 LHSType->isBlockCompatibleObjCPointerType(Context) &&
11115 RHSType->isBlockPointerType()) {
11116 RHS = ImpCastExprToType(RHS.get(), LHSType,
11117 CK_BlockPointerToObjCPointerCast);
11118 return computeResultTy();
11119 }
11120 }
11121 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11122 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11123 unsigned DiagID = 0;
11124 bool isError = false;
11125 if (LangOpts.DebuggerSupport) {
11126 // Under a debugger, allow the comparison of pointers to integers,
11127 // since users tend to want to compare addresses.
11128 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11129 (RHSIsNull && RHSType->isIntegerType())) {
11130 if (IsOrdered) {
11131 isError = getLangOpts().CPlusPlus;
11132 DiagID =
11133 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11134 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11135 }
11136 } else if (getLangOpts().CPlusPlus) {
11137 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11138 isError = true;
11139 } else if (IsOrdered)
11140 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11141 else
11142 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11143
11144 if (DiagID) {
11145 Diag(Loc, DiagID)
11146 << LHSType << RHSType << LHS.get()->getSourceRange()
11147 << RHS.get()->getSourceRange();
11148 if (isError)
11149 return QualType();
11150 }
11151
11152 if (LHSType->isIntegerType())
11153 LHS = ImpCastExprToType(LHS.get(), RHSType,
11154 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11155 else
11156 RHS = ImpCastExprToType(RHS.get(), LHSType,
11157 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11158 return computeResultTy();
11159 }
11160
11161 // Handle block pointers.
11162 if (!IsOrdered && RHSIsNull
11163 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11164 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11165 return computeResultTy();
11166 }
11167 if (!IsOrdered && LHSIsNull
11168 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11169 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11170 return computeResultTy();
11171 }
11172
11173 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11174 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11175 return computeResultTy();
11176 }
11177
11178 if (LHSType->isQueueT() && RHSType->isQueueT()) {
11179 return computeResultTy();
11180 }
11181
11182 if (LHSIsNull && RHSType->isQueueT()) {
11183 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11184 return computeResultTy();
11185 }
11186
11187 if (LHSType->isQueueT() && RHSIsNull) {
11188 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11189 return computeResultTy();
11190 }
11191 }
11192
11193 return InvalidOperands(Loc, LHS, RHS);
11194}
11195
11196// Return a signed ext_vector_type that is of identical size and number of
11197// elements. For floating point vectors, return an integer type of identical
11198// size and number of elements. In the non ext_vector_type case, search from
11199// the largest type to the smallest type to avoid cases where long long == long,
11200// where long gets picked over long long.
11201QualType Sema::GetSignedVectorType(QualType V) {
11202 const VectorType *VTy = V->castAs<VectorType>();
11203 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
11204
11205 if (isa<ExtVectorType>(VTy)) {
11206 if (TypeSize == Context.getTypeSize(Context.CharTy))
11207 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
11208 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11209 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
11210 else if (TypeSize == Context.getTypeSize(Context.IntTy))
11211 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
11212 else if (TypeSize == Context.getTypeSize(Context.LongTy))
11213 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
11214 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&((TypeSize == Context.getTypeSize(Context.LongLongTy) &&
"Unhandled vector element size in vector compare") ? static_cast
<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 11215, __PRETTY_FUNCTION__))
11215 "Unhandled vector element size in vector compare")((TypeSize == Context.getTypeSize(Context.LongLongTy) &&
"Unhandled vector element size in vector compare") ? static_cast
<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.LongLongTy) && \"Unhandled vector element size in vector compare\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 11215, __PRETTY_FUNCTION__))
;
11216 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
11217 }
11218
11219 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
11220 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
11221 VectorType::GenericVector);
11222 else if (TypeSize == Context.getTypeSize(Context.LongTy))
11223 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
11224 VectorType::GenericVector);
11225 else if (TypeSize == Context.getTypeSize(Context.IntTy))
11226 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
11227 VectorType::GenericVector);
11228 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
11229 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
11230 VectorType::GenericVector);
11231 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&((TypeSize == Context.getTypeSize(Context.CharTy) && "Unhandled vector element size in vector compare"
) ? static_cast<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 11232, __PRETTY_FUNCTION__))
11232 "Unhandled vector element size in vector compare")((TypeSize == Context.getTypeSize(Context.CharTy) && "Unhandled vector element size in vector compare"
) ? static_cast<void> (0) : __assert_fail ("TypeSize == Context.getTypeSize(Context.CharTy) && \"Unhandled vector element size in vector compare\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 11232, __PRETTY_FUNCTION__))
;
11233 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
11234 VectorType::GenericVector);
11235}
11236
11237/// CheckVectorCompareOperands - vector comparisons are a clang extension that
11238/// operates on extended vector types. Instead of producing an IntTy result,
11239/// like a scalar comparison, a vector comparison produces a vector of integer
11240/// types.
11241QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
11242 SourceLocation Loc,
11243 BinaryOperatorKind Opc) {
11244 if (Opc == BO_Cmp) {
11245 Diag(Loc, diag::err_three_way_vector_comparison);
11246 return QualType();
11247 }
11248
11249 // Check to make sure we're operating on vectors of the same type and width,
11250 // Allowing one side to be a scalar of element type.
11251 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
11252 /*AllowBothBool*/true,
11253 /*AllowBoolConversions*/getLangOpts().ZVector);
11254 if (vType.isNull())
11255 return vType;
11256
11257 QualType LHSType = LHS.get()->getType();
11258
11259 // If AltiVec, the comparison results in a numeric type, i.e.
11260 // bool for C++, int for C
11261 if (getLangOpts().AltiVec &&
11262 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
11263 return Context.getLogicalOperationType();
11264
11265 // For non-floating point types, check for self-comparisons of the form
11266 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11267 // often indicate logic errors in the program.
11268 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11269
11270 // Check for comparisons of floating point operands using != and ==.
11271 if (BinaryOperator::isEqualityOp(Opc) &&
11272 LHSType->hasFloatingRepresentation()) {
11273 assert(RHS.get()->getType()->hasFloatingRepresentation())((RHS.get()->getType()->hasFloatingRepresentation()) ? static_cast
<void> (0) : __assert_fail ("RHS.get()->getType()->hasFloatingRepresentation()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 11273, __PRETTY_FUNCTION__))
;
11274 CheckFloatComparison(Loc, LHS.get(), RHS.get());
11275 }
11276
11277 // Return a signed type for the vector.
11278 return GetSignedVectorType(vType);
11279}
11280
11281static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
11282 const ExprResult &XorRHS,
11283 const SourceLocation Loc) {
11284 // Do not diagnose macros.
11285 if (Loc.isMacroID())
11286 return;
11287
11288 bool Negative = false;
11289 bool ExplicitPlus = false;
11290 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
11291 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
11292
11293 if (!LHSInt)
11294 return;
11295 if (!RHSInt) {
11296 // Check negative literals.
11297 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
11298 UnaryOperatorKind Opc = UO->getOpcode();
11299 if (Opc != UO_Minus && Opc != UO_Plus)
11300 return;
11301 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
11302 if (!RHSInt)
11303 return;
11304 Negative = (Opc == UO_Minus);
11305 ExplicitPlus = !Negative;
11306 } else {
11307 return;
11308 }
11309 }
11310
11311 const llvm::APInt &LeftSideValue = LHSInt->getValue();
11312 llvm::APInt RightSideValue = RHSInt->getValue();
11313 if (LeftSideValue != 2 && LeftSideValue != 10)
11314 return;
11315
11316 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
11317 return;
11318
11319 CharSourceRange ExprRange = CharSourceRange::getCharRange(
11320 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
11321 llvm::StringRef ExprStr =
11322 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
11323
11324 CharSourceRange XorRange =
11325 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11326 llvm::StringRef XorStr =
11327 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
11328 // Do not diagnose if xor keyword/macro is used.
11329 if (XorStr == "xor")
11330 return;
11331
11332 std::string LHSStr = std::string(Lexer::getSourceText(
11333 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
11334 S.getSourceManager(), S.getLangOpts()));
11335 std::string RHSStr = std::string(Lexer::getSourceText(
11336 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
11337 S.getSourceManager(), S.getLangOpts()));
11338
11339 if (Negative) {
11340 RightSideValue = -RightSideValue;
11341 RHSStr = "-" + RHSStr;
11342 } else if (ExplicitPlus) {
11343 RHSStr = "+" + RHSStr;
11344 }
11345
11346 StringRef LHSStrRef = LHSStr;
11347 StringRef RHSStrRef = RHSStr;
11348 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
11349 // literals.
11350 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
11351 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
11352 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
11353 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
11354 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
11355 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
11356 LHSStrRef.find('\'') != StringRef::npos ||
11357 RHSStrRef.find('\'') != StringRef::npos)
11358 return;
11359
11360 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
11361 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
11362 int64_t RightSideIntValue = RightSideValue.getSExtValue();
11363 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
11364 std::string SuggestedExpr = "1 << " + RHSStr;
11365 bool Overflow = false;
11366 llvm::APInt One = (LeftSideValue - 1);
11367 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
11368 if (Overflow) {
11369 if (RightSideIntValue < 64)
11370 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11371 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
11372 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
11373 else if (RightSideIntValue == 64)
11374 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
11375 else
11376 return;
11377 } else {
11378 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
11379 << ExprStr << XorValue.toString(10, true) << SuggestedExpr
11380 << PowValue.toString(10, true)
11381 << FixItHint::CreateReplacement(
11382 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
11383 }
11384
11385 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
11386 } else if (LeftSideValue == 10) {
11387 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
11388 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
11389 << ExprStr << XorValue.toString(10, true) << SuggestedValue
11390 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
11391 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
11392 }
11393}
11394
11395QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11396 SourceLocation Loc) {
11397 // Ensure that either both operands are of the same vector type, or
11398 // one operand is of a vector type and the other is of its element type.
11399 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
11400 /*AllowBothBool*/true,
11401 /*AllowBoolConversions*/false);
11402 if (vType.isNull())
11403 return InvalidOperands(Loc, LHS, RHS);
11404 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
11405 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
11406 return InvalidOperands(Loc, LHS, RHS);
11407 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
11408 // usage of the logical operators && and || with vectors in C. This
11409 // check could be notionally dropped.
11410 if (!getLangOpts().CPlusPlus &&
11411 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
11412 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
11413
11414 return GetSignedVectorType(LHS.get()->getType());
11415}
11416
11417inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
11418 SourceLocation Loc,
11419 BinaryOperatorKind Opc) {
11420 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11421
11422 bool IsCompAssign =
11423 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
11424
11425 if (LHS.get()->getType()->isVectorType() ||
11426 RHS.get()->getType()->isVectorType()) {
11427 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11428 RHS.get()->getType()->hasIntegerRepresentation())
11429 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11430 /*AllowBothBool*/true,
11431 /*AllowBoolConversions*/getLangOpts().ZVector);
11432 return InvalidOperands(Loc, LHS, RHS);
11433 }
11434
11435 if (Opc == BO_And)
11436 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11437
11438 if (LHS.get()->getType()->hasFloatingRepresentation() ||
11439 RHS.get()->getType()->hasFloatingRepresentation())
11440 return InvalidOperands(Loc, LHS, RHS);
11441
11442 ExprResult LHSResult = LHS, RHSResult = RHS;
11443 QualType compType = UsualArithmeticConversions(
11444 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
11445 if (LHSResult.isInvalid() || RHSResult.isInvalid())
11446 return QualType();
11447 LHS = LHSResult.get();
11448 RHS = RHSResult.get();
11449
11450 if (Opc == BO_Xor)
11451 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
11452
11453 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
11454 return compType;
11455 return InvalidOperands(Loc, LHS, RHS);
11456}
11457
11458// C99 6.5.[13,14]
11459inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
11460 SourceLocation Loc,
11461 BinaryOperatorKind Opc) {
11462 // Check vector operands differently.
11463 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
11464 return CheckVectorLogicalOperands(LHS, RHS, Loc);
11465
11466 bool EnumConstantInBoolContext = false;
11467 for (const ExprResult &HS : {LHS, RHS}) {
11468 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
11469 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
11470 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
11471 EnumConstantInBoolContext = true;
11472 }
11473 }
11474
11475 if (EnumConstantInBoolContext)
11476 Diag(Loc, diag::warn_enum_constant_in_bool_context);
11477
11478 // Diagnose cases where the user write a logical and/or but probably meant a
11479 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
11480 // is a constant.
11481 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
11482 !LHS.get()->getType()->isBooleanType() &&
11483 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
11484 // Don't warn in macros or template instantiations.
11485 !Loc.isMacroID() && !inTemplateInstantiation()) {
11486 // If the RHS can be constant folded, and if it constant folds to something
11487 // that isn't 0 or 1 (which indicate a potential logical operation that
11488 // happened to fold to true/false) then warn.
11489 // Parens on the RHS are ignored.
11490 Expr::EvalResult EVResult;
11491 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
11492 llvm::APSInt Result = EVResult.Val.getInt();
11493 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
11494 !RHS.get()->getExprLoc().isMacroID()) ||
11495 (Result != 0 && Result != 1)) {
11496 Diag(Loc, diag::warn_logical_instead_of_bitwise)
11497 << RHS.get()->getSourceRange()
11498 << (Opc == BO_LAnd ? "&&" : "||");
11499 // Suggest replacing the logical operator with the bitwise version
11500 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
11501 << (Opc == BO_LAnd ? "&" : "|")
11502 << FixItHint::CreateReplacement(SourceRange(
11503 Loc, getLocForEndOfToken(Loc)),
11504 Opc == BO_LAnd ? "&" : "|");
11505 if (Opc == BO_LAnd)
11506 // Suggest replacing "Foo() && kNonZero" with "Foo()"
11507 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
11508 << FixItHint::CreateRemoval(
11509 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
11510 RHS.get()->getEndLoc()));
11511 }
11512 }
11513 }
11514
11515 if (!Context.getLangOpts().CPlusPlus) {
11516 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
11517 // not operate on the built-in scalar and vector float types.
11518 if (Context.getLangOpts().OpenCL &&
11519 Context.getLangOpts().OpenCLVersion < 120) {
11520 if (LHS.get()->getType()->isFloatingType() ||
11521 RHS.get()->getType()->isFloatingType())
11522 return InvalidOperands(Loc, LHS, RHS);
11523 }
11524
11525 LHS = UsualUnaryConversions(LHS.get());
11526 if (LHS.isInvalid())
11527 return QualType();
11528
11529 RHS = UsualUnaryConversions(RHS.get());
11530 if (RHS.isInvalid())
11531 return QualType();
11532
11533 if (!LHS.get()->getType()->isScalarType() ||
11534 !RHS.get()->getType()->isScalarType())
11535 return InvalidOperands(Loc, LHS, RHS);
11536
11537 return Context.IntTy;
11538 }
11539
11540 // The following is safe because we only use this method for
11541 // non-overloadable operands.
11542
11543 // C++ [expr.log.and]p1
11544 // C++ [expr.log.or]p1
11545 // The operands are both contextually converted to type bool.
11546 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11547 if (LHSRes.isInvalid())
11548 return InvalidOperands(Loc, LHS, RHS);
11549 LHS = LHSRes;
11550
11551 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11552 if (RHSRes.isInvalid())
11553 return InvalidOperands(Loc, LHS, RHS);
11554 RHS = RHSRes;
11555
11556 // C++ [expr.log.and]p2
11557 // C++ [expr.log.or]p2
11558 // The result is a bool.
11559 return Context.BoolTy;
11560}
11561
11562static bool IsReadonlyMessage(Expr *E, Sema &S) {
11563 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11564 if (!ME) return false;
11565 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11566 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11567 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11568 if (!Base) return false;
11569 return Base->getMethodDecl() != nullptr;
11570}
11571
11572/// Is the given expression (which must be 'const') a reference to a
11573/// variable which was originally non-const, but which has become
11574/// 'const' due to being captured within a block?
11575enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11576static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11577 assert(E->isLValue() && E->getType().isConstQualified())((E->isLValue() && E->getType().isConstQualified
()) ? static_cast<void> (0) : __assert_fail ("E->isLValue() && E->getType().isConstQualified()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 11577, __PRETTY_FUNCTION__))
;
11578 E = E->IgnoreParens();
11579
11580 // Must be a reference to a declaration from an enclosing scope.
11581 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11582 if (!DRE) return NCCK_None;
11583 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11584
11585 // The declaration must be a variable which is not declared 'const'.
11586 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11587 if (!var) return NCCK_None;
11588 if (var->getType().isConstQualified()) return NCCK_None;
11589 assert(var->hasLocalStorage() && "capture added 'const' to non-local?")((var->hasLocalStorage() && "capture added 'const' to non-local?"
) ? static_cast<void> (0) : __assert_fail ("var->hasLocalStorage() && \"capture added 'const' to non-local?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 11589, __PRETTY_FUNCTION__))
;
11590
11591 // Decide whether the first capture was for a block or a lambda.
11592 DeclContext *DC = S.CurContext, *Prev = nullptr;
11593 // Decide whether the first capture was for a block or a lambda.
11594 while (DC) {
11595 // For init-capture, it is possible that the variable belongs to the
11596 // template pattern of the current context.
11597 if (auto *FD = dyn_cast<FunctionDecl>(DC))
11598 if (var->isInitCapture() &&
11599 FD->getTemplateInstantiationPattern() == var->getDeclContext())
11600 break;
11601 if (DC == var->getDeclContext())
11602 break;
11603 Prev = DC;
11604 DC = DC->getParent();
11605 }
11606 // Unless we have an init-capture, we've gone one step too far.
11607 if (!var->isInitCapture())
11608 DC = Prev;
11609 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11610}
11611
11612static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11613 Ty = Ty.getNonReferenceType();
11614 if (IsDereference && Ty->isPointerType())
11615 Ty = Ty->getPointeeType();
11616 return !Ty.isConstQualified();
11617}
11618
11619// Update err_typecheck_assign_const and note_typecheck_assign_const
11620// when this enum is changed.
11621enum {
11622 ConstFunction,
11623 ConstVariable,
11624 ConstMember,
11625 ConstMethod,
11626 NestedConstMember,
11627 ConstUnknown, // Keep as last element
11628};
11629
11630/// Emit the "read-only variable not assignable" error and print notes to give
11631/// more information about why the variable is not assignable, such as pointing
11632/// to the declaration of a const variable, showing that a method is const, or
11633/// that the function is returning a const reference.
11634static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11635 SourceLocation Loc) {
11636 SourceRange ExprRange = E->getSourceRange();
11637
11638 // Only emit one error on the first const found. All other consts will emit
11639 // a note to the error.
11640 bool DiagnosticEmitted = false;
11641
11642 // Track if the current expression is the result of a dereference, and if the
11643 // next checked expression is the result of a dereference.
11644 bool IsDereference = false;
11645 bool NextIsDereference = false;
11646
11647 // Loop to process MemberExpr chains.
11648 while (true) {
11649 IsDereference = NextIsDereference;
11650
11651 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11652 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11653 NextIsDereference = ME->isArrow();
11654 const ValueDecl *VD = ME->getMemberDecl();
11655 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11656 // Mutable fields can be modified even if the class is const.
11657 if (Field->isMutable()) {
11658 assert(DiagnosticEmitted && "Expected diagnostic not emitted.")((DiagnosticEmitted && "Expected diagnostic not emitted."
) ? static_cast<void> (0) : __assert_fail ("DiagnosticEmitted && \"Expected diagnostic not emitted.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 11658, __PRETTY_FUNCTION__))
;
11659 break;
11660 }
11661
11662 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11663 if (!DiagnosticEmitted) {
11664 S.Diag(Loc, diag::err_typecheck_assign_const)
11665 << ExprRange << ConstMember << false /*static*/ << Field
11666 << Field->getType();
11667 DiagnosticEmitted = true;
11668 }
11669 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11670 << ConstMember << false /*static*/ << Field << Field->getType()
11671 << Field->getSourceRange();
11672 }
11673 E = ME->getBase();
11674 continue;
11675 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11676 if (VDecl->getType().isConstQualified()) {
11677 if (!DiagnosticEmitted) {
11678 S.Diag(Loc, diag::err_typecheck_assign_const)
11679 << ExprRange << ConstMember << true /*static*/ << VDecl
11680 << VDecl->getType();
11681 DiagnosticEmitted = true;
11682 }
11683 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11684 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11685 << VDecl->getSourceRange();
11686 }
11687 // Static fields do not inherit constness from parents.
11688 break;
11689 }
11690 break; // End MemberExpr
11691 } else if (const ArraySubscriptExpr *ASE =
11692 dyn_cast<ArraySubscriptExpr>(E)) {
11693 E = ASE->getBase()->IgnoreParenImpCasts();
11694 continue;
11695 } else if (const ExtVectorElementExpr *EVE =
11696 dyn_cast<ExtVectorElementExpr>(E)) {
11697 E = EVE->getBase()->IgnoreParenImpCasts();
11698 continue;
11699 }
11700 break;
11701 }
11702
11703 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11704 // Function calls
11705 const FunctionDecl *FD = CE->getDirectCallee();
11706 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11707 if (!DiagnosticEmitted) {
11708 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11709 << ConstFunction << FD;
11710 DiagnosticEmitted = true;
11711 }
11712 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11713 diag::note_typecheck_assign_const)
11714 << ConstFunction << FD << FD->getReturnType()
11715 << FD->getReturnTypeSourceRange();
11716 }
11717 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11718 // Point to variable declaration.
11719 if (const ValueDecl *VD = DRE->getDecl()) {
11720 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11721 if (!DiagnosticEmitted) {
11722 S.Diag(Loc, diag::err_typecheck_assign_const)
11723 << ExprRange << ConstVariable << VD << VD->getType();
11724 DiagnosticEmitted = true;
11725 }
11726 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11727 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11728 }
11729 }
11730 } else if (isa<CXXThisExpr>(E)) {
11731 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11732 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11733 if (MD->isConst()) {
11734 if (!DiagnosticEmitted) {
11735 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11736 << ConstMethod << MD;
11737 DiagnosticEmitted = true;
11738 }
11739 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11740 << ConstMethod << MD << MD->getSourceRange();
11741 }
11742 }
11743 }
11744 }
11745
11746 if (DiagnosticEmitted)
11747 return;
11748
11749 // Can't determine a more specific message, so display the generic error.
11750 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11751}
11752
11753enum OriginalExprKind {
11754 OEK_Variable,
11755 OEK_Member,
11756 OEK_LValue
11757};
11758
11759static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11760 const RecordType *Ty,
11761 SourceLocation Loc, SourceRange Range,
11762 OriginalExprKind OEK,
11763 bool &DiagnosticEmitted) {
11764 std::vector<const RecordType *> RecordTypeList;
11765 RecordTypeList.push_back(Ty);
11766 unsigned NextToCheckIndex = 0;
11767 // We walk the record hierarchy breadth-first to ensure that we print
11768 // diagnostics in field nesting order.
11769 while (RecordTypeList.size() > NextToCheckIndex) {
11770 bool IsNested = NextToCheckIndex > 0;
11771 for (const FieldDecl *Field :
11772 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11773 // First, check every field for constness.
11774 QualType FieldTy = Field->getType();
11775 if (FieldTy.isConstQualified()) {
11776 if (!DiagnosticEmitted) {
11777 S.Diag(Loc, diag::err_typecheck_assign_const)
11778 << Range << NestedConstMember << OEK << VD
11779 << IsNested << Field;
11780 DiagnosticEmitted = true;
11781 }
11782 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11783 << NestedConstMember << IsNested << Field
11784 << FieldTy << Field->getSourceRange();
11785 }
11786
11787 // Then we append it to the list to check next in order.
11788 FieldTy = FieldTy.getCanonicalType();
11789 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11790 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11791 RecordTypeList.push_back(FieldRecTy);
11792 }
11793 }
11794 ++NextToCheckIndex;
11795 }
11796}
11797
11798/// Emit an error for the case where a record we are trying to assign to has a
11799/// const-qualified field somewhere in its hierarchy.
11800static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11801 SourceLocation Loc) {
11802 QualType Ty = E->getType();
11803 assert(Ty->isRecordType() && "lvalue was not record?")((Ty->isRecordType() && "lvalue was not record?") ?
static_cast<void> (0) : __assert_fail ("Ty->isRecordType() && \"lvalue was not record?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 11803, __PRETTY_FUNCTION__))
;
11804 SourceRange Range = E->getSourceRange();
11805 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11806 bool DiagEmitted = false;
11807
11808 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11809 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11810 Range, OEK_Member, DiagEmitted);
11811 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11812 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11813 Range, OEK_Variable, DiagEmitted);
11814 else
11815 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11816 Range, OEK_LValue, DiagEmitted);
11817 if (!DiagEmitted)
11818 DiagnoseConstAssignment(S, E, Loc);
11819}
11820
11821/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
11822/// emit an error and return true. If so, return false.
11823static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11824 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject))((!E->hasPlaceholderType(BuiltinType::PseudoObject)) ? static_cast
<void> (0) : __assert_fail ("!E->hasPlaceholderType(BuiltinType::PseudoObject)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 11824, __PRETTY_FUNCTION__))
;
11825
11826 S.CheckShadowingDeclModification(E, Loc);
11827
11828 SourceLocation OrigLoc = Loc;
11829 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11830 &Loc);
11831 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11832 IsLV = Expr::MLV_InvalidMessageExpression;
11833 if (IsLV == Expr::MLV_Valid)
11834 return false;
11835
11836 unsigned DiagID = 0;
11837 bool NeedType = false;
11838 switch (IsLV) { // C99 6.5.16p2
11839 case Expr::MLV_ConstQualified:
11840 // Use a specialized diagnostic when we're assigning to an object
11841 // from an enclosing function or block.
11842 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11843 if (NCCK == NCCK_Block)
11844 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11845 else
11846 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11847 break;
11848 }
11849
11850 // In ARC, use some specialized diagnostics for occasions where we
11851 // infer 'const'. These are always pseudo-strong variables.
11852 if (S.getLangOpts().ObjCAutoRefCount) {
11853 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11854 if (declRef && isa<VarDecl>(declRef->getDecl())) {
11855 VarDecl *var = cast<VarDecl>(declRef->getDecl());
11856
11857 // Use the normal diagnostic if it's pseudo-__strong but the
11858 // user actually wrote 'const'.
11859 if (var->isARCPseudoStrong() &&
11860 (!var->getTypeSourceInfo() ||
11861 !var->getTypeSourceInfo()->getType().isConstQualified())) {
11862 // There are three pseudo-strong cases:
11863 // - self
11864 ObjCMethodDecl *method = S.getCurMethodDecl();
11865 if (method && var == method->getSelfDecl()) {
11866 DiagID = method->isClassMethod()
11867 ? diag::err_typecheck_arc_assign_self_class_method
11868 : diag::err_typecheck_arc_assign_self;
11869
11870 // - Objective-C externally_retained attribute.
11871 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11872 isa<ParmVarDecl>(var)) {
11873 DiagID = diag::err_typecheck_arc_assign_externally_retained;
11874
11875 // - fast enumeration variables
11876 } else {
11877 DiagID = diag::err_typecheck_arr_assign_enumeration;
11878 }
11879
11880 SourceRange Assign;
11881 if (Loc != OrigLoc)
11882 Assign = SourceRange(OrigLoc, OrigLoc);
11883 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11884 // We need to preserve the AST regardless, so migration tool
11885 // can do its job.
11886 return false;
11887 }
11888 }
11889 }
11890
11891 // If none of the special cases above are triggered, then this is a
11892 // simple const assignment.
11893 if (DiagID == 0) {
11894 DiagnoseConstAssignment(S, E, Loc);
11895 return true;
11896 }
11897
11898 break;
11899 case Expr::MLV_ConstAddrSpace:
11900 DiagnoseConstAssignment(S, E, Loc);
11901 return true;
11902 case Expr::MLV_ConstQualifiedField:
11903 DiagnoseRecursiveConstFields(S, E, Loc);
11904 return true;
11905 case Expr::MLV_ArrayType:
11906 case Expr::MLV_ArrayTemporary:
11907 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11908 NeedType = true;
11909 break;
11910 case Expr::MLV_NotObjectType:
11911 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11912 NeedType = true;
11913 break;
11914 case Expr::MLV_LValueCast:
11915 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11916 break;
11917 case Expr::MLV_Valid:
11918 llvm_unreachable("did not take early return for MLV_Valid")::llvm::llvm_unreachable_internal("did not take early return for MLV_Valid"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 11918)
;
11919 case Expr::MLV_InvalidExpression:
11920 case Expr::MLV_MemberFunction:
11921 case Expr::MLV_ClassTemporary:
11922 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11923 break;
11924 case Expr::MLV_IncompleteType:
11925 case Expr::MLV_IncompleteVoidType:
11926 return S.RequireCompleteType(Loc, E->getType(),
11927 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11928 case Expr::MLV_DuplicateVectorComponents:
11929 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11930 break;
11931 case Expr::MLV_NoSetterProperty:
11932 llvm_unreachable("readonly properties should be processed differently")::llvm::llvm_unreachable_internal("readonly properties should be processed differently"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 11932)
;
11933 case Expr::MLV_InvalidMessageExpression:
11934 DiagID = diag::err_readonly_message_assignment;
11935 break;
11936 case Expr::MLV_SubObjCPropertySetting:
11937 DiagID = diag::err_no_subobject_property_setting;
11938 break;
11939 }
11940
11941 SourceRange Assign;
11942 if (Loc != OrigLoc)
11943 Assign = SourceRange(OrigLoc, OrigLoc);
11944 if (NeedType)
11945 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11946 else
11947 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11948 return true;
11949}
11950
11951static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11952 SourceLocation Loc,
11953 Sema &Sema) {
11954 if (Sema.inTemplateInstantiation())
11955 return;
11956 if (Sema.isUnevaluatedContext())
11957 return;
11958 if (Loc.isInvalid() || Loc.isMacroID())
11959 return;
11960 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11961 return;
11962
11963 // C / C++ fields
11964 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11965 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11966 if (ML && MR) {
11967 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11968 return;
11969 const ValueDecl *LHSDecl =
11970 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11971 const ValueDecl *RHSDecl =
11972 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11973 if (LHSDecl != RHSDecl)
11974 return;
11975 if (LHSDecl->getType().isVolatileQualified())
11976 return;
11977 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11978 if (RefTy->getPointeeType().isVolatileQualified())
11979 return;
11980
11981 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11982 }
11983
11984 // Objective-C instance variables
11985 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11986 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11987 if (OL && OR && OL->getDecl() == OR->getDecl()) {
11988 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11989 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11990 if (RL && RR && RL->getDecl() == RR->getDecl())
11991 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11992 }
11993}
11994
11995// C99 6.5.16.1
11996QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11997 SourceLocation Loc,
11998 QualType CompoundType) {
11999 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))((!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject))
? static_cast<void> (0) : __assert_fail ("!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 11999, __PRETTY_FUNCTION__))
;
12000
12001 // Verify that LHS is a modifiable lvalue, and emit error if not.
12002 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12003 return QualType();
12004
12005 QualType LHSType = LHSExpr->getType();
12006 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12007 CompoundType;
12008 // OpenCL v1.2 s6.1.1.1 p2:
12009 // The half data type can only be used to declare a pointer to a buffer that
12010 // contains half values
12011 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12012 LHSType->isHalfType()) {
12013 Diag(Loc, diag::err_opencl_half_load_store) << 1
12014 << LHSType.getUnqualifiedType();
12015 return QualType();
12016 }
12017
12018 AssignConvertType ConvTy;
12019 if (CompoundType.isNull()) {
12020 Expr *RHSCheck = RHS.get();
12021
12022 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12023
12024 QualType LHSTy(LHSType);
12025 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12026 if (RHS.isInvalid())
12027 return QualType();
12028 // Special case of NSObject attributes on c-style pointer types.
12029 if (ConvTy == IncompatiblePointer &&
12030 ((Context.isObjCNSObjectType(LHSType) &&
12031 RHSType->isObjCObjectPointerType()) ||
12032 (Context.isObjCNSObjectType(RHSType) &&
12033 LHSType->isObjCObjectPointerType())))
12034 ConvTy = Compatible;
12035
12036 if (ConvTy == Compatible &&
12037 LHSType->isObjCObjectType())
12038 Diag(Loc, diag::err_objc_object_assignment)
12039 << LHSType;
12040
12041 // If the RHS is a unary plus or minus, check to see if they = and + are
12042 // right next to each other. If so, the user may have typo'd "x =+ 4"
12043 // instead of "x += 4".
12044 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12045 RHSCheck = ICE->getSubExpr();
12046 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12047 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12048 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12049 // Only if the two operators are exactly adjacent.
12050 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12051 // And there is a space or other character before the subexpr of the
12052 // unary +/-. We don't want to warn on "x=-1".
12053 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12054 UO->getSubExpr()->getBeginLoc().isFileID()) {
12055 Diag(Loc, diag::warn_not_compound_assign)
12056 << (UO->getOpcode() == UO_Plus ? "+" : "-")
12057 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12058 }
12059 }
12060
12061 if (ConvTy == Compatible) {
12062 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12063 // Warn about retain cycles where a block captures the LHS, but
12064 // not if the LHS is a simple variable into which the block is
12065 // being stored...unless that variable can be captured by reference!
12066 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12067 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12068 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12069 checkRetainCycles(LHSExpr, RHS.get());
12070 }
12071
12072 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12073 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12074 // It is safe to assign a weak reference into a strong variable.
12075 // Although this code can still have problems:
12076 // id x = self.weakProp;
12077 // id y = self.weakProp;
12078 // we do not warn to warn spuriously when 'x' and 'y' are on separate
12079 // paths through the function. This should be revisited if
12080 // -Wrepeated-use-of-weak is made flow-sensitive.
12081 // For ObjCWeak only, we do not warn if the assign is to a non-weak
12082 // variable, which will be valid for the current autorelease scope.
12083 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12084 RHS.get()->getBeginLoc()))
12085 getCurFunction()->markSafeWeakUse(RHS.get());
12086
12087 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12088 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12089 }
12090 }
12091 } else {
12092 // Compound assignment "x += y"
12093 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12094 }
12095
12096 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12097 RHS.get(), AA_Assigning))
12098 return QualType();
12099
12100 CheckForNullPointerDereference(*this, LHSExpr);
12101
12102 if (getLangOpts().CPlusPlus2a && LHSType.isVolatileQualified()) {
12103 if (CompoundType.isNull()) {
12104 // C++2a [expr.ass]p5:
12105 // A simple-assignment whose left operand is of a volatile-qualified
12106 // type is deprecated unless the assignment is either a discarded-value
12107 // expression or an unevaluated operand
12108 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12109 } else {
12110 // C++2a [expr.ass]p6:
12111 // [Compound-assignment] expressions are deprecated if E1 has
12112 // volatile-qualified type
12113 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
12114 }
12115 }
12116
12117 // C99 6.5.16p3: The type of an assignment expression is the type of the
12118 // left operand unless the left operand has qualified type, in which case
12119 // it is the unqualified version of the type of the left operand.
12120 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
12121 // is converted to the type of the assignment expression (above).
12122 // C++ 5.17p1: the type of the assignment expression is that of its left
12123 // operand.
12124 return (getLangOpts().CPlusPlus
12125 ? LHSType : LHSType.getUnqualifiedType());
12126}
12127
12128// Only ignore explicit casts to void.
12129static bool IgnoreCommaOperand(const Expr *E) {
12130 E = E->IgnoreParens();
12131
12132 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
12133 if (CE->getCastKind() == CK_ToVoid) {
12134 return true;
12135 }
12136
12137 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
12138 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
12139 CE->getSubExpr()->getType()->isDependentType()) {
12140 return true;
12141 }
12142 }
12143
12144 return false;
12145}
12146
12147// Look for instances where it is likely the comma operator is confused with
12148// another operator. There is a whitelist of acceptable expressions for the
12149// left hand side of the comma operator, otherwise emit a warning.
12150void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
12151 // No warnings in macros
12152 if (Loc.isMacroID())
12153 return;
12154
12155 // Don't warn in template instantiations.
12156 if (inTemplateInstantiation())
12157 return;
12158
12159 // Scope isn't fine-grained enough to whitelist the specific cases, so
12160 // instead, skip more than needed, then call back into here with the
12161 // CommaVisitor in SemaStmt.cpp.
12162 // The whitelisted locations are the initialization and increment portions
12163 // of a for loop. The additional checks are on the condition of
12164 // if statements, do/while loops, and for loops.
12165 // Differences in scope flags for C89 mode requires the extra logic.
12166 const unsigned ForIncrementFlags =
12167 getLangOpts().C99 || getLangOpts().CPlusPlus
12168 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
12169 : Scope::ContinueScope | Scope::BreakScope;
12170 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
12171 const unsigned ScopeFlags = getCurScope()->getFlags();
12172 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
12173 (ScopeFlags & ForInitFlags) == ForInitFlags)
12174 return;
12175
12176 // If there are multiple comma operators used together, get the RHS of the
12177 // of the comma operator as the LHS.
12178 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
12179 if (BO->getOpcode() != BO_Comma)
12180 break;
12181 LHS = BO->getRHS();
12182 }
12183
12184 // Only allow some expressions on LHS to not warn.
12185 if (IgnoreCommaOperand(LHS))
12186 return;
12187
12188 Diag(Loc, diag::warn_comma_operator);
12189 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
12190 << LHS->getSourceRange()
12191 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
12192 LangOpts.CPlusPlus ? "static_cast<void>("
12193 : "(void)(")
12194 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
12195 ")");
12196}
12197
12198// C99 6.5.17
12199static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
12200 SourceLocation Loc) {
12201 LHS = S.CheckPlaceholderExpr(LHS.get());
12202 RHS = S.CheckPlaceholderExpr(RHS.get());
12203 if (LHS.isInvalid() || RHS.isInvalid())
12204 return QualType();
12205
12206 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
12207 // operands, but not unary promotions.
12208 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
12209
12210 // So we treat the LHS as a ignored value, and in C++ we allow the
12211 // containing site to determine what should be done with the RHS.
12212 LHS = S.IgnoredValueConversions(LHS.get());
12213 if (LHS.isInvalid())
12214 return QualType();
12215
12216 S.DiagnoseUnusedExprResult(LHS.get());
12217
12218 if (!S.getLangOpts().CPlusPlus) {
12219 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
12220 if (RHS.isInvalid())
12221 return QualType();
12222 if (!RHS.get()->getType()->isVoidType())
12223 S.RequireCompleteType(Loc, RHS.get()->getType(),
12224 diag::err_incomplete_type);
12225 }
12226
12227 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
12228 S.DiagnoseCommaOperator(LHS.get(), Loc);
12229
12230 return RHS.get()->getType();
12231}
12232
12233/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
12234/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
12235static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
12236 ExprValueKind &VK,
12237 ExprObjectKind &OK,
12238 SourceLocation OpLoc,
12239 bool IsInc, bool IsPrefix) {
12240 if (Op->isTypeDependent())
12241 return S.Context.DependentTy;
12242
12243 QualType ResType = Op->getType();
12244 // Atomic types can be used for increment / decrement where the non-atomic
12245 // versions can, so ignore the _Atomic() specifier for the purpose of
12246 // checking.
12247 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
12248 ResType = ResAtomicType->getValueType();
12249
12250 assert(!ResType.isNull() && "no type for increment/decrement expression")((!ResType.isNull() && "no type for increment/decrement expression"
) ? static_cast<void> (0) : __assert_fail ("!ResType.isNull() && \"no type for increment/decrement expression\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 12250, __PRETTY_FUNCTION__))
;
12251
12252 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
12253 // Decrement of bool is not allowed.
12254 if (!IsInc) {
12255 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
12256 return QualType();
12257 }
12258 // Increment of bool sets it to true, but is deprecated.
12259 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
12260 : diag::warn_increment_bool)
12261 << Op->getSourceRange();
12262 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
12263 // Error on enum increments and decrements in C++ mode
12264 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
12265 return QualType();
12266 } else if (ResType->isRealType()) {
12267 // OK!
12268 } else if (ResType->isPointerType()) {
12269 // C99 6.5.2.4p2, 6.5.6p2
12270 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
12271 return QualType();
12272 } else if (ResType->isObjCObjectPointerType()) {
12273 // On modern runtimes, ObjC pointer arithmetic is forbidden.
12274 // Otherwise, we just need a complete type.
12275 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
12276 checkArithmeticOnObjCPointer(S, OpLoc, Op))
12277 return QualType();
12278 } else if (ResType->isAnyComplexType()) {
12279 // C99 does not support ++/-- on complex types, we allow as an extension.
12280 S.Diag(OpLoc, diag::ext_integer_increment_complex)
12281 << ResType << Op->getSourceRange();
12282 } else if (ResType->isPlaceholderType()) {
12283 ExprResult PR = S.CheckPlaceholderExpr(Op);
12284 if (PR.isInvalid()) return QualType();
12285 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
12286 IsInc, IsPrefix);
12287 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
12288 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
12289 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
12290 (ResType->castAs<VectorType>()->getVectorKind() !=
12291 VectorType::AltiVecBool)) {
12292 // The z vector extensions allow ++ and -- for non-bool vectors.
12293 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
12294 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
12295 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
12296 } else {
12297 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
12298 << ResType << int(IsInc) << Op->getSourceRange();
12299 return QualType();
12300 }
12301 // At this point, we know we have a real, complex or pointer type.
12302 // Now make sure the operand is a modifiable lvalue.
12303 if (CheckForModifiableLvalue(Op, OpLoc, S))
12304 return QualType();
12305 if (S.getLangOpts().CPlusPlus2a && ResType.isVolatileQualified()) {
12306 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
12307 // An operand with volatile-qualified type is deprecated
12308 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
12309 << IsInc << ResType;
12310 }
12311 // In C++, a prefix increment is the same type as the operand. Otherwise
12312 // (in C or with postfix), the increment is the unqualified type of the
12313 // operand.
12314 if (IsPrefix && S.getLangOpts().CPlusPlus) {
12315 VK = VK_LValue;
12316 OK = Op->getObjectKind();
12317 return ResType;
12318 } else {
12319 VK = VK_RValue;
12320 return ResType.getUnqualifiedType();
12321 }
12322}
12323
12324
12325/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
12326/// This routine allows us to typecheck complex/recursive expressions
12327/// where the declaration is needed for type checking. We only need to
12328/// handle cases when the expression references a function designator
12329/// or is an lvalue. Here are some examples:
12330/// - &(x) => x
12331/// - &*****f => f for f a function designator.
12332/// - &s.xx => s
12333/// - &s.zz[1].yy -> s, if zz is an array
12334/// - *(x + 1) -> x, if x is an array
12335/// - &"123"[2] -> 0
12336/// - & __real__ x -> x
12337static ValueDecl *getPrimaryDecl(Expr *E) {
12338 switch (E->getStmtClass()) {
12339 case Stmt::DeclRefExprClass:
12340 return cast<DeclRefExpr>(E)->getDecl();
12341 case Stmt::MemberExprClass:
12342 // If this is an arrow operator, the address is an offset from
12343 // the base's value, so the object the base refers to is
12344 // irrelevant.
12345 if (cast<MemberExpr>(E)->isArrow())
12346 return nullptr;
12347 // Otherwise, the expression refers to a part of the base
12348 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
12349 case Stmt::ArraySubscriptExprClass: {
12350 // FIXME: This code shouldn't be necessary! We should catch the implicit
12351 // promotion of register arrays earlier.
12352 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
12353 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
12354 if (ICE->getSubExpr()->getType()->isArrayType())
12355 return getPrimaryDecl(ICE->getSubExpr());
12356 }
12357 return nullptr;
12358 }
12359 case Stmt::UnaryOperatorClass: {
12360 UnaryOperator *UO = cast<UnaryOperator>(E);
12361
12362 switch(UO->getOpcode()) {
12363 case UO_Real:
12364 case UO_Imag:
12365 case UO_Extension:
12366 return getPrimaryDecl(UO->getSubExpr());
12367 default:
12368 return nullptr;
12369 }
12370 }
12371 case Stmt::ParenExprClass:
12372 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
12373 case Stmt::ImplicitCastExprClass:
12374 // If the result of an implicit cast is an l-value, we care about
12375 // the sub-expression; otherwise, the result here doesn't matter.
12376 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
12377 default:
12378 return nullptr;
12379 }
12380}
12381
12382namespace {
12383 enum {
12384 AO_Bit_Field = 0,
12385 AO_Vector_Element = 1,
12386 AO_Property_Expansion = 2,
12387 AO_Register_Variable = 3,
12388 AO_No_Error = 4
12389 };
12390}
12391/// Diagnose invalid operand for address of operations.
12392///
12393/// \param Type The type of operand which cannot have its address taken.
12394static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
12395 Expr *E, unsigned Type) {
12396 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
12397}
12398
12399/// CheckAddressOfOperand - The operand of & must be either a function
12400/// designator or an lvalue designating an object. If it is an lvalue, the
12401/// object cannot be declared with storage class register or be a bit field.
12402/// Note: The usual conversions are *not* applied to the operand of the &
12403/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
12404/// In C++, the operand might be an overloaded function name, in which case
12405/// we allow the '&' but retain the overloaded-function type.
12406QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
12407 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
12408 if (PTy->getKind() == BuiltinType::Overload) {
12409 Expr *E = OrigOp.get()->IgnoreParens();
12410 if (!isa<OverloadExpr>(E)) {
12411 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)((cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) ?
static_cast<void> (0) : __assert_fail ("cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 12411, __PRETTY_FUNCTION__))
;
12412 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
12413 << OrigOp.get()->getSourceRange();
12414 return QualType();
12415 }
12416
12417 OverloadExpr *Ovl = cast<OverloadExpr>(E);
12418 if (isa<UnresolvedMemberExpr>(Ovl))
12419 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
12420 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12421 << OrigOp.get()->getSourceRange();
12422 return QualType();
12423 }
12424
12425 return Context.OverloadTy;
12426 }
12427
12428 if (PTy->getKind() == BuiltinType::UnknownAny)
12429 return Context.UnknownAnyTy;
12430
12431 if (PTy->getKind() == BuiltinType::BoundMember) {
12432 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12433 << OrigOp.get()->getSourceRange();
12434 return QualType();
12435 }
12436
12437 OrigOp = CheckPlaceholderExpr(OrigOp.get());
12438 if (OrigOp.isInvalid()) return QualType();
12439 }
12440
12441 if (OrigOp.get()->isTypeDependent())
12442 return Context.DependentTy;
12443
12444 assert(!OrigOp.get()->getType()->isPlaceholderType())((!OrigOp.get()->getType()->isPlaceholderType()) ? static_cast
<void> (0) : __assert_fail ("!OrigOp.get()->getType()->isPlaceholderType()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 12444, __PRETTY_FUNCTION__))
;
12445
12446 // Make sure to ignore parentheses in subsequent checks
12447 Expr *op = OrigOp.get()->IgnoreParens();
12448
12449 // In OpenCL captures for blocks called as lambda functions
12450 // are located in the private address space. Blocks used in
12451 // enqueue_kernel can be located in a different address space
12452 // depending on a vendor implementation. Thus preventing
12453 // taking an address of the capture to avoid invalid AS casts.
12454 if (LangOpts.OpenCL) {
12455 auto* VarRef = dyn_cast<DeclRefExpr>(op);
12456 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
12457 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
12458 return QualType();
12459 }
12460 }
12461
12462 if (getLangOpts().C99) {
12463 // Implement C99-only parts of addressof rules.
12464 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
12465 if (uOp->getOpcode() == UO_Deref)
12466 // Per C99 6.5.3.2, the address of a deref always returns a valid result
12467 // (assuming the deref expression is valid).
12468 return uOp->getSubExpr()->getType();
12469 }
12470 // Technically, there should be a check for array subscript
12471 // expressions here, but the result of one is always an lvalue anyway.
12472 }
12473 ValueDecl *dcl = getPrimaryDecl(op);
12474
12475 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
12476 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12477 op->getBeginLoc()))
12478 return QualType();
12479
12480 Expr::LValueClassification lval = op->ClassifyLValue(Context);
12481 unsigned AddressOfError = AO_No_Error;
12482
12483 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
12484 bool sfinae = (bool)isSFINAEContext();
12485 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
12486 : diag::ext_typecheck_addrof_temporary)
12487 << op->getType() << op->getSourceRange();
12488 if (sfinae)
12489 return QualType();
12490 // Materialize the temporary as an lvalue so that we can take its address.
12491 OrigOp = op =
12492 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
12493 } else if (isa<ObjCSelectorExpr>(op)) {
12494 return Context.getPointerType(op->getType());
12495 } else if (lval == Expr::LV_MemberFunction) {
12496 // If it's an instance method, make a member pointer.
12497 // The expression must have exactly the form &A::foo.
12498
12499 // If the underlying expression isn't a decl ref, give up.
12500 if (!isa<DeclRefExpr>(op)) {
12501 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
12502 << OrigOp.get()->getSourceRange();
12503 return QualType();
12504 }
12505 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
12506 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
12507
12508 // The id-expression was parenthesized.
12509 if (OrigOp.get() != DRE) {
12510 Diag(OpLoc, diag::err_parens_pointer_member_function)
12511 << OrigOp.get()->getSourceRange();
12512
12513 // The method was named without a qualifier.
12514 } else if (!DRE->getQualifier()) {
12515 if (MD->getParent()->getName().empty())
12516 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12517 << op->getSourceRange();
12518 else {
12519 SmallString<32> Str;
12520 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
12521 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
12522 << op->getSourceRange()
12523 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
12524 }
12525 }
12526
12527 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
12528 if (isa<CXXDestructorDecl>(MD))
12529 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
12530
12531 QualType MPTy = Context.getMemberPointerType(
12532 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
12533 // Under the MS ABI, lock down the inheritance model now.
12534 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12535 (void)isCompleteType(OpLoc, MPTy);
12536 return MPTy;
12537 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
12538 // C99 6.5.3.2p1
12539 // The operand must be either an l-value or a function designator
12540 if (!op->getType()->isFunctionType()) {
12541 // Use a special diagnostic for loads from property references.
12542 if (isa<PseudoObjectExpr>(op)) {
12543 AddressOfError = AO_Property_Expansion;
12544 } else {
12545 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12546 << op->getType() << op->getSourceRange();
12547 return QualType();
12548 }
12549 }
12550 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12551 // The operand cannot be a bit-field
12552 AddressOfError = AO_Bit_Field;
12553 } else if (op->getObjectKind() == OK_VectorComponent) {
12554 // The operand cannot be an element of a vector
12555 AddressOfError = AO_Vector_Element;
12556 } else if (dcl) { // C99 6.5.3.2p1
12557 // We have an lvalue with a decl. Make sure the decl is not declared
12558 // with the register storage-class specifier.
12559 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12560 // in C++ it is not error to take address of a register
12561 // variable (c++03 7.1.1P3)
12562 if (vd->getStorageClass() == SC_Register &&
12563 !getLangOpts().CPlusPlus) {
12564 AddressOfError = AO_Register_Variable;
12565 }
12566 } else if (isa<MSPropertyDecl>(dcl)) {
12567 AddressOfError = AO_Property_Expansion;
12568 } else if (isa<FunctionTemplateDecl>(dcl)) {
12569 return Context.OverloadTy;
12570 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12571 // Okay: we can take the address of a field.
12572 // Could be a pointer to member, though, if there is an explicit
12573 // scope qualifier for the class.
12574 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12575 DeclContext *Ctx = dcl->getDeclContext();
12576 if (Ctx && Ctx->isRecord()) {
12577 if (dcl->getType()->isReferenceType()) {
12578 Diag(OpLoc,
12579 diag::err_cannot_form_pointer_to_member_of_reference_type)
12580 << dcl->getDeclName() << dcl->getType();
12581 return QualType();
12582 }
12583
12584 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12585 Ctx = Ctx->getParent();
12586
12587 QualType MPTy = Context.getMemberPointerType(
12588 op->getType(),
12589 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12590 // Under the MS ABI, lock down the inheritance model now.
12591 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12592 (void)isCompleteType(OpLoc, MPTy);
12593 return MPTy;
12594 }
12595 }
12596 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12597 !isa<BindingDecl>(dcl))
12598 llvm_unreachable("Unknown/unexpected decl type")::llvm::llvm_unreachable_internal("Unknown/unexpected decl type"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 12598)
;
12599 }
12600
12601 if (AddressOfError != AO_No_Error) {
12602 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12603 return QualType();
12604 }
12605
12606 if (lval == Expr::LV_IncompleteVoidType) {
12607 // Taking the address of a void variable is technically illegal, but we
12608 // allow it in cases which are otherwise valid.
12609 // Example: "extern void x; void* y = &x;".
12610 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12611 }
12612
12613 // If the operand has type "type", the result has type "pointer to type".
12614 if (op->getType()->isObjCObjectType())
12615 return Context.getObjCObjectPointerType(op->getType());
12616
12617 CheckAddressOfPackedMember(op);
12618
12619 return Context.getPointerType(op->getType());
12620}
12621
12622static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12623 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12624 if (!DRE)
12625 return;
12626 const Decl *D = DRE->getDecl();
12627 if (!D)
12628 return;
12629 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12630 if (!Param)
12631 return;
12632 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12633 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12634 return;
12635 if (FunctionScopeInfo *FD = S.getCurFunction())
12636 if (!FD->ModifiedNonNullParams.count(Param))
12637 FD->ModifiedNonNullParams.insert(Param);
12638}
12639
12640/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12641static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12642 SourceLocation OpLoc) {
12643 if (Op->isTypeDependent())
12644 return S.Context.DependentTy;
12645
12646 ExprResult ConvResult = S.UsualUnaryConversions(Op);
12647 if (ConvResult.isInvalid())
12648 return QualType();
12649 Op = ConvResult.get();
12650 QualType OpTy = Op->getType();
12651 QualType Result;
12652
12653 if (isa<CXXReinterpretCastExpr>(Op)) {
12654 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12655 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12656 Op->getSourceRange());
12657 }
12658
12659 if (const PointerType *PT = OpTy->getAs<PointerType>())
12660 {
12661 Result = PT->getPointeeType();
12662 }
12663 else if (const ObjCObjectPointerType *OPT =
12664 OpTy->getAs<ObjCObjectPointerType>())
12665 Result = OPT->getPointeeType();
12666 else {
12667 ExprResult PR = S.CheckPlaceholderExpr(Op);
12668 if (PR.isInvalid()) return QualType();
12669 if (PR.get() != Op)
12670 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12671 }
12672
12673 if (Result.isNull()) {
12674 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12675 << OpTy << Op->getSourceRange();
12676 return QualType();
12677 }
12678
12679 // Note that per both C89 and C99, indirection is always legal, even if Result
12680 // is an incomplete type or void. It would be possible to warn about
12681 // dereferencing a void pointer, but it's completely well-defined, and such a
12682 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12683 // for pointers to 'void' but is fine for any other pointer type:
12684 //
12685 // C++ [expr.unary.op]p1:
12686 // [...] the expression to which [the unary * operator] is applied shall
12687 // be a pointer to an object type, or a pointer to a function type
12688 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12689 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12690 << OpTy << Op->getSourceRange();
12691
12692 // Dereferences are usually l-values...
12693 VK = VK_LValue;
12694
12695 // ...except that certain expressions are never l-values in C.
12696 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12697 VK = VK_RValue;
12698
12699 return Result;
12700}
12701
12702BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12703 BinaryOperatorKind Opc;
12704 switch (Kind) {
12705 default: llvm_unreachable("Unknown binop!")::llvm::llvm_unreachable_internal("Unknown binop!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 12705)
;
12706 case tok::periodstar: Opc = BO_PtrMemD; break;
12707 case tok::arrowstar: Opc = BO_PtrMemI; break;
12708 case tok::star: Opc = BO_Mul; break;
12709 case tok::slash: Opc = BO_Div; break;
12710 case tok::percent: Opc = BO_Rem; break;
12711 case tok::plus: Opc = BO_Add; break;
12712 case tok::minus: Opc = BO_Sub; break;
12713 case tok::lessless: Opc = BO_Shl; break;
12714 case tok::greatergreater: Opc = BO_Shr; break;
12715 case tok::lessequal: Opc = BO_LE; break;
12716 case tok::less: Opc = BO_LT; break;
12717 case tok::greaterequal: Opc = BO_GE; break;
12718 case tok::greater: Opc = BO_GT; break;
12719 case tok::exclaimequal: Opc = BO_NE; break;
12720 case tok::equalequal: Opc = BO_EQ; break;
12721 case tok::spaceship: Opc = BO_Cmp; break;
12722 case tok::amp: Opc = BO_And; break;
12723 case tok::caret: Opc = BO_Xor; break;
12724 case tok::pipe: Opc = BO_Or; break;
12725 case tok::ampamp: Opc = BO_LAnd; break;
12726 case tok::pipepipe: Opc = BO_LOr; break;
12727 case tok::equal: Opc = BO_Assign; break;
12728 case tok::starequal: Opc = BO_MulAssign; break;
12729 case tok::slashequal: Opc = BO_DivAssign; break;
12730 case tok::percentequal: Opc = BO_RemAssign; break;
12731 case tok::plusequal: Opc = BO_AddAssign; break;
12732 case tok::minusequal: Opc = BO_SubAssign; break;
12733 case tok::lesslessequal: Opc = BO_ShlAssign; break;
12734 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
12735 case tok::ampequal: Opc = BO_AndAssign; break;
12736 case tok::caretequal: Opc = BO_XorAssign; break;
12737 case tok::pipeequal: Opc = BO_OrAssign; break;
12738 case tok::comma: Opc = BO_Comma; break;
12739 }
12740 return Opc;
12741}
12742
12743static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12744 tok::TokenKind Kind) {
12745 UnaryOperatorKind Opc;
12746 switch (Kind) {
12747 default: llvm_unreachable("Unknown unary op!")::llvm::llvm_unreachable_internal("Unknown unary op!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 12747)
;
12748 case tok::plusplus: Opc = UO_PreInc; break;
12749 case tok::minusminus: Opc = UO_PreDec; break;
12750 case tok::amp: Opc = UO_AddrOf; break;
12751 case tok::star: Opc = UO_Deref; break;
12752 case tok::plus: Opc = UO_Plus; break;
12753 case tok::minus: Opc = UO_Minus; break;
12754 case tok::tilde: Opc = UO_Not; break;
12755 case tok::exclaim: Opc = UO_LNot; break;
12756 case tok::kw___real: Opc = UO_Real; break;
12757 case tok::kw___imag: Opc = UO_Imag; break;
12758 case tok::kw___extension__: Opc = UO_Extension; break;
12759 }
12760 return Opc;
12761}
12762
12763/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12764/// This warning suppressed in the event of macro expansions.
12765static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12766 SourceLocation OpLoc, bool IsBuiltin) {
12767 if (S.inTemplateInstantiation())
12768 return;
12769 if (S.isUnevaluatedContext())
12770 return;
12771 if (OpLoc.isInvalid() || OpLoc.isMacroID())
12772 return;
12773 LHSExpr = LHSExpr->IgnoreParenImpCasts();
12774 RHSExpr = RHSExpr->IgnoreParenImpCasts();
12775 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12776 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12777 if (!LHSDeclRef || !RHSDeclRef ||
12778 LHSDeclRef->getLocation().isMacroID() ||
12779 RHSDeclRef->getLocation().isMacroID())
12780 return;
12781 const ValueDecl *LHSDecl =
12782 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12783 const ValueDecl *RHSDecl =
12784 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12785 if (LHSDecl != RHSDecl)
12786 return;
12787 if (LHSDecl->getType().isVolatileQualified())
12788 return;
12789 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12790 if (RefTy->getPointeeType().isVolatileQualified())
12791 return;
12792
12793 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12794 : diag::warn_self_assignment_overloaded)
12795 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12796 << RHSExpr->getSourceRange();
12797}
12798
12799/// Check if a bitwise-& is performed on an Objective-C pointer. This
12800/// is usually indicative of introspection within the Objective-C pointer.
12801static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12802 SourceLocation OpLoc) {
12803 if (!S.getLangOpts().ObjC)
12804 return;
12805
12806 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12807 const Expr *LHS = L.get();
12808 const Expr *RHS = R.get();
12809
12810 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12811 ObjCPointerExpr = LHS;
12812 OtherExpr = RHS;
12813 }
12814 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12815 ObjCPointerExpr = RHS;
12816 OtherExpr = LHS;
12817 }
12818
12819 // This warning is deliberately made very specific to reduce false
12820 // positives with logic that uses '&' for hashing. This logic mainly
12821 // looks for code trying to introspect into tagged pointers, which
12822 // code should generally never do.
12823 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12824 unsigned Diag = diag::warn_objc_pointer_masking;
12825 // Determine if we are introspecting the result of performSelectorXXX.
12826 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12827 // Special case messages to -performSelector and friends, which
12828 // can return non-pointer values boxed in a pointer value.
12829 // Some clients may wish to silence warnings in this subcase.
12830 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12831 Selector S = ME->getSelector();
12832 StringRef SelArg0 = S.getNameForSlot(0);
12833 if (SelArg0.startswith("performSelector"))
12834 Diag = diag::warn_objc_pointer_masking_performSelector;
12835 }
12836
12837 S.Diag(OpLoc, Diag)
12838 << ObjCPointerExpr->getSourceRange();
12839 }
12840}
12841
12842static NamedDecl *getDeclFromExpr(Expr *E) {
12843 if (!E)
12844 return nullptr;
12845 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12846 return DRE->getDecl();
12847 if (auto *ME = dyn_cast<MemberExpr>(E))
12848 return ME->getMemberDecl();
12849 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12850 return IRE->getDecl();
12851 return nullptr;
12852}
12853
12854// This helper function promotes a binary operator's operands (which are of a
12855// half vector type) to a vector of floats and then truncates the result to
12856// a vector of either half or short.
12857static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12858 BinaryOperatorKind Opc, QualType ResultTy,
12859 ExprValueKind VK, ExprObjectKind OK,
12860 bool IsCompAssign, SourceLocation OpLoc,
12861 FPOptions FPFeatures) {
12862 auto &Context = S.getASTContext();
12863 assert((isVector(ResultTy, Context.HalfTy) ||(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context
.ShortTy)) && "Result must be a vector of half or short"
) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 12865, __PRETTY_FUNCTION__))
12864 isVector(ResultTy, Context.ShortTy)) &&(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context
.ShortTy)) && "Result must be a vector of half or short"
) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 12865, __PRETTY_FUNCTION__))
12865 "Result must be a vector of half or short")(((isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context
.ShortTy)) && "Result must be a vector of half or short"
) ? static_cast<void> (0) : __assert_fail ("(isVector(ResultTy, Context.HalfTy) || isVector(ResultTy, Context.ShortTy)) && \"Result must be a vector of half or short\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 12865, __PRETTY_FUNCTION__))
;
12866 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&((isVector(LHS.get()->getType(), Context.HalfTy) &&
isVector(RHS.get()->getType(), Context.HalfTy) &&
"both operands expected to be a half vector") ? static_cast<
void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 12868, __PRETTY_FUNCTION__))
12867 isVector(RHS.get()->getType(), Context.HalfTy) &&((isVector(LHS.get()->getType(), Context.HalfTy) &&
isVector(RHS.get()->getType(), Context.HalfTy) &&
"both operands expected to be a half vector") ? static_cast<
void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 12868, __PRETTY_FUNCTION__))
12868 "both operands expected to be a half vector")((isVector(LHS.get()->getType(), Context.HalfTy) &&
isVector(RHS.get()->getType(), Context.HalfTy) &&
"both operands expected to be a half vector") ? static_cast<
void> (0) : __assert_fail ("isVector(LHS.get()->getType(), Context.HalfTy) && isVector(RHS.get()->getType(), Context.HalfTy) && \"both operands expected to be a half vector\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 12868, __PRETTY_FUNCTION__))
;
12869
12870 RHS = convertVector(RHS.get(), Context.FloatTy, S);
12871 QualType BinOpResTy = RHS.get()->getType();
12872
12873 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12874 // change BinOpResTy to a vector of ints.
12875 if (isVector(ResultTy, Context.ShortTy))
12876 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12877
12878 if (IsCompAssign)
12879 return new (Context) CompoundAssignOperator(
12880 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12881 OpLoc, FPFeatures);
12882
12883 LHS = convertVector(LHS.get(), Context.FloatTy, S);
12884 auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12885 VK, OK, OpLoc, FPFeatures);
12886 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
12887}
12888
12889static std::pair<ExprResult, ExprResult>
12890CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12891 Expr *RHSExpr) {
12892 ExprResult LHS = LHSExpr, RHS = RHSExpr;
12893 if (!S.getLangOpts().CPlusPlus) {
12894 // C cannot handle TypoExpr nodes on either side of a binop because it
12895 // doesn't handle dependent types properly, so make sure any TypoExprs have
12896 // been dealt with before checking the operands.
12897 LHS = S.CorrectDelayedTyposInExpr(LHS);
12898 RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12899 if (Opc != BO_Assign)
12900 return ExprResult(E);
12901 // Avoid correcting the RHS to the same Expr as the LHS.
12902 Decl *D = getDeclFromExpr(E);
12903 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12904 });
12905 }
12906 return std::make_pair(LHS, RHS);
12907}
12908
12909/// Returns true if conversion between vectors of halfs and vectors of floats
12910/// is needed.
12911static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12912 QualType SrcType) {
12913 return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12914 !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12915 isVector(SrcType, Ctx.HalfTy);
12916}
12917
12918/// CreateBuiltinBinOp - Creates a new built-in binary operation with
12919/// operator @p Opc at location @c TokLoc. This routine only supports
12920/// built-in operations; ActOnBinOp handles overloaded operators.
12921ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12922 BinaryOperatorKind Opc,
12923 Expr *LHSExpr, Expr *RHSExpr) {
12924 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12925 // The syntax only allows initializer lists on the RHS of assignment,
12926 // so we don't need to worry about accepting invalid code for
12927 // non-assignment operators.
12928 // C++11 5.17p9:
12929 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12930 // of x = {} is x = T().
12931 InitializationKind Kind = InitializationKind::CreateDirectList(
12932 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12933 InitializedEntity Entity =
12934 InitializedEntity::InitializeTemporary(LHSExpr->getType());
12935 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12936 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12937 if (Init.isInvalid())
12938 return Init;
12939 RHSExpr = Init.get();
12940 }
12941
12942 ExprResult LHS = LHSExpr, RHS = RHSExpr;
12943 QualType ResultTy; // Result type of the binary operator.
12944 // The following two variables are used for compound assignment operators
12945 QualType CompLHSTy; // Type of LHS after promotions for computation
12946 QualType CompResultTy; // Type of computation result
12947 ExprValueKind VK = VK_RValue;
12948 ExprObjectKind OK = OK_Ordinary;
12949 bool ConvertHalfVec = false;
12950
12951 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12952 if (!LHS.isUsable() || !RHS.isUsable())
12953 return ExprError();
12954
12955 if (getLangOpts().OpenCL) {
12956 QualType LHSTy = LHSExpr->getType();
12957 QualType RHSTy = RHSExpr->getType();
12958 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12959 // the ATOMIC_VAR_INIT macro.
12960 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12961 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12962 if (BO_Assign == Opc)
12963 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12964 else
12965 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12966 return ExprError();
12967 }
12968
12969 // OpenCL special types - image, sampler, pipe, and blocks are to be used
12970 // only with a builtin functions and therefore should be disallowed here.
12971 if (LHSTy->isImageType() || RHSTy->isImageType() ||
12972 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12973 LHSTy->isPipeType() || RHSTy->isPipeType() ||
12974 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12975 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12976 return ExprError();
12977 }
12978 }
12979
12980 // Diagnose operations on the unsupported types for OpenMP device compilation.
12981 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12982 if (Opc != BO_Assign && Opc != BO_Comma) {
12983 checkOpenMPDeviceExpr(LHSExpr);
12984 checkOpenMPDeviceExpr(RHSExpr);
12985 }
12986 }
12987
12988 switch (Opc) {
12989 case BO_Assign:
12990 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12991 if (getLangOpts().CPlusPlus &&
12992 LHS.get()->getObjectKind() != OK_ObjCProperty) {
12993 VK = LHS.get()->getValueKind();
12994 OK = LHS.get()->getObjectKind();
12995 }
12996 if (!ResultTy.isNull()) {
12997 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12998 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12999
13000 // Avoid copying a block to the heap if the block is assigned to a local
13001 // auto variable that is declared in the same scope as the block. This
13002 // optimization is unsafe if the local variable is declared in an outer
13003 // scope. For example:
13004 //
13005 // BlockTy b;
13006 // {
13007 // b = ^{...};
13008 // }
13009 // // It is unsafe to invoke the block here if it wasn't copied to the
13010 // // heap.
13011 // b();
13012
13013 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13014 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13015 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13016 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13017 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13018
13019 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13020 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13021 NTCUC_Assignment, NTCUK_Copy);
13022 }
13023 RecordModifiableNonNullParam(*this, LHS.get());
13024 break;
13025 case BO_PtrMemD:
13026 case BO_PtrMemI:
13027 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13028 Opc == BO_PtrMemI);
13029 break;
13030 case BO_Mul:
13031 case BO_Div:
13032 ConvertHalfVec = true;
13033 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13034 Opc == BO_Div);
13035 break;
13036 case BO_Rem:
13037 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13038 break;
13039 case BO_Add:
13040 ConvertHalfVec = true;
13041 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13042 break;
13043 case BO_Sub:
13044 ConvertHalfVec = true;
13045 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13046 break;
13047 case BO_Shl:
13048 case BO_Shr:
13049 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13050 break;
13051 case BO_LE:
13052 case BO_LT:
13053 case BO_GE:
13054 case BO_GT:
13055 ConvertHalfVec = true;
13056 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13057 break;
13058 case BO_EQ:
13059 case BO_NE:
13060 ConvertHalfVec = true;
13061 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13062 break;
13063 case BO_Cmp:
13064 ConvertHalfVec = true;
13065 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13066 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl())((ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()) ? static_cast
<void> (0) : __assert_fail ("ResultTy.isNull() || ResultTy->getAsCXXRecordDecl()"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 13066, __PRETTY_FUNCTION__))
;
13067 break;
13068 case BO_And:
13069 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13070 LLVM_FALLTHROUGH[[gnu::fallthrough]];
13071 case BO_Xor:
13072 case BO_Or:
13073 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13074 break;
13075 case BO_LAnd:
13076 case BO_LOr:
13077 ConvertHalfVec = true;
13078 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13079 break;
13080 case BO_MulAssign:
13081 case BO_DivAssign:
13082 ConvertHalfVec = true;
13083 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13084 Opc == BO_DivAssign);
13085 CompLHSTy = CompResultTy;
13086 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13087 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13088 break;
13089 case BO_RemAssign:
13090 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13091 CompLHSTy = CompResultTy;
13092 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13093 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13094 break;
13095 case BO_AddAssign:
13096 ConvertHalfVec = true;
13097 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
13098 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13099 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13100 break;
13101 case BO_SubAssign:
13102 ConvertHalfVec = true;
13103 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
13104 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13105 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13106 break;
13107 case BO_ShlAssign:
13108 case BO_ShrAssign:
13109 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
13110 CompLHSTy = CompResultTy;
13111 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13112 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13113 break;
13114 case BO_AndAssign:
13115 case BO_OrAssign: // fallthrough
13116 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13117 LLVM_FALLTHROUGH[[gnu::fallthrough]];
13118 case BO_XorAssign:
13119 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13120 CompLHSTy = CompResultTy;
13121 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13122 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13123 break;
13124 case BO_Comma:
13125 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
13126 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
13127 VK = RHS.get()->getValueKind();
13128 OK = RHS.get()->getObjectKind();
13129 }
13130 break;
13131 }
13132 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
13133 return ExprError();
13134
13135 if (ResultTy->isRealFloatingType() &&
13136 (getLangOpts().getFPRoundingMode() != LangOptions::FPR_ToNearest ||
13137 getLangOpts().getFPExceptionMode() != LangOptions::FPE_Ignore))
13138 // Mark the current function as usng floating point constrained intrinsics
13139 if (FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13140 F->setUsesFPIntrin(true);
13141 }
13142
13143 // Some of the binary operations require promoting operands of half vector to
13144 // float vectors and truncating the result back to half vector. For now, we do
13145 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
13146 // arm64).
13147 assert(isVector(RHS.get()->getType(), Context.HalfTy) ==((isVector(RHS.get()->getType(), Context.HalfTy) == isVector
(LHS.get()->getType(), Context.HalfTy) && "both sides are half vectors or neither sides are"
) ? static_cast<void> (0) : __assert_fail ("isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) && \"both sides are half vectors or neither sides are\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 13149, __PRETTY_FUNCTION__))
13148 isVector(LHS.get()->getType(), Context.HalfTy) &&((isVector(RHS.get()->getType(), Context.HalfTy) == isVector
(LHS.get()->getType(), Context.HalfTy) && "both sides are half vectors or neither sides are"
) ? static_cast<void> (0) : __assert_fail ("isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) && \"both sides are half vectors or neither sides are\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 13149, __PRETTY_FUNCTION__))
13149 "both sides are half vectors or neither sides are")((isVector(RHS.get()->getType(), Context.HalfTy) == isVector
(LHS.get()->getType(), Context.HalfTy) && "both sides are half vectors or neither sides are"
) ? static_cast<void> (0) : __assert_fail ("isVector(RHS.get()->getType(), Context.HalfTy) == isVector(LHS.get()->getType(), Context.HalfTy) && \"both sides are half vectors or neither sides are\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 13149, __PRETTY_FUNCTION__))
;
13150 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
13151 LHS.get()->getType());
13152
13153 // Check for array bounds violations for both sides of the BinaryOperator
13154 CheckArrayAccess(LHS.get());
13155 CheckArrayAccess(RHS.get());
13156
13157 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
13158 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
13159 &Context.Idents.get("object_setClass"),
13160 SourceLocation(), LookupOrdinaryName);
13161 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
13162 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
13163 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
13164 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
13165 "object_setClass(")
13166 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
13167 ",")
13168 << FixItHint::CreateInsertion(RHSLocEnd, ")");
13169 }
13170 else
13171 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
13172 }
13173 else if (const ObjCIvarRefExpr *OIRE =
13174 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
13175 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
13176
13177 // Opc is not a compound assignment if CompResultTy is null.
13178 if (CompResultTy.isNull()) {
13179 if (ConvertHalfVec)
13180 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
13181 OpLoc, FPFeatures);
13182 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
13183 OK, OpLoc, FPFeatures);
13184 }
13185
13186 // Handle compound assignments.
13187 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
13188 OK_ObjCProperty) {
13189 VK = VK_LValue;
13190 OK = LHS.get()->getObjectKind();
13191 }
13192
13193 if (ConvertHalfVec)
13194 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
13195 OpLoc, FPFeatures);
13196
13197 return new (Context) CompoundAssignOperator(
13198 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
13199 OpLoc, FPFeatures);
13200}
13201
13202/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
13203/// operators are mixed in a way that suggests that the programmer forgot that
13204/// comparison operators have higher precedence. The most typical example of
13205/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
13206static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
13207 SourceLocation OpLoc, Expr *LHSExpr,
13208 Expr *RHSExpr) {
13209 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
13210 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
13211
13212 // Check that one of the sides is a comparison operator and the other isn't.
13213 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
13214 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
13215 if (isLeftComp == isRightComp)
13216 return;
13217
13218 // Bitwise operations are sometimes used as eager logical ops.
13219 // Don't diagnose this.
13220 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
13221 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
13222 if (isLeftBitwise || isRightBitwise)
13223 return;
13224
13225 SourceRange DiagRange = isLeftComp
13226 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
13227 : SourceRange(OpLoc, RHSExpr->getEndLoc());
13228 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
13229 SourceRange ParensRange =
13230 isLeftComp
13231 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
13232 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
13233
13234 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
13235 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
13236 SuggestParentheses(Self, OpLoc,
13237 Self.PDiag(diag::note_precedence_silence) << OpStr,
13238 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
13239 SuggestParentheses(Self, OpLoc,
13240 Self.PDiag(diag::note_precedence_bitwise_first)
13241 << BinaryOperator::getOpcodeStr(Opc),
13242 ParensRange);
13243}
13244
13245/// It accepts a '&&' expr that is inside a '||' one.
13246/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
13247/// in parentheses.
13248static void
13249EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
13250 BinaryOperator *Bop) {
13251 assert(Bop->getOpcode() == BO_LAnd)((Bop->getOpcode() == BO_LAnd) ? static_cast<void> (
0) : __assert_fail ("Bop->getOpcode() == BO_LAnd", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 13251, __PRETTY_FUNCTION__))
;
13252 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
13253 << Bop->getSourceRange() << OpLoc;
13254 SuggestParentheses(Self, Bop->getOperatorLoc(),
13255 Self.PDiag(diag::note_precedence_silence)
13256 << Bop->getOpcodeStr(),
13257 Bop->getSourceRange());
13258}
13259
13260/// Returns true if the given expression can be evaluated as a constant
13261/// 'true'.
13262static bool EvaluatesAsTrue(Sema &S, Expr *E) {
13263 bool Res;
13264 return !E->isValueDependent() &&
13265 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
13266}
13267
13268/// Returns true if the given expression can be evaluated as a constant
13269/// 'false'.
13270static bool EvaluatesAsFalse(Sema &S, Expr *E) {
13271 bool Res;
13272 return !E->isValueDependent() &&
13273 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
13274}
13275
13276/// Look for '&&' in the left hand of a '||' expr.
13277static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
13278 Expr *LHSExpr, Expr *RHSExpr) {
13279 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
13280 if (Bop->getOpcode() == BO_LAnd) {
13281 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
13282 if (EvaluatesAsFalse(S, RHSExpr))
13283 return;
13284 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
13285 if (!EvaluatesAsTrue(S, Bop->getLHS()))
13286 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13287 } else if (Bop->getOpcode() == BO_LOr) {
13288 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
13289 // If it's "a || b && 1 || c" we didn't warn earlier for
13290 // "a || b && 1", but warn now.
13291 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
13292 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
13293 }
13294 }
13295 }
13296}
13297
13298/// Look for '&&' in the right hand of a '||' expr.
13299static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
13300 Expr *LHSExpr, Expr *RHSExpr) {
13301 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
13302 if (Bop->getOpcode() == BO_LAnd) {
13303 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
13304 if (EvaluatesAsFalse(S, LHSExpr))
13305 return;
13306 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
13307 if (!EvaluatesAsTrue(S, Bop->getRHS()))
13308 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
13309 }
13310 }
13311}
13312
13313/// Look for bitwise op in the left or right hand of a bitwise op with
13314/// lower precedence and emit a diagnostic together with a fixit hint that wraps
13315/// the '&' expression in parentheses.
13316static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
13317 SourceLocation OpLoc, Expr *SubExpr) {
13318 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13319 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
13320 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
13321 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
13322 << Bop->getSourceRange() << OpLoc;
13323 SuggestParentheses(S, Bop->getOperatorLoc(),
13324 S.PDiag(diag::note_precedence_silence)
13325 << Bop->getOpcodeStr(),
13326 Bop->getSourceRange());
13327 }
13328 }
13329}
13330
13331static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
13332 Expr *SubExpr, StringRef Shift) {
13333 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
13334 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
13335 StringRef Op = Bop->getOpcodeStr();
13336 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
13337 << Bop->getSourceRange() << OpLoc << Shift << Op;
13338 SuggestParentheses(S, Bop->getOperatorLoc(),
13339 S.PDiag(diag::note_precedence_silence) << Op,
13340 Bop->getSourceRange());
13341 }
13342 }
13343}
13344
13345static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
13346 Expr *LHSExpr, Expr *RHSExpr) {
13347 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
13348 if (!OCE)
13349 return;
13350
13351 FunctionDecl *FD = OCE->getDirectCallee();
13352 if (!FD || !FD->isOverloadedOperator())
13353 return;
13354
13355 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
13356 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
13357 return;
13358
13359 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
13360 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
13361 << (Kind == OO_LessLess);
13362 SuggestParentheses(S, OCE->getOperatorLoc(),
13363 S.PDiag(diag::note_precedence_silence)
13364 << (Kind == OO_LessLess ? "<<" : ">>"),
13365 OCE->getSourceRange());
13366 SuggestParentheses(
13367 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
13368 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
13369}
13370
13371/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
13372/// precedence.
13373static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
13374 SourceLocation OpLoc, Expr *LHSExpr,
13375 Expr *RHSExpr){
13376 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
13377 if (BinaryOperator::isBitwiseOp(Opc))
13378 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
13379
13380 // Diagnose "arg1 & arg2 | arg3"
13381 if ((Opc == BO_Or || Opc == BO_Xor) &&
13382 !OpLoc.isMacroID()/* Don't warn in macros. */) {
13383 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
13384 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
13385 }
13386
13387 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
13388 // We don't warn for 'assert(a || b && "bad")' since this is safe.
13389 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
13390 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
13391 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
13392 }
13393
13394 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
13395 || Opc == BO_Shr) {
13396 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
13397 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
13398 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
13399 }
13400
13401 // Warn on overloaded shift operators and comparisons, such as:
13402 // cout << 5 == 4;
13403 if (BinaryOperator::isComparisonOp(Opc))
13404 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
13405}
13406
13407// Binary Operators. 'Tok' is the token for the operator.
13408ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
13409 tok::TokenKind Kind,
13410 Expr *LHSExpr, Expr *RHSExpr) {
13411 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
13412 assert(LHSExpr && "ActOnBinOp(): missing left expression")((LHSExpr && "ActOnBinOp(): missing left expression")
? static_cast<void> (0) : __assert_fail ("LHSExpr && \"ActOnBinOp(): missing left expression\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 13412, __PRETTY_FUNCTION__))
;
13413 assert(RHSExpr && "ActOnBinOp(): missing right expression")((RHSExpr && "ActOnBinOp(): missing right expression"
) ? static_cast<void> (0) : __assert_fail ("RHSExpr && \"ActOnBinOp(): missing right expression\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 13413, __PRETTY_FUNCTION__))
;
13414
13415 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
13416 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
13417
13418 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
13419}
13420
13421/// Build an overloaded binary operator expression in the given scope.
13422static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
13423 BinaryOperatorKind Opc,
13424 Expr *LHS, Expr *RHS) {
13425 switch (Opc) {
13426 case BO_Assign:
13427 case BO_DivAssign:
13428 case BO_RemAssign:
13429 case BO_SubAssign:
13430 case BO_AndAssign:
13431 case BO_OrAssign:
13432 case BO_XorAssign:
13433 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
13434 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
13435 break;
13436 default:
13437 break;
13438 }
13439
13440 // Find all of the overloaded operators visible from this
13441 // point. We perform both an operator-name lookup from the local
13442 // scope and an argument-dependent lookup based on the types of
13443 // the arguments.
13444 UnresolvedSet<16> Functions;
13445 OverloadedOperatorKind OverOp
13446 = BinaryOperator::getOverloadedOperator(Opc);
13447 if (Sc && OverOp != OO_None && OverOp != OO_Equal)
13448 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
13449 RHS->getType(), Functions);
13450
13451 // In C++20 onwards, we may have a second operator to look up.
13452 if (S.getLangOpts().CPlusPlus2a) {
13453 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
13454 S.LookupOverloadedOperatorName(ExtraOp, Sc, LHS->getType(),
13455 RHS->getType(), Functions);
13456 }
13457
13458 // Build the (potentially-overloaded, potentially-dependent)
13459 // binary operation.
13460 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
13461}
13462
13463ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
13464 BinaryOperatorKind Opc,
13465 Expr *LHSExpr, Expr *RHSExpr) {
13466 ExprResult LHS, RHS;
13467 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13468 if (!LHS.isUsable() || !RHS.isUsable())
13469 return ExprError();
13470 LHSExpr = LHS.get();
13471 RHSExpr = RHS.get();
13472
13473 // We want to end up calling one of checkPseudoObjectAssignment
13474 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
13475 // both expressions are overloadable or either is type-dependent),
13476 // or CreateBuiltinBinOp (in any other case). We also want to get
13477 // any placeholder types out of the way.
13478
13479 // Handle pseudo-objects in the LHS.
13480 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
13481 // Assignments with a pseudo-object l-value need special analysis.
13482 if (pty->getKind() == BuiltinType::PseudoObject &&
13483 BinaryOperator::isAssignmentOp(Opc))
13484 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
13485
13486 // Don't resolve overloads if the other type is overloadable.
13487 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
13488 // We can't actually test that if we still have a placeholder,
13489 // though. Fortunately, none of the exceptions we see in that
13490 // code below are valid when the LHS is an overload set. Note
13491 // that an overload set can be dependently-typed, but it never
13492 // instantiates to having an overloadable type.
13493 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13494 if (resolvedRHS.isInvalid()) return ExprError();
13495 RHSExpr = resolvedRHS.get();
13496
13497 if (RHSExpr->isTypeDependent() ||
13498 RHSExpr->getType()->isOverloadableType())
13499 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13500 }
13501
13502 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
13503 // template, diagnose the missing 'template' keyword instead of diagnosing
13504 // an invalid use of a bound member function.
13505 //
13506 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
13507 // to C++1z [over.over]/1.4, but we already checked for that case above.
13508 if (Opc == BO_LT && inTemplateInstantiation() &&
13509 (pty->getKind() == BuiltinType::BoundMember ||
13510 pty->getKind() == BuiltinType::Overload)) {
13511 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
13512 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
13513 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
13514 return isa<FunctionTemplateDecl>(ND);
13515 })) {
13516 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
13517 : OE->getNameLoc(),
13518 diag::err_template_kw_missing)
13519 << OE->getName().getAsString() << "";
13520 return ExprError();
13521 }
13522 }
13523
13524 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
13525 if (LHS.isInvalid()) return ExprError();
13526 LHSExpr = LHS.get();
13527 }
13528
13529 // Handle pseudo-objects in the RHS.
13530 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
13531 // An overload in the RHS can potentially be resolved by the type
13532 // being assigned to.
13533 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
13534 if (getLangOpts().CPlusPlus &&
13535 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
13536 LHSExpr->getType()->isOverloadableType()))
13537 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13538
13539 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13540 }
13541
13542 // Don't resolve overloads if the other type is overloadable.
13543 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
13544 LHSExpr->getType()->isOverloadableType())
13545 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13546
13547 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
13548 if (!resolvedRHS.isUsable()) return ExprError();
13549 RHSExpr = resolvedRHS.get();
13550 }
13551
13552 if (getLangOpts().CPlusPlus) {
13553 // If either expression is type-dependent, always build an
13554 // overloaded op.
13555 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
13556 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13557
13558 // Otherwise, build an overloaded op if either expression has an
13559 // overloadable type.
13560 if (LHSExpr->getType()->isOverloadableType() ||
13561 RHSExpr->getType()->isOverloadableType())
13562 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13563 }
13564
13565 // Build a built-in binary operation.
13566 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13567}
13568
13569static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13570 if (T.isNull() || T->isDependentType())
13571 return false;
13572
13573 if (!T->isPromotableIntegerType())
13574 return true;
13575
13576 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13577}
13578
13579ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13580 UnaryOperatorKind Opc,
13581 Expr *InputExpr) {
13582 ExprResult Input = InputExpr;
13583 ExprValueKind VK = VK_RValue;
13584 ExprObjectKind OK = OK_Ordinary;
13585 QualType resultType;
13586 bool CanOverflow = false;
13587
13588 bool ConvertHalfVec = false;
13589 if (getLangOpts().OpenCL) {
13590 QualType Ty = InputExpr->getType();
13591 // The only legal unary operation for atomics is '&'.
13592 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13593 // OpenCL special types - image, sampler, pipe, and blocks are to be used
13594 // only with a builtin functions and therefore should be disallowed here.
13595 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13596 || Ty->isBlockPointerType())) {
13597 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13598 << InputExpr->getType()
13599 << Input.get()->getSourceRange());
13600 }
13601 }
13602 // Diagnose operations on the unsupported types for OpenMP device compilation.
13603 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13604 if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13605 UnaryOperator::isArithmeticOp(Opc))
13606 checkOpenMPDeviceExpr(InputExpr);
13607 }
13608
13609 switch (Opc) {
13610 case UO_PreInc:
13611 case UO_PreDec:
13612 case UO_PostInc:
13613 case UO_PostDec:
13614 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13615 OpLoc,
13616 Opc == UO_PreInc ||
13617 Opc == UO_PostInc,
13618 Opc == UO_PreInc ||
13619 Opc == UO_PreDec);
13620 CanOverflow = isOverflowingIntegerType(Context, resultType);
13621 break;
13622 case UO_AddrOf:
13623 resultType = CheckAddressOfOperand(Input, OpLoc);
13624 CheckAddressOfNoDeref(InputExpr);
13625 RecordModifiableNonNullParam(*this, InputExpr);
13626 break;
13627 case UO_Deref: {
13628 Input = DefaultFunctionArrayLvalueConversion(Input.get());
13629 if (Input.isInvalid()) return ExprError();
13630 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13631 break;
13632 }
13633 case UO_Plus:
13634 case UO_Minus:
13635 CanOverflow = Opc == UO_Minus &&
13636 isOverflowingIntegerType(Context, Input.get()->getType());
13637 Input = UsualUnaryConversions(Input.get());
13638 if (Input.isInvalid()) return ExprError();
13639 // Unary plus and minus require promoting an operand of half vector to a
13640 // float vector and truncating the result back to a half vector. For now, we
13641 // do this only when HalfArgsAndReturns is set (that is, when the target is
13642 // arm or arm64).
13643 ConvertHalfVec =
13644 needsConversionOfHalfVec(true, Context, Input.get()->getType());
13645
13646 // If the operand is a half vector, promote it to a float vector.
13647 if (ConvertHalfVec)
13648 Input = convertVector(Input.get(), Context.FloatTy, *this);
13649 resultType = Input.get()->getType();
13650 if (resultType->isDependentType())
13651 break;
13652 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13653 break;
13654 else if (resultType->isVectorType() &&
13655 // The z vector extensions don't allow + or - with bool vectors.
13656 (!Context.getLangOpts().ZVector ||
13657 resultType->castAs<VectorType>()->getVectorKind() !=
13658 VectorType::AltiVecBool))
13659 break;
13660 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13661 Opc == UO_Plus &&
13662 resultType->isPointerType())
13663 break;
13664
13665 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13666 << resultType << Input.get()->getSourceRange());
13667
13668 case UO_Not: // bitwise complement
13669 Input = UsualUnaryConversions(Input.get());
13670 if (Input.isInvalid())
13671 return ExprError();
13672 resultType = Input.get()->getType();
13673 if (resultType->isDependentType())
13674 break;
13675 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13676 if (resultType->isComplexType() || resultType->isComplexIntegerType())
13677 // C99 does not support '~' for complex conjugation.
13678 Diag(OpLoc, diag::ext_integer_complement_complex)
13679 << resultType << Input.get()->getSourceRange();
13680 else if (resultType->hasIntegerRepresentation())
13681 break;
13682 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13683 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13684 // on vector float types.
13685 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13686 if (!T->isIntegerType())
13687 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13688 << resultType << Input.get()->getSourceRange());
13689 } else {
13690 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13691 << resultType << Input.get()->getSourceRange());
13692 }
13693 break;
13694
13695 case UO_LNot: // logical negation
13696 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13697 Input = DefaultFunctionArrayLvalueConversion(Input.get());
13698 if (Input.isInvalid()) return ExprError();
13699 resultType = Input.get()->getType();
13700
13701 // Though we still have to promote half FP to float...
13702 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13703 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13704 resultType = Context.FloatTy;
13705 }
13706
13707 if (resultType->isDependentType())
13708 break;
13709 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13710 // C99 6.5.3.3p1: ok, fallthrough;
13711 if (Context.getLangOpts().CPlusPlus) {
13712 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13713 // operand contextually converted to bool.
13714 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13715 ScalarTypeToBooleanCastKind(resultType));
13716 } else if (Context.getLangOpts().OpenCL &&
13717 Context.getLangOpts().OpenCLVersion < 120) {
13718 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13719 // operate on scalar float types.
13720 if (!resultType->isIntegerType() && !resultType->isPointerType())
13721 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13722 << resultType << Input.get()->getSourceRange());
13723 }
13724 } else if (resultType->isExtVectorType()) {
13725 if (Context.getLangOpts().OpenCL &&
13726 Context.getLangOpts().OpenCLVersion < 120 &&
13727 !Context.getLangOpts().OpenCLCPlusPlus) {
13728 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13729 // operate on vector float types.
13730 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
13731 if (!T->isIntegerType())
13732 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13733 << resultType << Input.get()->getSourceRange());
13734 }
13735 // Vector logical not returns the signed variant of the operand type.
13736 resultType = GetSignedVectorType(resultType);
13737 break;
13738 } else {
13739 // FIXME: GCC's vector extension permits the usage of '!' with a vector
13740 // type in C++. We should allow that here too.
13741 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13742 << resultType << Input.get()->getSourceRange());
13743 }
13744
13745 // LNot always has type int. C99 6.5.3.3p5.
13746 // In C++, it's bool. C++ 5.3.1p8
13747 resultType = Context.getLogicalOperationType();
13748 break;
13749 case UO_Real:
13750 case UO_Imag:
13751 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13752 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13753 // complex l-values to ordinary l-values and all other values to r-values.
13754 if (Input.isInvalid()) return ExprError();
13755 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13756 if (Input.get()->getValueKind() != VK_RValue &&
13757 Input.get()->getObjectKind() == OK_Ordinary)
13758 VK = Input.get()->getValueKind();
13759 } else if (!getLangOpts().CPlusPlus) {
13760 // In C, a volatile scalar is read by __imag. In C++, it is not.
13761 Input = DefaultLvalueConversion(Input.get());
13762 }
13763 break;
13764 case UO_Extension:
13765 resultType = Input.get()->getType();
13766 VK = Input.get()->getValueKind();
13767 OK = Input.get()->getObjectKind();
13768 break;
13769 case UO_Coawait:
13770 // It's unnecessary to represent the pass-through operator co_await in the
13771 // AST; just return the input expression instead.
13772 assert(!Input.get()->getType()->isDependentType() &&((!Input.get()->getType()->isDependentType() &&
"the co_await expression must be non-dependant before " "building operator co_await"
) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 13774, __PRETTY_FUNCTION__))
13773 "the co_await expression must be non-dependant before "((!Input.get()->getType()->isDependentType() &&
"the co_await expression must be non-dependant before " "building operator co_await"
) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 13774, __PRETTY_FUNCTION__))
13774 "building operator co_await")((!Input.get()->getType()->isDependentType() &&
"the co_await expression must be non-dependant before " "building operator co_await"
) ? static_cast<void> (0) : __assert_fail ("!Input.get()->getType()->isDependentType() && \"the co_await expression must be non-dependant before \" \"building operator co_await\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 13774, __PRETTY_FUNCTION__))
;
13775 return Input;
13776 }
13777 if (resultType.isNull() || Input.isInvalid())
13778 return ExprError();
13779
13780 // Check for array bounds violations in the operand of the UnaryOperator,
13781 // except for the '*' and '&' operators that have to be handled specially
13782 // by CheckArrayAccess (as there are special cases like &array[arraysize]
13783 // that are explicitly defined as valid by the standard).
13784 if (Opc != UO_AddrOf && Opc != UO_Deref)
13785 CheckArrayAccess(Input.get());
13786
13787 auto *UO = new (Context)
13788 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13789
13790 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13791 !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13792 ExprEvalContexts.back().PossibleDerefs.insert(UO);
13793
13794 // Convert the result back to a half vector.
13795 if (ConvertHalfVec)
13796 return convertVector(UO, Context.HalfTy, *this);
13797 return UO;
13798}
13799
13800/// Determine whether the given expression is a qualified member
13801/// access expression, of a form that could be turned into a pointer to member
13802/// with the address-of operator.
13803bool Sema::isQualifiedMemberAccess(Expr *E) {
13804 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13805 if (!DRE->getQualifier())
13806 return false;
13807
13808 ValueDecl *VD = DRE->getDecl();
13809 if (!VD->isCXXClassMember())
13810 return false;
13811
13812 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13813 return true;
13814 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13815 return Method->isInstance();
13816
13817 return false;
13818 }
13819
13820 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13821 if (!ULE->getQualifier())
13822 return false;
13823
13824 for (NamedDecl *D : ULE->decls()) {
13825 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13826 if (Method->isInstance())
13827 return true;
13828 } else {
13829 // Overload set does not contain methods.
13830 break;
13831 }
13832 }
13833
13834 return false;
13835 }
13836
13837 return false;
13838}
13839
13840ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13841 UnaryOperatorKind Opc, Expr *Input) {
13842 // First things first: handle placeholders so that the
13843 // overloaded-operator check considers the right type.
13844 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13845 // Increment and decrement of pseudo-object references.
13846 if (pty->getKind() == BuiltinType::PseudoObject &&
13847 UnaryOperator::isIncrementDecrementOp(Opc))
13848 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13849
13850 // extension is always a builtin operator.
13851 if (Opc == UO_Extension)
13852 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13853
13854 // & gets special logic for several kinds of placeholder.
13855 // The builtin code knows what to do.
13856 if (Opc == UO_AddrOf &&
13857 (pty->getKind() == BuiltinType::Overload ||
13858 pty->getKind() == BuiltinType::UnknownAny ||
13859 pty->getKind() == BuiltinType::BoundMember))
13860 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13861
13862 // Anything else needs to be handled now.
13863 ExprResult Result = CheckPlaceholderExpr(Input);
13864 if (Result.isInvalid()) return ExprError();
13865 Input = Result.get();
13866 }
13867
13868 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13869 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13870 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13871 // Find all of the overloaded operators visible from this
13872 // point. We perform both an operator-name lookup from the local
13873 // scope and an argument-dependent lookup based on the types of
13874 // the arguments.
13875 UnresolvedSet<16> Functions;
13876 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13877 if (S && OverOp != OO_None)
13878 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13879 Functions);
13880
13881 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13882 }
13883
13884 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13885}
13886
13887// Unary Operators. 'Tok' is the token for the operator.
13888ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13889 tok::TokenKind Op, Expr *Input) {
13890 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13891}
13892
13893/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13894ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13895 LabelDecl *TheDecl) {
13896 TheDecl->markUsed(Context);
13897 // Create the AST node. The address of a label always has type 'void*'.
13898 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13899 Context.getPointerType(Context.VoidTy));
13900}
13901
13902void Sema::ActOnStartStmtExpr() {
13903 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13904}
13905
13906void Sema::ActOnStmtExprError() {
13907 // Note that function is also called by TreeTransform when leaving a
13908 // StmtExpr scope without rebuilding anything.
13909
13910 DiscardCleanupsInEvaluationContext();
13911 PopExpressionEvaluationContext();
13912}
13913
13914ExprResult
13915Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13916 SourceLocation RPLoc) { // "({..})"
13917 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!")((SubStmt && isa<CompoundStmt>(SubStmt) &&
"Invalid action invocation!") ? static_cast<void> (0) :
__assert_fail ("SubStmt && isa<CompoundStmt>(SubStmt) && \"Invalid action invocation!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 13917, __PRETTY_FUNCTION__))
;
13918 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13919
13920 if (hasAnyUnrecoverableErrorsInThisFunction())
13921 DiscardCleanupsInEvaluationContext();
13922 assert(!Cleanup.exprNeedsCleanups() &&((!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!"
) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 13923, __PRETTY_FUNCTION__))
13923 "cleanups within StmtExpr not correctly bound!")((!Cleanup.exprNeedsCleanups() && "cleanups within StmtExpr not correctly bound!"
) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within StmtExpr not correctly bound!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 13923, __PRETTY_FUNCTION__))
;
13924 PopExpressionEvaluationContext();
13925
13926 // FIXME: there are a variety of strange constraints to enforce here, for
13927 // example, it is not possible to goto into a stmt expression apparently.
13928 // More semantic analysis is needed.
13929
13930 // If there are sub-stmts in the compound stmt, take the type of the last one
13931 // as the type of the stmtexpr.
13932 QualType Ty = Context.VoidTy;
13933 bool StmtExprMayBindToTemp = false;
13934 if (!Compound->body_empty()) {
13935 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
13936 if (const auto *LastStmt =
13937 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
13938 if (const Expr *Value = LastStmt->getExprStmt()) {
13939 StmtExprMayBindToTemp = true;
13940 Ty = Value->getType();
13941 }
13942 }
13943 }
13944
13945 // FIXME: Check that expression type is complete/non-abstract; statement
13946 // expressions are not lvalues.
13947 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13948 if (StmtExprMayBindToTemp)
13949 return MaybeBindToTemporary(ResStmtExpr);
13950 return ResStmtExpr;
13951}
13952
13953ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13954 if (ER.isInvalid())
13955 return ExprError();
13956
13957 // Do function/array conversion on the last expression, but not
13958 // lvalue-to-rvalue. However, initialize an unqualified type.
13959 ER = DefaultFunctionArrayConversion(ER.get());
13960 if (ER.isInvalid())
13961 return ExprError();
13962 Expr *E = ER.get();
13963
13964 if (E->isTypeDependent())
13965 return E;
13966
13967 // In ARC, if the final expression ends in a consume, splice
13968 // the consume out and bind it later. In the alternate case
13969 // (when dealing with a retainable type), the result
13970 // initialization will create a produce. In both cases the
13971 // result will be +1, and we'll need to balance that out with
13972 // a bind.
13973 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13974 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13975 return Cast->getSubExpr();
13976
13977 // FIXME: Provide a better location for the initialization.
13978 return PerformCopyInitialization(
13979 InitializedEntity::InitializeStmtExprResult(
13980 E->getBeginLoc(), E->getType().getUnqualifiedType()),
13981 SourceLocation(), E);
13982}
13983
13984ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13985 TypeSourceInfo *TInfo,
13986 ArrayRef<OffsetOfComponent> Components,
13987 SourceLocation RParenLoc) {
13988 QualType ArgTy = TInfo->getType();
13989 bool Dependent = ArgTy->isDependentType();
13990 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13991
13992 // We must have at least one component that refers to the type, and the first
13993 // one is known to be a field designator. Verify that the ArgTy represents
13994 // a struct/union/class.
13995 if (!Dependent && !ArgTy->isRecordType())
13996 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13997 << ArgTy << TypeRange);
13998
13999 // Type must be complete per C99 7.17p3 because a declaring a variable
14000 // with an incomplete type would be ill-formed.
14001 if (!Dependent
14002 && RequireCompleteType(BuiltinLoc, ArgTy,
14003 diag::err_offsetof_incomplete_type, TypeRange))
14004 return ExprError();
14005
14006 bool DidWarnAboutNonPOD = false;
14007 QualType CurrentType = ArgTy;
14008 SmallVector<OffsetOfNode, 4> Comps;
14009 SmallVector<Expr*, 4> Exprs;
14010 for (const OffsetOfComponent &OC : Components) {
14011 if (OC.isBrackets) {
14012 // Offset of an array sub-field. TODO: Should we allow vector elements?
14013 if (!CurrentType->isDependentType()) {
14014 const ArrayType *AT = Context.getAsArrayType(CurrentType);
14015 if(!AT)
14016 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14017 << CurrentType);
14018 CurrentType = AT->getElementType();
14019 } else
14020 CurrentType = Context.DependentTy;
14021
14022 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14023 if (IdxRval.isInvalid())
14024 return ExprError();
14025 Expr *Idx = IdxRval.get();
14026
14027 // The expression must be an integral expression.
14028 // FIXME: An integral constant expression?
14029 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14030 !Idx->getType()->isIntegerType())
14031 return ExprError(
14032 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14033 << Idx->getSourceRange());
14034
14035 // Record this array index.
14036 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14037 Exprs.push_back(Idx);
14038 continue;
14039 }
14040
14041 // Offset of a field.
14042 if (CurrentType->isDependentType()) {
14043 // We have the offset of a field, but we can't look into the dependent
14044 // type. Just record the identifier of the field.
14045 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14046 CurrentType = Context.DependentTy;
14047 continue;
14048 }
14049
14050 // We need to have a complete type to look into.
14051 if (RequireCompleteType(OC.LocStart, CurrentType,
14052 diag::err_offsetof_incomplete_type))
14053 return ExprError();
14054
14055 // Look for the designated field.
14056 const RecordType *RC = CurrentType->getAs<RecordType>();
14057 if (!RC)
14058 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
14059 << CurrentType);
14060 RecordDecl *RD = RC->getDecl();
14061
14062 // C++ [lib.support.types]p5:
14063 // The macro offsetof accepts a restricted set of type arguments in this
14064 // International Standard. type shall be a POD structure or a POD union
14065 // (clause 9).
14066 // C++11 [support.types]p4:
14067 // If type is not a standard-layout class (Clause 9), the results are
14068 // undefined.
14069 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14070 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
14071 unsigned DiagID =
14072 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
14073 : diag::ext_offsetof_non_pod_type;
14074
14075 if (!IsSafe && !DidWarnAboutNonPOD &&
14076 DiagRuntimeBehavior(BuiltinLoc, nullptr,
14077 PDiag(DiagID)
14078 << SourceRange(Components[0].LocStart, OC.LocEnd)
14079 << CurrentType))
14080 DidWarnAboutNonPOD = true;
14081 }
14082
14083 // Look for the field.
14084 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
14085 LookupQualifiedName(R, RD);
14086 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
14087 IndirectFieldDecl *IndirectMemberDecl = nullptr;
14088 if (!MemberDecl) {
14089 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
14090 MemberDecl = IndirectMemberDecl->getAnonField();
14091 }
14092
14093 if (!MemberDecl)
14094 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
14095 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
14096 OC.LocEnd));
14097
14098 // C99 7.17p3:
14099 // (If the specified member is a bit-field, the behavior is undefined.)
14100 //
14101 // We diagnose this as an error.
14102 if (MemberDecl->isBitField()) {
14103 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
14104 << MemberDecl->getDeclName()
14105 << SourceRange(BuiltinLoc, RParenLoc);
14106 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
14107 return ExprError();
14108 }
14109
14110 RecordDecl *Parent = MemberDecl->getParent();
14111 if (IndirectMemberDecl)
14112 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
14113
14114 // If the member was found in a base class, introduce OffsetOfNodes for
14115 // the base class indirections.
14116 CXXBasePaths Paths;
14117 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
14118 Paths)) {
14119 if (Paths.getDetectedVirtual()) {
14120 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
14121 << MemberDecl->getDeclName()
14122 << SourceRange(BuiltinLoc, RParenLoc);
14123 return ExprError();
14124 }
14125
14126 CXXBasePath &Path = Paths.front();
14127 for (const CXXBasePathElement &B : Path)
14128 Comps.push_back(OffsetOfNode(B.Base));
14129 }
14130
14131 if (IndirectMemberDecl) {
14132 for (auto *FI : IndirectMemberDecl->chain()) {
14133 assert(isa<FieldDecl>(FI))((isa<FieldDecl>(FI)) ? static_cast<void> (0) : __assert_fail
("isa<FieldDecl>(FI)", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 14133, __PRETTY_FUNCTION__))
;
14134 Comps.push_back(OffsetOfNode(OC.LocStart,
14135 cast<FieldDecl>(FI), OC.LocEnd));
14136 }
14137 } else
14138 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
14139
14140 CurrentType = MemberDecl->getType().getNonReferenceType();
14141 }
14142
14143 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
14144 Comps, Exprs, RParenLoc);
14145}
14146
14147ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
14148 SourceLocation BuiltinLoc,
14149 SourceLocation TypeLoc,
14150 ParsedType ParsedArgTy,
14151 ArrayRef<OffsetOfComponent> Components,
14152 SourceLocation RParenLoc) {
14153
14154 TypeSourceInfo *ArgTInfo;
14155 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
14156 if (ArgTy.isNull())
14157 return ExprError();
14158
14159 if (!ArgTInfo)
14160 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
14161
14162 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
14163}
14164
14165
14166ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
14167 Expr *CondExpr,
14168 Expr *LHSExpr, Expr *RHSExpr,
14169 SourceLocation RPLoc) {
14170 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)")(((CondExpr && LHSExpr && RHSExpr) &&
"Missing type argument(s)") ? static_cast<void> (0) : __assert_fail
("(CondExpr && LHSExpr && RHSExpr) && \"Missing type argument(s)\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 14170, __PRETTY_FUNCTION__))
;
14171
14172 ExprValueKind VK = VK_RValue;
14173 ExprObjectKind OK = OK_Ordinary;
14174 QualType resType;
14175 bool ValueDependent = false;
14176 bool CondIsTrue = false;
14177 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
14178 resType = Context.DependentTy;
14179 ValueDependent = true;
14180 } else {
14181 // The conditional expression is required to be a constant expression.
14182 llvm::APSInt condEval(32);
14183 ExprResult CondICE
14184 = VerifyIntegerConstantExpression(CondExpr, &condEval,
14185 diag::err_typecheck_choose_expr_requires_constant, false);
14186 if (CondICE.isInvalid())
14187 return ExprError();
14188 CondExpr = CondICE.get();
14189 CondIsTrue = condEval.getZExtValue();
14190
14191 // If the condition is > zero, then the AST type is the same as the LHSExpr.
14192 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
14193
14194 resType = ActiveExpr->getType();
14195 ValueDependent = ActiveExpr->isValueDependent();
14196 VK = ActiveExpr->getValueKind();
14197 OK = ActiveExpr->getObjectKind();
14198 }
14199
14200 return new (Context)
14201 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
14202 CondIsTrue, resType->isDependentType(), ValueDependent);
14203}
14204
14205//===----------------------------------------------------------------------===//
14206// Clang Extensions.
14207//===----------------------------------------------------------------------===//
14208
14209/// ActOnBlockStart - This callback is invoked when a block literal is started.
14210void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
14211 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
14212
14213 if (LangOpts.CPlusPlus) {
14214 MangleNumberingContext *MCtx;
14215 Decl *ManglingContextDecl;
14216 std::tie(MCtx, ManglingContextDecl) =
14217 getCurrentMangleNumberContext(Block->getDeclContext());
14218 if (MCtx) {
14219 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
14220 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
14221 }
14222 }
14223
14224 PushBlockScope(CurScope, Block);
14225 CurContext->addDecl(Block);
14226 if (CurScope)
14227 PushDeclContext(CurScope, Block);
14228 else
14229 CurContext = Block;
14230
14231 getCurBlock()->HasImplicitReturnType = true;
14232
14233 // Enter a new evaluation context to insulate the block from any
14234 // cleanups from the enclosing full-expression.
14235 PushExpressionEvaluationContext(
14236 ExpressionEvaluationContext::PotentiallyEvaluated);
14237}
14238
14239void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
14240 Scope *CurScope) {
14241 assert(ParamInfo.getIdentifier() == nullptr &&((ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!"
) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 14242, __PRETTY_FUNCTION__))
14242 "block-id should have no identifier!")((ParamInfo.getIdentifier() == nullptr && "block-id should have no identifier!"
) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getIdentifier() == nullptr && \"block-id should have no identifier!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 14242, __PRETTY_FUNCTION__))
;
14243 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext)((ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext
) ? static_cast<void> (0) : __assert_fail ("ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 14243, __PRETTY_FUNCTION__))
;
14244 BlockScopeInfo *CurBlock = getCurBlock();
14245
14246 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
14247 QualType T = Sig->getType();
14248
14249 // FIXME: We should allow unexpanded parameter packs here, but that would,
14250 // in turn, make the block expression contain unexpanded parameter packs.
14251 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
14252 // Drop the parameters.
14253 FunctionProtoType::ExtProtoInfo EPI;
14254 EPI.HasTrailingReturn = false;
14255 EPI.TypeQuals.addConst();
14256 T = Context.getFunctionType(Context.DependentTy, None, EPI);
14257 Sig = Context.getTrivialTypeSourceInfo(T);
14258 }
14259
14260 // GetTypeForDeclarator always produces a function type for a block
14261 // literal signature. Furthermore, it is always a FunctionProtoType
14262 // unless the function was written with a typedef.
14263 assert(T->isFunctionType() &&((T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature"
) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 14264, __PRETTY_FUNCTION__))
14264 "GetTypeForDeclarator made a non-function block signature")((T->isFunctionType() && "GetTypeForDeclarator made a non-function block signature"
) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"GetTypeForDeclarator made a non-function block signature\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 14264, __PRETTY_FUNCTION__))
;
14265
14266 // Look for an explicit signature in that function type.
14267 FunctionProtoTypeLoc ExplicitSignature;
14268
14269 if ((ExplicitSignature = Sig->getTypeLoc()
14270 .getAsAdjusted<FunctionProtoTypeLoc>())) {
14271
14272 // Check whether that explicit signature was synthesized by
14273 // GetTypeForDeclarator. If so, don't save that as part of the
14274 // written signature.
14275 if (ExplicitSignature.getLocalRangeBegin() ==
14276 ExplicitSignature.getLocalRangeEnd()) {
14277 // This would be much cheaper if we stored TypeLocs instead of
14278 // TypeSourceInfos.
14279 TypeLoc Result = ExplicitSignature.getReturnLoc();
14280 unsigned Size = Result.getFullDataSize();
14281 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
14282 Sig->getTypeLoc().initializeFullCopy(Result, Size);
14283
14284 ExplicitSignature = FunctionProtoTypeLoc();
14285 }
14286 }
14287
14288 CurBlock->TheDecl->setSignatureAsWritten(Sig);
14289 CurBlock->FunctionType = T;
14290
14291 const FunctionType *Fn = T->getAs<FunctionType>();
14292 QualType RetTy = Fn->getReturnType();
14293 bool isVariadic =
14294 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
14295
14296 CurBlock->TheDecl->setIsVariadic(isVariadic);
14297
14298 // Context.DependentTy is used as a placeholder for a missing block
14299 // return type. TODO: what should we do with declarators like:
14300 // ^ * { ... }
14301 // If the answer is "apply template argument deduction"....
14302 if (RetTy != Context.DependentTy) {
14303 CurBlock->ReturnType = RetTy;
14304 CurBlock->TheDecl->setBlockMissingReturnType(false);
14305 CurBlock->HasImplicitReturnType = false;
14306 }
14307
14308 // Push block parameters from the declarator if we had them.
14309 SmallVector<ParmVarDecl*, 8> Params;
14310 if (ExplicitSignature) {
14311 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
14312 ParmVarDecl *Param = ExplicitSignature.getParam(I);
14313 if (Param->getIdentifier() == nullptr &&
14314 !Param->isImplicit() &&
14315 !Param->isInvalidDecl() &&
14316 !getLangOpts().CPlusPlus)
14317 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
14318 Params.push_back(Param);
14319 }
14320
14321 // Fake up parameter variables if we have a typedef, like
14322 // ^ fntype { ... }
14323 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
14324 for (const auto &I : Fn->param_types()) {
14325 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
14326 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
14327 Params.push_back(Param);
14328 }
14329 }
14330
14331 // Set the parameters on the block decl.
14332 if (!Params.empty()) {
14333 CurBlock->TheDecl->setParams(Params);
14334 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
14335 /*CheckParameterNames=*/false);
14336 }
14337
14338 // Finally we can process decl attributes.
14339 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
14340
14341 // Put the parameter variables in scope.
14342 for (auto AI : CurBlock->TheDecl->parameters()) {
14343 AI->setOwningFunction(CurBlock->TheDecl);
14344
14345 // If this has an identifier, add it to the scope stack.
14346 if (AI->getIdentifier()) {
14347 CheckShadow(CurBlock->TheScope, AI);
14348
14349 PushOnScopeChains(AI, CurBlock->TheScope);
14350 }
14351 }
14352}
14353
14354/// ActOnBlockError - If there is an error parsing a block, this callback
14355/// is invoked to pop the information about the block from the action impl.
14356void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
14357 // Leave the expression-evaluation context.
14358 DiscardCleanupsInEvaluationContext();
14359 PopExpressionEvaluationContext();
14360
14361 // Pop off CurBlock, handle nested blocks.
14362 PopDeclContext();
14363 PopFunctionScopeInfo();
14364}
14365
14366/// ActOnBlockStmtExpr - This is called when the body of a block statement
14367/// literal was successfully completed. ^(int x){...}
14368ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
14369 Stmt *Body, Scope *CurScope) {
14370 // If blocks are disabled, emit an error.
14371 if (!LangOpts.Blocks)
14372 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
14373
14374 // Leave the expression-evaluation context.
14375 if (hasAnyUnrecoverableErrorsInThisFunction())
14376 DiscardCleanupsInEvaluationContext();
14377 assert(!Cleanup.exprNeedsCleanups() &&((!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!"
) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 14378, __PRETTY_FUNCTION__))
14378 "cleanups within block not correctly bound!")((!Cleanup.exprNeedsCleanups() && "cleanups within block not correctly bound!"
) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"cleanups within block not correctly bound!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 14378, __PRETTY_FUNCTION__))
;
14379 PopExpressionEvaluationContext();
14380
14381 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
14382 BlockDecl *BD = BSI->TheDecl;
14383
14384 if (BSI->HasImplicitReturnType)
14385 deduceClosureReturnType(*BSI);
14386
14387 QualType RetTy = Context.VoidTy;
14388 if (!BSI->ReturnType.isNull())
14389 RetTy = BSI->ReturnType;
14390
14391 bool NoReturn = BD->hasAttr<NoReturnAttr>();
14392 QualType BlockTy;
14393
14394 // If the user wrote a function type in some form, try to use that.
14395 if (!BSI->FunctionType.isNull()) {
14396 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
14397
14398 FunctionType::ExtInfo Ext = FTy->getExtInfo();
14399 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
14400
14401 // Turn protoless block types into nullary block types.
14402 if (isa<FunctionNoProtoType>(FTy)) {
14403 FunctionProtoType::ExtProtoInfo EPI;
14404 EPI.ExtInfo = Ext;
14405 BlockTy = Context.getFunctionType(RetTy, None, EPI);
14406
14407 // Otherwise, if we don't need to change anything about the function type,
14408 // preserve its sugar structure.
14409 } else if (FTy->getReturnType() == RetTy &&
14410 (!NoReturn || FTy->getNoReturnAttr())) {
14411 BlockTy = BSI->FunctionType;
14412
14413 // Otherwise, make the minimal modifications to the function type.
14414 } else {
14415 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
14416 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14417 EPI.TypeQuals = Qualifiers();
14418 EPI.ExtInfo = Ext;
14419 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
14420 }
14421
14422 // If we don't have a function type, just build one from nothing.
14423 } else {
14424 FunctionProtoType::ExtProtoInfo EPI;
14425 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
14426 BlockTy = Context.getFunctionType(RetTy, None, EPI);
14427 }
14428
14429 DiagnoseUnusedParameters(BD->parameters());
14430 BlockTy = Context.getBlockPointerType(BlockTy);
14431
14432 // If needed, diagnose invalid gotos and switches in the block.
14433 if (getCurFunction()->NeedsScopeChecking() &&
14434 !PP.isCodeCompletionEnabled())
14435 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
14436
14437 BD->setBody(cast<CompoundStmt>(Body));
14438
14439 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14440 DiagnoseUnguardedAvailabilityViolations(BD);
14441
14442 // Try to apply the named return value optimization. We have to check again
14443 // if we can do this, though, because blocks keep return statements around
14444 // to deduce an implicit return type.
14445 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
14446 !BD->isDependentContext())
14447 computeNRVO(Body, BSI);
14448
14449 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
14450 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
14451 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
14452 NTCUK_Destruct|NTCUK_Copy);
14453
14454 PopDeclContext();
14455
14456 // Pop the block scope now but keep it alive to the end of this function.
14457 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14458 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
14459
14460 // Set the captured variables on the block.
14461 SmallVector<BlockDecl::Capture, 4> Captures;
14462 for (Capture &Cap : BSI->Captures) {
14463 if (Cap.isInvalid() || Cap.isThisCapture())
14464 continue;
14465
14466 VarDecl *Var = Cap.getVariable();
14467 Expr *CopyExpr = nullptr;
14468 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
14469 if (const RecordType *Record =
14470 Cap.getCaptureType()->getAs<RecordType>()) {
14471 // The capture logic needs the destructor, so make sure we mark it.
14472 // Usually this is unnecessary because most local variables have
14473 // their destructors marked at declaration time, but parameters are
14474 // an exception because it's technically only the call site that
14475 // actually requires the destructor.
14476 if (isa<ParmVarDecl>(Var))
14477 FinalizeVarWithDestructor(Var, Record);
14478
14479 // Enter a separate potentially-evaluated context while building block
14480 // initializers to isolate their cleanups from those of the block
14481 // itself.
14482 // FIXME: Is this appropriate even when the block itself occurs in an
14483 // unevaluated operand?
14484 EnterExpressionEvaluationContext EvalContext(
14485 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
14486
14487 SourceLocation Loc = Cap.getLocation();
14488
14489 ExprResult Result = BuildDeclarationNameExpr(
14490 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
14491
14492 // According to the blocks spec, the capture of a variable from
14493 // the stack requires a const copy constructor. This is not true
14494 // of the copy/move done to move a __block variable to the heap.
14495 if (!Result.isInvalid() &&
14496 !Result.get()->getType().isConstQualified()) {
14497 Result = ImpCastExprToType(Result.get(),
14498 Result.get()->getType().withConst(),
14499 CK_NoOp, VK_LValue);
14500 }
14501
14502 if (!Result.isInvalid()) {
14503 Result = PerformCopyInitialization(
14504 InitializedEntity::InitializeBlock(Var->getLocation(),
14505 Cap.getCaptureType(), false),
14506 Loc, Result.get());
14507 }
14508
14509 // Build a full-expression copy expression if initialization
14510 // succeeded and used a non-trivial constructor. Recover from
14511 // errors by pretending that the copy isn't necessary.
14512 if (!Result.isInvalid() &&
14513 !cast<CXXConstructExpr>(Result.get())->getConstructor()
14514 ->isTrivial()) {
14515 Result = MaybeCreateExprWithCleanups(Result);
14516 CopyExpr = Result.get();
14517 }
14518 }
14519 }
14520
14521 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
14522 CopyExpr);
14523 Captures.push_back(NewCap);
14524 }
14525 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
14526
14527 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
14528
14529 // If the block isn't obviously global, i.e. it captures anything at
14530 // all, then we need to do a few things in the surrounding context:
14531 if (Result->getBlockDecl()->hasCaptures()) {
14532 // First, this expression has a new cleanup object.
14533 ExprCleanupObjects.push_back(Result->getBlockDecl());
14534 Cleanup.setExprNeedsCleanups(true);
14535
14536 // It also gets a branch-protected scope if any of the captured
14537 // variables needs destruction.
14538 for (const auto &CI : Result->getBlockDecl()->captures()) {
14539 const VarDecl *var = CI.getVariable();
14540 if (var->getType().isDestructedType() != QualType::DK_none) {
14541 setFunctionHasBranchProtectedScope();
14542 break;
14543 }
14544 }
14545 }
14546
14547 if (getCurFunction())
14548 getCurFunction()->addBlock(BD);
14549
14550 return Result;
14551}
14552
14553ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
14554 SourceLocation RPLoc) {
14555 TypeSourceInfo *TInfo;
14556 GetTypeFromParser(Ty, &TInfo);
14557 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
14558}
14559
14560ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
14561 Expr *E, TypeSourceInfo *TInfo,
14562 SourceLocation RPLoc) {
14563 Expr *OrigExpr = E;
14564 bool IsMS = false;
14565
14566 // CUDA device code does not support varargs.
14567 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
14568 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
14569 CUDAFunctionTarget T = IdentifyCUDATarget(F);
14570 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
14571 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
14572 }
14573 }
14574
14575 // NVPTX does not support va_arg expression.
14576 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
14577 Context.getTargetInfo().getTriple().isNVPTX())
14578 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
14579
14580 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
14581 // as Microsoft ABI on an actual Microsoft platform, where
14582 // __builtin_ms_va_list and __builtin_va_list are the same.)
14583 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
14584 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
14585 QualType MSVaListType = Context.getBuiltinMSVaListType();
14586 if (Context.hasSameType(MSVaListType, E->getType())) {
14587 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
14588 return ExprError();
14589 IsMS = true;
14590 }
14591 }
14592
14593 // Get the va_list type
14594 QualType VaListType = Context.getBuiltinVaListType();
14595 if (!IsMS) {
14596 if (VaListType->isArrayType()) {
14597 // Deal with implicit array decay; for example, on x86-64,
14598 // va_list is an array, but it's supposed to decay to
14599 // a pointer for va_arg.
14600 VaListType = Context.getArrayDecayedType(VaListType);
14601 // Make sure the input expression also decays appropriately.
14602 ExprResult Result = UsualUnaryConversions(E);
14603 if (Result.isInvalid())
14604 return ExprError();
14605 E = Result.get();
14606 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
14607 // If va_list is a record type and we are compiling in C++ mode,
14608 // check the argument using reference binding.
14609 InitializedEntity Entity = InitializedEntity::InitializeParameter(
14610 Context, Context.getLValueReferenceType(VaListType), false);
14611 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
14612 if (Init.isInvalid())
14613 return ExprError();
14614 E = Init.getAs<Expr>();
14615 } else {
14616 // Otherwise, the va_list argument must be an l-value because
14617 // it is modified by va_arg.
14618 if (!E->isTypeDependent() &&
14619 CheckForModifiableLvalue(E, BuiltinLoc, *this))
14620 return ExprError();
14621 }
14622 }
14623
14624 if (!IsMS && !E->isTypeDependent() &&
14625 !Context.hasSameType(VaListType, E->getType()))
14626 return ExprError(
14627 Diag(E->getBeginLoc(),
14628 diag::err_first_argument_to_va_arg_not_of_type_va_list)
14629 << OrigExpr->getType() << E->getSourceRange());
14630
14631 if (!TInfo->getType()->isDependentType()) {
14632 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14633 diag::err_second_parameter_to_va_arg_incomplete,
14634 TInfo->getTypeLoc()))
14635 return ExprError();
14636
14637 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14638 TInfo->getType(),
14639 diag::err_second_parameter_to_va_arg_abstract,
14640 TInfo->getTypeLoc()))
14641 return ExprError();
14642
14643 if (!TInfo->getType().isPODType(Context)) {
14644 Diag(TInfo->getTypeLoc().getBeginLoc(),
14645 TInfo->getType()->isObjCLifetimeType()
14646 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14647 : diag::warn_second_parameter_to_va_arg_not_pod)
14648 << TInfo->getType()
14649 << TInfo->getTypeLoc().getSourceRange();
14650 }
14651
14652 // Check for va_arg where arguments of the given type will be promoted
14653 // (i.e. this va_arg is guaranteed to have undefined behavior).
14654 QualType PromoteType;
14655 if (TInfo->getType()->isPromotableIntegerType()) {
14656 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14657 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14658 PromoteType = QualType();
14659 }
14660 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14661 PromoteType = Context.DoubleTy;
14662 if (!PromoteType.isNull())
14663 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14664 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14665 << TInfo->getType()
14666 << PromoteType
14667 << TInfo->getTypeLoc().getSourceRange());
14668 }
14669
14670 QualType T = TInfo->getType().getNonLValueExprType(Context);
14671 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14672}
14673
14674ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14675 // The type of __null will be int or long, depending on the size of
14676 // pointers on the target.
14677 QualType Ty;
14678 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14679 if (pw == Context.getTargetInfo().getIntWidth())
14680 Ty = Context.IntTy;
14681 else if (pw == Context.getTargetInfo().getLongWidth())
14682 Ty = Context.LongTy;
14683 else if (pw == Context.getTargetInfo().getLongLongWidth())
14684 Ty = Context.LongLongTy;
14685 else {
14686 llvm_unreachable("I don't know size of pointer!")::llvm::llvm_unreachable_internal("I don't know size of pointer!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 14686)
;
14687 }
14688
14689 return new (Context) GNUNullExpr(Ty, TokenLoc);
14690}
14691
14692ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
14693 SourceLocation BuiltinLoc,
14694 SourceLocation RPLoc) {
14695 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
14696}
14697
14698ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
14699 SourceLocation BuiltinLoc,
14700 SourceLocation RPLoc,
14701 DeclContext *ParentContext) {
14702 return new (Context)
14703 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
14704}
14705
14706bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14707 bool Diagnose) {
14708 if (!getLangOpts().ObjC)
14709 return false;
14710
14711 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14712 if (!PT)
14713 return false;
14714
14715 if (!PT->isObjCIdType()) {
14716 // Check if the destination is the 'NSString' interface.
14717 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14718 if (!ID || !ID->getIdentifier()->isStr("NSString"))
14719 return false;
14720 }
14721
14722 // Ignore any parens, implicit casts (should only be
14723 // array-to-pointer decays), and not-so-opaque values. The last is
14724 // important for making this trigger for property assignments.
14725 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14726 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14727 if (OV->getSourceExpr())
14728 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14729
14730 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14731 if (!SL || !SL->isAscii())
14732 return false;
14733 if (Diagnose) {
14734 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14735 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14736 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14737 }
14738 return true;
14739}
14740
14741static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14742 const Expr *SrcExpr) {
14743 if (!DstType->isFunctionPointerType() ||
14744 !SrcExpr->getType()->isFunctionType())
14745 return false;
14746
14747 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14748 if (!DRE)
14749 return false;
14750
14751 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14752 if (!FD)
14753 return false;
14754
14755 return !S.checkAddressOfFunctionIsAvailable(FD,
14756 /*Complain=*/true,
14757 SrcExpr->getBeginLoc());
14758}
14759
14760bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14761 SourceLocation Loc,
14762 QualType DstType, QualType SrcType,
14763 Expr *SrcExpr, AssignmentAction Action,
14764 bool *Complained) {
14765 if (Complained)
14766 *Complained = false;
14767
14768 // Decode the result (notice that AST's are still created for extensions).
14769 bool CheckInferredResultType = false;
14770 bool isInvalid = false;
14771 unsigned DiagKind = 0;
14772 FixItHint Hint;
14773 ConversionFixItGenerator ConvHints;
14774 bool MayHaveConvFixit = false;
14775 bool MayHaveFunctionDiff = false;
14776 const ObjCInterfaceDecl *IFace = nullptr;
14777 const ObjCProtocolDecl *PDecl = nullptr;
14778
14779 switch (ConvTy) {
14780 case Compatible:
14781 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14782 return false;
14783
14784 case PointerToInt:
14785 if (getLangOpts().CPlusPlus) {
14786 DiagKind = diag::err_typecheck_convert_pointer_int;
14787 isInvalid = true;
14788 } else {
14789 DiagKind = diag::ext_typecheck_convert_pointer_int;
14790 }
14791 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14792 MayHaveConvFixit = true;
14793 break;
14794 case IntToPointer:
14795 if (getLangOpts().CPlusPlus) {
14796 DiagKind = diag::err_typecheck_convert_int_pointer;
14797 isInvalid = true;
14798 } else {
14799 DiagKind = diag::ext_typecheck_convert_int_pointer;
14800 }
14801 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14802 MayHaveConvFixit = true;
14803 break;
14804 case IncompatibleFunctionPointer:
14805 if (getLangOpts().CPlusPlus) {
14806 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
14807 isInvalid = true;
14808 } else {
14809 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14810 }
14811 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14812 MayHaveConvFixit = true;
14813 break;
14814 case IncompatiblePointer:
14815 if (Action == AA_Passing_CFAudited) {
14816 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14817 } else if (getLangOpts().CPlusPlus) {
14818 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
14819 isInvalid = true;
14820 } else {
14821 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14822 }
14823 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14824 SrcType->isObjCObjectPointerType();
14825 if (Hint.isNull() && !CheckInferredResultType) {
14826 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14827 }
14828 else if (CheckInferredResultType) {
14829 SrcType = SrcType.getUnqualifiedType();
14830 DstType = DstType.getUnqualifiedType();
14831 }
14832 MayHaveConvFixit = true;
14833 break;
14834 case IncompatiblePointerSign:
14835 if (getLangOpts().CPlusPlus) {
14836 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
14837 isInvalid = true;
14838 } else {
14839 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14840 }
14841 break;
14842 case FunctionVoidPointer:
14843 if (getLangOpts().CPlusPlus) {
14844 DiagKind = diag::err_typecheck_convert_pointer_void_func;
14845 isInvalid = true;
14846 } else {
14847 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14848 }
14849 break;
14850 case IncompatiblePointerDiscardsQualifiers: {
14851 // Perform array-to-pointer decay if necessary.
14852 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14853
14854 isInvalid = true;
14855
14856 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14857 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14858 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14859 DiagKind = diag::err_typecheck_incompatible_address_space;
14860 break;
14861
14862 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14863 DiagKind = diag::err_typecheck_incompatible_ownership;
14864 break;
14865 }
14866
14867 llvm_unreachable("unknown error case for discarding qualifiers!")::llvm::llvm_unreachable_internal("unknown error case for discarding qualifiers!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 14867)
;
14868 // fallthrough
14869 }
14870 case CompatiblePointerDiscardsQualifiers:
14871 // If the qualifiers lost were because we were applying the
14872 // (deprecated) C++ conversion from a string literal to a char*
14873 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
14874 // Ideally, this check would be performed in
14875 // checkPointerTypesForAssignment. However, that would require a
14876 // bit of refactoring (so that the second argument is an
14877 // expression, rather than a type), which should be done as part
14878 // of a larger effort to fix checkPointerTypesForAssignment for
14879 // C++ semantics.
14880 if (getLangOpts().CPlusPlus &&
14881 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14882 return false;
14883 if (getLangOpts().CPlusPlus) {
14884 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
14885 isInvalid = true;
14886 } else {
14887 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14888 }
14889
14890 break;
14891 case IncompatibleNestedPointerQualifiers:
14892 if (getLangOpts().CPlusPlus) {
14893 isInvalid = true;
14894 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
14895 } else {
14896 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14897 }
14898 break;
14899 case IncompatibleNestedPointerAddressSpaceMismatch:
14900 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
14901 isInvalid = true;
14902 break;
14903 case IntToBlockPointer:
14904 DiagKind = diag::err_int_to_block_pointer;
14905 isInvalid = true;
14906 break;
14907 case IncompatibleBlockPointer:
14908 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14909 isInvalid = true;
14910 break;
14911 case IncompatibleObjCQualifiedId: {
14912 if (SrcType->isObjCQualifiedIdType()) {
14913 const ObjCObjectPointerType *srcOPT =
14914 SrcType->castAs<ObjCObjectPointerType>();
14915 for (auto *srcProto : srcOPT->quals()) {
14916 PDecl = srcProto;
14917 break;
14918 }
14919 if (const ObjCInterfaceType *IFaceT =
14920 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14921 IFace = IFaceT->getDecl();
14922 }
14923 else if (DstType->isObjCQualifiedIdType()) {
14924 const ObjCObjectPointerType *dstOPT =
14925 DstType->castAs<ObjCObjectPointerType>();
14926 for (auto *dstProto : dstOPT->quals()) {
14927 PDecl = dstProto;
14928 break;
14929 }
14930 if (const ObjCInterfaceType *IFaceT =
14931 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
14932 IFace = IFaceT->getDecl();
14933 }
14934 if (getLangOpts().CPlusPlus) {
14935 DiagKind = diag::err_incompatible_qualified_id;
14936 isInvalid = true;
14937 } else {
14938 DiagKind = diag::warn_incompatible_qualified_id;
14939 }
14940 break;
14941 }
14942 case IncompatibleVectors:
14943 if (getLangOpts().CPlusPlus) {
14944 DiagKind = diag::err_incompatible_vectors;
14945 isInvalid = true;
14946 } else {
14947 DiagKind = diag::warn_incompatible_vectors;
14948 }
14949 break;
14950 case IncompatibleObjCWeakRef:
14951 DiagKind = diag::err_arc_weak_unavailable_assign;
14952 isInvalid = true;
14953 break;
14954 case Incompatible:
14955 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14956 if (Complained)
14957 *Complained = true;
14958 return true;
14959 }
14960
14961 DiagKind = diag::err_typecheck_convert_incompatible;
14962 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14963 MayHaveConvFixit = true;
14964 isInvalid = true;
14965 MayHaveFunctionDiff = true;
14966 break;
14967 }
14968
14969 QualType FirstType, SecondType;
14970 switch (Action) {
14971 case AA_Assigning:
14972 case AA_Initializing:
14973 // The destination type comes first.
14974 FirstType = DstType;
14975 SecondType = SrcType;
14976 break;
14977
14978 case AA_Returning:
14979 case AA_Passing:
14980 case AA_Passing_CFAudited:
14981 case AA_Converting:
14982 case AA_Sending:
14983 case AA_Casting:
14984 // The source type comes first.
14985 FirstType = SrcType;
14986 SecondType = DstType;
14987 break;
14988 }
14989
14990 PartialDiagnostic FDiag = PDiag(DiagKind);
14991 if (Action == AA_Passing_CFAudited)
14992 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14993 else
14994 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14995
14996 // If we can fix the conversion, suggest the FixIts.
14997 assert(ConvHints.isNull() || Hint.isNull())((ConvHints.isNull() || Hint.isNull()) ? static_cast<void>
(0) : __assert_fail ("ConvHints.isNull() || Hint.isNull()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 14997, __PRETTY_FUNCTION__))
;
14998 if (!ConvHints.isNull()) {
14999 for (FixItHint &H : ConvHints.Hints)
15000 FDiag << H;
15001 } else {
15002 FDiag << Hint;
15003 }
15004 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15005
15006 if (MayHaveFunctionDiff)
15007 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15008
15009 Diag(Loc, FDiag);
15010 if ((DiagKind == diag::warn_incompatible_qualified_id ||
15011 DiagKind == diag::err_incompatible_qualified_id) &&
15012 PDecl && IFace && !IFace->hasDefinition())
15013 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15014 << IFace << PDecl;
15015
15016 if (SecondType == Context.OverloadTy)
15017 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15018 FirstType, /*TakingAddress=*/true);
15019
15020 if (CheckInferredResultType)
15021 EmitRelatedResultTypeNote(SrcExpr);
15022
15023 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15024 EmitRelatedResultTypeNoteForReturn(DstType);
15025
15026 if (Complained)
15027 *Complained = true;
15028 return isInvalid;
15029}
15030
15031ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15032 llvm::APSInt *Result) {
15033 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15034 public:
15035 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15036 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
15037 }
15038 } Diagnoser;
15039
15040 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
15041}
15042
15043ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15044 llvm::APSInt *Result,
15045 unsigned DiagID,
15046 bool AllowFold) {
15047 class IDDiagnoser : public VerifyICEDiagnoser {
15048 unsigned DiagID;
15049
15050 public:
15051 IDDiagnoser(unsigned DiagID)
15052 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
15053
15054 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
15055 S.Diag(Loc, DiagID) << SR;
15056 }
15057 } Diagnoser(DiagID);
15058
15059 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
15060}
15061
15062void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
15063 SourceRange SR) {
15064 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
15065}
15066
15067ExprResult
15068Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
15069 VerifyICEDiagnoser &Diagnoser,
15070 bool AllowFold) {
15071 SourceLocation DiagLoc = E->getBeginLoc();
15072
15073 if (getLangOpts().CPlusPlus11) {
15074 // C++11 [expr.const]p5:
15075 // If an expression of literal class type is used in a context where an
15076 // integral constant expression is required, then that class type shall
15077 // have a single non-explicit conversion function to an integral or
15078 // unscoped enumeration type
15079 ExprResult Converted;
15080 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
15081 public:
15082 CXX11ConvertDiagnoser(bool Silent)
15083 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
15084 Silent, true) {}
15085
15086 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
15087 QualType T) override {
15088 return S.Diag(Loc, diag::err_ice_not_integral) << T;
15089 }
15090
15091 SemaDiagnosticBuilder diagnoseIncomplete(
15092 Sema &S, SourceLocation Loc, QualType T) override {
15093 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
15094 }
15095
15096 SemaDiagnosticBuilder diagnoseExplicitConv(
15097 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15098 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
15099 }
15100
15101 SemaDiagnosticBuilder noteExplicitConv(
15102 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15103 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15104 << ConvTy->isEnumeralType() << ConvTy;
15105 }
15106
15107 SemaDiagnosticBuilder diagnoseAmbiguous(
15108 Sema &S, SourceLocation Loc, QualType T) override {
15109 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
15110 }
15111
15112 SemaDiagnosticBuilder noteAmbiguous(
15113 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
15114 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
15115 << ConvTy->isEnumeralType() << ConvTy;
15116 }
15117
15118 SemaDiagnosticBuilder diagnoseConversion(
15119 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
15120 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 15120)
;
15121 }
15122 } ConvertDiagnoser(Diagnoser.Suppress);
15123
15124 Converted = PerformContextualImplicitConversion(DiagLoc, E,
15125 ConvertDiagnoser);
15126 if (Converted.isInvalid())
15127 return Converted;
15128 E = Converted.get();
15129 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
15130 return ExprError();
15131 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15132 // An ICE must be of integral or unscoped enumeration type.
15133 if (!Diagnoser.Suppress)
15134 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15135 return ExprError();
15136 }
15137
15138 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
15139 // in the non-ICE case.
15140 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
15141 if (Result)
15142 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
15143 if (!isa<ConstantExpr>(E))
15144 E = ConstantExpr::Create(Context, E);
15145 return E;
15146 }
15147
15148 Expr::EvalResult EvalResult;
15149 SmallVector<PartialDiagnosticAt, 8> Notes;
15150 EvalResult.Diag = &Notes;
15151
15152 // Try to evaluate the expression, and produce diagnostics explaining why it's
15153 // not a constant expression as a side-effect.
15154 bool Folded =
15155 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
15156 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
15157
15158 if (!isa<ConstantExpr>(E))
15159 E = ConstantExpr::Create(Context, E, EvalResult.Val);
15160
15161 // In C++11, we can rely on diagnostics being produced for any expression
15162 // which is not a constant expression. If no diagnostics were produced, then
15163 // this is a constant expression.
15164 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
15165 if (Result)
15166 *Result = EvalResult.Val.getInt();
15167 return E;
15168 }
15169
15170 // If our only note is the usual "invalid subexpression" note, just point
15171 // the caret at its location rather than producing an essentially
15172 // redundant note.
15173 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
15174 diag::note_invalid_subexpr_in_const_expr) {
15175 DiagLoc = Notes[0].first;
15176 Notes.clear();
15177 }
15178
15179 if (!Folded || !AllowFold) {
15180 if (!Diagnoser.Suppress) {
15181 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
15182 for (const PartialDiagnosticAt &Note : Notes)
15183 Diag(Note.first, Note.second);
15184 }
15185
15186 return ExprError();
15187 }
15188
15189 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
15190 for (const PartialDiagnosticAt &Note : Notes)
15191 Diag(Note.first, Note.second);
15192
15193 if (Result)
15194 *Result = EvalResult.Val.getInt();
15195 return E;
15196}
15197
15198namespace {
15199 // Handle the case where we conclude a expression which we speculatively
15200 // considered to be unevaluated is actually evaluated.
15201 class TransformToPE : public TreeTransform<TransformToPE> {
15202 typedef TreeTransform<TransformToPE> BaseTransform;
15203
15204 public:
15205 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
15206
15207 // Make sure we redo semantic analysis
15208 bool AlwaysRebuild() { return true; }
15209 bool ReplacingOriginal() { return true; }
15210
15211 // We need to special-case DeclRefExprs referring to FieldDecls which
15212 // are not part of a member pointer formation; normal TreeTransforming
15213 // doesn't catch this case because of the way we represent them in the AST.
15214 // FIXME: This is a bit ugly; is it really the best way to handle this
15215 // case?
15216 //
15217 // Error on DeclRefExprs referring to FieldDecls.
15218 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15219 if (isa<FieldDecl>(E->getDecl()) &&
15220 !SemaRef.isUnevaluatedContext())
15221 return SemaRef.Diag(E->getLocation(),
15222 diag::err_invalid_non_static_member_use)
15223 << E->getDecl() << E->getSourceRange();
15224
15225 return BaseTransform::TransformDeclRefExpr(E);
15226 }
15227
15228 // Exception: filter out member pointer formation
15229 ExprResult TransformUnaryOperator(UnaryOperator *E) {
15230 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
15231 return E;
15232
15233 return BaseTransform::TransformUnaryOperator(E);
15234 }
15235
15236 // The body of a lambda-expression is in a separate expression evaluation
15237 // context so never needs to be transformed.
15238 // FIXME: Ideally we wouldn't transform the closure type either, and would
15239 // just recreate the capture expressions and lambda expression.
15240 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
15241 return SkipLambdaBody(E, Body);
15242 }
15243 };
15244}
15245
15246ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
15247 assert(isUnevaluatedContext() &&((isUnevaluatedContext() && "Should only transform unevaluated expressions"
) ? static_cast<void> (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 15248, __PRETTY_FUNCTION__))
15248 "Should only transform unevaluated expressions")((isUnevaluatedContext() && "Should only transform unevaluated expressions"
) ? static_cast<void> (0) : __assert_fail ("isUnevaluatedContext() && \"Should only transform unevaluated expressions\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 15248, __PRETTY_FUNCTION__))
;
15249 ExprEvalContexts.back().Context =
15250 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
15251 if (isUnevaluatedContext())
15252 return E;
15253 return TransformToPE(*this).TransformExpr(E);
15254}
15255
15256void
15257Sema::PushExpressionEvaluationContext(
15258 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
15259 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15260 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
15261 LambdaContextDecl, ExprContext);
15262 Cleanup.reset();
15263 if (!MaybeODRUseExprs.empty())
15264 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
15265}
15266
15267void
15268Sema::PushExpressionEvaluationContext(
15269 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
15270 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
15271 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
15272 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
15273}
15274
15275namespace {
15276
15277const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
15278 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
15279 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
15280 if (E->getOpcode() == UO_Deref)
15281 return CheckPossibleDeref(S, E->getSubExpr());
15282 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
15283 return CheckPossibleDeref(S, E->getBase());
15284 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
15285 return CheckPossibleDeref(S, E->getBase());
15286 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
15287 QualType Inner;
15288 QualType Ty = E->getType();
15289 if (const auto *Ptr = Ty->getAs<PointerType>())
15290 Inner = Ptr->getPointeeType();
15291 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
15292 Inner = Arr->getElementType();
15293 else
15294 return nullptr;
15295
15296 if (Inner->hasAttr(attr::NoDeref))
15297 return E;
15298 }
15299 return nullptr;
15300}
15301
15302} // namespace
15303
15304void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
15305 for (const Expr *E : Rec.PossibleDerefs) {
15306 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
15307 if (DeclRef) {
15308 const ValueDecl *Decl = DeclRef->getDecl();
15309 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
15310 << Decl->getName() << E->getSourceRange();
15311 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
15312 } else {
15313 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
15314 << E->getSourceRange();
15315 }
15316 }
15317 Rec.PossibleDerefs.clear();
15318}
15319
15320/// Check whether E, which is either a discarded-value expression or an
15321/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
15322/// and if so, remove it from the list of volatile-qualified assignments that
15323/// we are going to warn are deprecated.
15324void Sema::CheckUnusedVolatileAssignment(Expr *E) {
15325 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus2a)
15326 return;
15327
15328 // Note: ignoring parens here is not justified by the standard rules, but
15329 // ignoring parentheses seems like a more reasonable approach, and this only
15330 // drives a deprecation warning so doesn't affect conformance.
15331 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
15332 if (BO->getOpcode() == BO_Assign) {
15333 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
15334 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
15335 LHSs.end());
15336 }
15337 }
15338}
15339
15340ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
15341 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
15342 RebuildingImmediateInvocation)
15343 return E;
15344
15345 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
15346 /// It's OK if this fails; we'll also remove this in
15347 /// HandleImmediateInvocations, but catching it here allows us to avoid
15348 /// walking the AST looking for it in simple cases.
15349 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
15350 if (auto *DeclRef =
15351 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
15352 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
15353
15354 E = MaybeCreateExprWithCleanups(E);
15355
15356 ConstantExpr *Res = ConstantExpr::Create(
15357 getASTContext(), E.get(),
15358 ConstantExpr::getStorageKind(E.get()->getType().getTypePtr(),
15359 getASTContext()),
15360 /*IsImmediateInvocation*/ true);
15361 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
15362 return Res;
15363}
15364
15365static void EvaluateAndDiagnoseImmediateInvocation(
15366 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
15367 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
15368 Expr::EvalResult Eval;
15369 Eval.Diag = &Notes;
15370 ConstantExpr *CE = Candidate.getPointer();
15371 bool Result = CE->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen,
15372 SemaRef.getASTContext(), true);
15373 if (!Result || !Notes.empty()) {
15374 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
15375 FunctionDecl *FD = nullptr;
15376 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
15377 FD = cast<FunctionDecl>(Call->getCalleeDecl());
15378 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
15379 FD = Call->getConstructor();
15380 else
15381 llvm_unreachable("unhandled decl kind")::llvm::llvm_unreachable_internal("unhandled decl kind", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 15381)
;
15382 assert(FD->isConsteval())((FD->isConsteval()) ? static_cast<void> (0) : __assert_fail
("FD->isConsteval()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 15382, __PRETTY_FUNCTION__))
;
15383 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
15384 for (auto &Note : Notes)
15385 SemaRef.Diag(Note.first, Note.second);
15386 return;
15387 }
15388 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
15389}
15390
15391static void RemoveNestedImmediateInvocation(
15392 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
15393 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
15394 struct ComplexRemove : TreeTransform<ComplexRemove> {
15395 using Base = TreeTransform<ComplexRemove>;
15396 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
15397 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
15398 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
15399 CurrentII;
15400 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
15401 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
15402 SmallVector<Sema::ImmediateInvocationCandidate,
15403 4>::reverse_iterator Current)
15404 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
15405 void RemoveImmediateInvocation(ConstantExpr* E) {
15406 auto It = std::find_if(CurrentII, IISet.rend(),
15407 [E](Sema::ImmediateInvocationCandidate Elem) {
15408 return Elem.getPointer() == E;
15409 });
15410 assert(It != IISet.rend() &&((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should "
"be present") ? static_cast<void> (0) : __assert_fail (
"It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 15412, __PRETTY_FUNCTION__))
15411 "ConstantExpr marked IsImmediateInvocation should "((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should "
"be present") ? static_cast<void> (0) : __assert_fail (
"It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 15412, __PRETTY_FUNCTION__))
15412 "be present")((It != IISet.rend() && "ConstantExpr marked IsImmediateInvocation should "
"be present") ? static_cast<void> (0) : __assert_fail (
"It != IISet.rend() && \"ConstantExpr marked IsImmediateInvocation should \" \"be present\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 15412, __PRETTY_FUNCTION__))
;
15413 It->setInt(1); // Mark as deleted
15414 }
15415 ExprResult TransformConstantExpr(ConstantExpr *E) {
15416 if (!E->isImmediateInvocation())
15417 return Base::TransformConstantExpr(E);
15418 RemoveImmediateInvocation(E);
15419 return Base::TransformExpr(E->getSubExpr());
15420 }
15421 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
15422 /// we need to remove its DeclRefExpr from the DRSet.
15423 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
15424 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
15425 return Base::TransformCXXOperatorCallExpr(E);
15426 }
15427 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
15428 /// here.
15429 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
15430 if (!Init)
15431 return Init;
15432 /// ConstantExpr are the first layer of implicit node to be removed so if
15433 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
15434 if (auto *CE = dyn_cast<ConstantExpr>(Init))
15435 if (CE->isImmediateInvocation())
15436 RemoveImmediateInvocation(CE);
15437 return Base::TransformInitializer(Init, NotCopyInit);
15438 }
15439 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
15440 DRSet.erase(E);
15441 return E;
15442 }
15443 bool AlwaysRebuild() { return false; }
15444 bool ReplacingOriginal() { return true; }
15445 } Transformer(SemaRef, Rec.ReferenceToConsteval,
15446 Rec.ImmediateInvocationCandidates, It);
15447 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
15448 assert(Res.isUsable())((Res.isUsable()) ? static_cast<void> (0) : __assert_fail
("Res.isUsable()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 15448, __PRETTY_FUNCTION__))
;
15449 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
15450 It->getPointer()->setSubExpr(Res.get());
15451}
15452
15453static void
15454HandleImmediateInvocations(Sema &SemaRef,
15455 Sema::ExpressionEvaluationContextRecord &Rec) {
15456 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
15457 Rec.ReferenceToConsteval.size() == 0) ||
15458 SemaRef.RebuildingImmediateInvocation)
15459 return;
15460
15461 /// When we have more then 1 ImmediateInvocationCandidates we need to check
15462 /// for nested ImmediateInvocationCandidates. when we have only 1 we only
15463 /// need to remove ReferenceToConsteval in the immediate invocation.
15464 if (Rec.ImmediateInvocationCandidates.size() > 1) {
15465
15466 /// Prevent sema calls during the tree transform from adding pointers that
15467 /// are already in the sets.
15468 llvm::SaveAndRestore<bool> DisableIITracking(
15469 SemaRef.RebuildingImmediateInvocation, true);
15470
15471 /// Prevent diagnostic during tree transfrom as they are duplicates
15472 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
15473
15474 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
15475 It != Rec.ImmediateInvocationCandidates.rend(); It++)
15476 if (!It->getInt())
15477 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
15478 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
15479 Rec.ReferenceToConsteval.size()) {
15480 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
15481 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
15482 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
15483 bool VisitDeclRefExpr(DeclRefExpr *E) {
15484 DRSet.erase(E);
15485 return DRSet.size();
15486 }
15487 } Visitor(Rec.ReferenceToConsteval);
15488 Visitor.TraverseStmt(
15489 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
15490 }
15491 for (auto CE : Rec.ImmediateInvocationCandidates)
15492 if (!CE.getInt())
15493 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
15494 for (auto DR : Rec.ReferenceToConsteval) {
15495 auto *FD = cast<FunctionDecl>(DR->getDecl());
15496 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
15497 << FD;
15498 SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
15499 }
15500}
15501
15502void Sema::PopExpressionEvaluationContext() {
15503 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
15504 unsigned NumTypos = Rec.NumTypos;
15505
15506 if (!Rec.Lambdas.empty()) {
15507 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
15508 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
15509 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
15510 unsigned D;
15511 if (Rec.isUnevaluated()) {
15512 // C++11 [expr.prim.lambda]p2:
15513 // A lambda-expression shall not appear in an unevaluated operand
15514 // (Clause 5).
15515 D = diag::err_lambda_unevaluated_operand;
15516 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
15517 // C++1y [expr.const]p2:
15518 // A conditional-expression e is a core constant expression unless the
15519 // evaluation of e, following the rules of the abstract machine, would
15520 // evaluate [...] a lambda-expression.
15521 D = diag::err_lambda_in_constant_expression;
15522 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
15523 // C++17 [expr.prim.lamda]p2:
15524 // A lambda-expression shall not appear [...] in a template-argument.
15525 D = diag::err_lambda_in_invalid_context;
15526 } else
15527 llvm_unreachable("Couldn't infer lambda error message.")::llvm::llvm_unreachable_internal("Couldn't infer lambda error message."
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 15527)
;
15528
15529 for (const auto *L : Rec.Lambdas)
15530 Diag(L->getBeginLoc(), D);
15531 }
15532 }
15533
15534 WarnOnPendingNoDerefs(Rec);
15535 HandleImmediateInvocations(*this, Rec);
15536
15537 // Warn on any volatile-qualified simple-assignments that are not discarded-
15538 // value expressions nor unevaluated operands (those cases get removed from
15539 // this list by CheckUnusedVolatileAssignment).
15540 for (auto *BO : Rec.VolatileAssignmentLHSs)
15541 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
15542 << BO->getType();
15543
15544 // When are coming out of an unevaluated context, clear out any
15545 // temporaries that we may have created as part of the evaluation of
15546 // the expression in that context: they aren't relevant because they
15547 // will never be constructed.
15548 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
15549 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
15550 ExprCleanupObjects.end());
15551 Cleanup = Rec.ParentCleanup;
15552 CleanupVarDeclMarking();
15553 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
15554 // Otherwise, merge the contexts together.
15555 } else {
15556 Cleanup.mergeFrom(Rec.ParentCleanup);
15557 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
15558 Rec.SavedMaybeODRUseExprs.end());
15559 }
15560
15561 // Pop the current expression evaluation context off the stack.
15562 ExprEvalContexts.pop_back();
15563
15564 // The global expression evaluation context record is never popped.
15565 ExprEvalContexts.back().NumTypos += NumTypos;
15566}
15567
15568void Sema::DiscardCleanupsInEvaluationContext() {
15569 ExprCleanupObjects.erase(
15570 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
15571 ExprCleanupObjects.end());
15572 Cleanup.reset();
15573 MaybeODRUseExprs.clear();
15574}
15575
15576ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
15577 ExprResult Result = CheckPlaceholderExpr(E);
15578 if (Result.isInvalid())
15579 return ExprError();
15580 E = Result.get();
15581 if (!E->getType()->isVariablyModifiedType())
15582 return E;
15583 return TransformToPotentiallyEvaluated(E);
15584}
15585
15586/// Are we in a context that is potentially constant evaluated per C++20
15587/// [expr.const]p12?
15588static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
15589 /// C++2a [expr.const]p12:
15590 // An expression or conversion is potentially constant evaluated if it is
15591 switch (SemaRef.ExprEvalContexts.back().Context) {
15592 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15593 // -- a manifestly constant-evaluated expression,
15594 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15595 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15596 case Sema::ExpressionEvaluationContext::DiscardedStatement:
15597 // -- a potentially-evaluated expression,
15598 case Sema::ExpressionEvaluationContext::UnevaluatedList:
15599 // -- an immediate subexpression of a braced-init-list,
15600
15601 // -- [FIXME] an expression of the form & cast-expression that occurs
15602 // within a templated entity
15603 // -- a subexpression of one of the above that is not a subexpression of
15604 // a nested unevaluated operand.
15605 return true;
15606
15607 case Sema::ExpressionEvaluationContext::Unevaluated:
15608 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15609 // Expressions in this context are never evaluated.
15610 return false;
15611 }
15612 llvm_unreachable("Invalid context")::llvm::llvm_unreachable_internal("Invalid context", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 15612)
;
15613}
15614
15615/// Return true if this function has a calling convention that requires mangling
15616/// in the size of the parameter pack.
15617static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
15618 // These manglings don't do anything on non-Windows or non-x86 platforms, so
15619 // we don't need parameter type sizes.
15620 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
15621 if (!TT.isOSWindows() || !TT.isX86())
15622 return false;
15623
15624 // If this is C++ and this isn't an extern "C" function, parameters do not
15625 // need to be complete. In this case, C++ mangling will apply, which doesn't
15626 // use the size of the parameters.
15627 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
15628 return false;
15629
15630 // Stdcall, fastcall, and vectorcall need this special treatment.
15631 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15632 switch (CC) {
15633 case CC_X86StdCall:
15634 case CC_X86FastCall:
15635 case CC_X86VectorCall:
15636 return true;
15637 default:
15638 break;
15639 }
15640 return false;
15641}
15642
15643/// Require that all of the parameter types of function be complete. Normally,
15644/// parameter types are only required to be complete when a function is called
15645/// or defined, but to mangle functions with certain calling conventions, the
15646/// mangler needs to know the size of the parameter list. In this situation,
15647/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
15648/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
15649/// result in a linker error. Clang doesn't implement this behavior, and instead
15650/// attempts to error at compile time.
15651static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
15652 SourceLocation Loc) {
15653 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
15654 FunctionDecl *FD;
15655 ParmVarDecl *Param;
15656
15657 public:
15658 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
15659 : FD(FD), Param(Param) {}
15660
15661 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15662 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
15663 StringRef CCName;
15664 switch (CC) {
15665 case CC_X86StdCall:
15666 CCName = "stdcall";
15667 break;
15668 case CC_X86FastCall:
15669 CCName = "fastcall";
15670 break;
15671 case CC_X86VectorCall:
15672 CCName = "vectorcall";
15673 break;
15674 default:
15675 llvm_unreachable("CC does not need mangling")::llvm::llvm_unreachable_internal("CC does not need mangling"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 15675)
;
15676 }
15677
15678 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
15679 << Param->getDeclName() << FD->getDeclName() << CCName;
15680 }
15681 };
15682
15683 for (ParmVarDecl *Param : FD->parameters()) {
15684 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
15685 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
15686 }
15687}
15688
15689namespace {
15690enum class OdrUseContext {
15691 /// Declarations in this context are not odr-used.
15692 None,
15693 /// Declarations in this context are formally odr-used, but this is a
15694 /// dependent context.
15695 Dependent,
15696 /// Declarations in this context are odr-used but not actually used (yet).
15697 FormallyOdrUsed,
15698 /// Declarations in this context are used.
15699 Used
15700};
15701}
15702
15703/// Are we within a context in which references to resolved functions or to
15704/// variables result in odr-use?
15705static OdrUseContext isOdrUseContext(Sema &SemaRef) {
15706 OdrUseContext Result;
15707
15708 switch (SemaRef.ExprEvalContexts.back().Context) {
15709 case Sema::ExpressionEvaluationContext::Unevaluated:
15710 case Sema::ExpressionEvaluationContext::UnevaluatedList:
15711 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
15712 return OdrUseContext::None;
15713
15714 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
15715 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
15716 Result = OdrUseContext::Used;
15717 break;
15718
15719 case Sema::ExpressionEvaluationContext::DiscardedStatement:
15720 Result = OdrUseContext::FormallyOdrUsed;
15721 break;
15722
15723 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15724 // A default argument formally results in odr-use, but doesn't actually
15725 // result in a use in any real sense until it itself is used.
15726 Result = OdrUseContext::FormallyOdrUsed;
15727 break;
15728 }
15729
15730 if (SemaRef.CurContext->isDependentContext())
15731 return OdrUseContext::Dependent;
15732
15733 return Result;
15734}
15735
15736static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
15737 return Func->isConstexpr() &&
15738 (Func->isImplicitlyInstantiable() || !Func->isUserProvided());
15739}
15740
15741/// Mark a function referenced, and check whether it is odr-used
15742/// (C++ [basic.def.odr]p2, C99 6.9p3)
15743void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
15744 bool MightBeOdrUse) {
15745 assert(Func && "No function?")((Func && "No function?") ? static_cast<void> (
0) : __assert_fail ("Func && \"No function?\"", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 15745, __PRETTY_FUNCTION__))
;
15746
15747 Func->setReferenced();
15748
15749 // Recursive functions aren't really used until they're used from some other
15750 // context.
15751 bool IsRecursiveCall = CurContext == Func;
15752
15753 // C++11 [basic.def.odr]p3:
15754 // A function whose name appears as a potentially-evaluated expression is
15755 // odr-used if it is the unique lookup result or the selected member of a
15756 // set of overloaded functions [...].
15757 //
15758 // We (incorrectly) mark overload resolution as an unevaluated context, so we
15759 // can just check that here.
15760 OdrUseContext OdrUse =
15761 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
15762 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
15763 OdrUse = OdrUseContext::FormallyOdrUsed;
15764
15765 // Trivial default constructors and destructors are never actually used.
15766 // FIXME: What about other special members?
15767 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
15768 OdrUse == OdrUseContext::Used) {
15769 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
15770 if (Constructor->isDefaultConstructor())
15771 OdrUse = OdrUseContext::FormallyOdrUsed;
15772 if (isa<CXXDestructorDecl>(Func))
15773 OdrUse = OdrUseContext::FormallyOdrUsed;
15774 }
15775
15776 // C++20 [expr.const]p12:
15777 // A function [...] is needed for constant evaluation if it is [...] a
15778 // constexpr function that is named by an expression that is potentially
15779 // constant evaluated
15780 bool NeededForConstantEvaluation =
15781 isPotentiallyConstantEvaluatedContext(*this) &&
15782 isImplicitlyDefinableConstexprFunction(Func);
15783
15784 // Determine whether we require a function definition to exist, per
15785 // C++11 [temp.inst]p3:
15786 // Unless a function template specialization has been explicitly
15787 // instantiated or explicitly specialized, the function template
15788 // specialization is implicitly instantiated when the specialization is
15789 // referenced in a context that requires a function definition to exist.
15790 // C++20 [temp.inst]p7:
15791 // The existence of a definition of a [...] function is considered to
15792 // affect the semantics of the program if the [...] function is needed for
15793 // constant evaluation by an expression
15794 // C++20 [basic.def.odr]p10:
15795 // Every program shall contain exactly one definition of every non-inline
15796 // function or variable that is odr-used in that program outside of a
15797 // discarded statement
15798 // C++20 [special]p1:
15799 // The implementation will implicitly define [defaulted special members]
15800 // if they are odr-used or needed for constant evaluation.
15801 //
15802 // Note that we skip the implicit instantiation of templates that are only
15803 // used in unused default arguments or by recursive calls to themselves.
15804 // This is formally non-conforming, but seems reasonable in practice.
15805 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
15806 NeededForConstantEvaluation);
15807
15808 // C++14 [temp.expl.spec]p6:
15809 // If a template [...] is explicitly specialized then that specialization
15810 // shall be declared before the first use of that specialization that would
15811 // cause an implicit instantiation to take place, in every translation unit
15812 // in which such a use occurs
15813 if (NeedDefinition &&
15814 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
15815 Func->getMemberSpecializationInfo()))
15816 checkSpecializationVisibility(Loc, Func);
15817
15818 if (getLangOpts().CUDA)
15819 CheckCUDACall(Loc, Func);
15820
15821 // If we need a definition, try to create one.
15822 if (NeedDefinition && !Func->getBody()) {
15823 runWithSufficientStackSpace(Loc, [&] {
15824 if (CXXConstructorDecl *Constructor =
15825 dyn_cast<CXXConstructorDecl>(Func)) {
15826 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
15827 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
15828 if (Constructor->isDefaultConstructor()) {
15829 if (Constructor->isTrivial() &&
15830 !Constructor->hasAttr<DLLExportAttr>())
15831 return;
15832 DefineImplicitDefaultConstructor(Loc, Constructor);
15833 } else if (Constructor->isCopyConstructor()) {
15834 DefineImplicitCopyConstructor(Loc, Constructor);
15835 } else if (Constructor->isMoveConstructor()) {
15836 DefineImplicitMoveConstructor(Loc, Constructor);
15837 }
15838 } else if (Constructor->getInheritedConstructor()) {
15839 DefineInheritingConstructor(Loc, Constructor);
15840 }
15841 } else if (CXXDestructorDecl *Destructor =
15842 dyn_cast<CXXDestructorDecl>(Func)) {
15843 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
15844 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
15845 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
15846 return;
15847 DefineImplicitDestructor(Loc, Destructor);
15848 }
15849 if (Destructor->isVirtual() && getLangOpts().AppleKext)
15850 MarkVTableUsed(Loc, Destructor->getParent());
15851 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
15852 if (MethodDecl->isOverloadedOperator() &&
15853 MethodDecl->getOverloadedOperator() == OO_Equal) {
15854 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
15855 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
15856 if (MethodDecl->isCopyAssignmentOperator())
15857 DefineImplicitCopyAssignment(Loc, MethodDecl);
15858 else if (MethodDecl->isMoveAssignmentOperator())
15859 DefineImplicitMoveAssignment(Loc, MethodDecl);
15860 }
15861 } else if (isa<CXXConversionDecl>(MethodDecl) &&
15862 MethodDecl->getParent()->isLambda()) {
15863 CXXConversionDecl *Conversion =
15864 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
15865 if (Conversion->isLambdaToBlockPointerConversion())
15866 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
15867 else
15868 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
15869 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
15870 MarkVTableUsed(Loc, MethodDecl->getParent());
15871 }
15872
15873 if (Func->isDefaulted() && !Func->isDeleted()) {
15874 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
15875 if (DCK != DefaultedComparisonKind::None)
15876 DefineDefaultedComparison(Loc, Func, DCK);
15877 }
15878
15879 // Implicit instantiation of function templates and member functions of
15880 // class templates.
15881 if (Func->isImplicitlyInstantiable()) {
15882 TemplateSpecializationKind TSK =
15883 Func->getTemplateSpecializationKindForInstantiation();
15884 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
15885 bool FirstInstantiation = PointOfInstantiation.isInvalid();
15886 if (FirstInstantiation) {
15887 PointOfInstantiation = Loc;
15888 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15889 } else if (TSK != TSK_ImplicitInstantiation) {
15890 // Use the point of use as the point of instantiation, instead of the
15891 // point of explicit instantiation (which we track as the actual point
15892 // of instantiation). This gives better backtraces in diagnostics.
15893 PointOfInstantiation = Loc;
15894 }
15895
15896 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
15897 Func->isConstexpr()) {
15898 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
15899 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
15900 CodeSynthesisContexts.size())
15901 PendingLocalImplicitInstantiations.push_back(
15902 std::make_pair(Func, PointOfInstantiation));
15903 else if (Func->isConstexpr())
15904 // Do not defer instantiations of constexpr functions, to avoid the
15905 // expression evaluator needing to call back into Sema if it sees a
15906 // call to such a function.
15907 InstantiateFunctionDefinition(PointOfInstantiation, Func);
15908 else {
15909 Func->setInstantiationIsPending(true);
15910 PendingInstantiations.push_back(
15911 std::make_pair(Func, PointOfInstantiation));
15912 // Notify the consumer that a function was implicitly instantiated.
15913 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
15914 }
15915 }
15916 } else {
15917 // Walk redefinitions, as some of them may be instantiable.
15918 for (auto i : Func->redecls()) {
15919 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
15920 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
15921 }
15922 }
15923 });
15924 }
15925
15926 // C++14 [except.spec]p17:
15927 // An exception-specification is considered to be needed when:
15928 // - the function is odr-used or, if it appears in an unevaluated operand,
15929 // would be odr-used if the expression were potentially-evaluated;
15930 //
15931 // Note, we do this even if MightBeOdrUse is false. That indicates that the
15932 // function is a pure virtual function we're calling, and in that case the
15933 // function was selected by overload resolution and we need to resolve its
15934 // exception specification for a different reason.
15935 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
15936 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
15937 ResolveExceptionSpec(Loc, FPT);
15938
15939 // If this is the first "real" use, act on that.
15940 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
15941 // Keep track of used but undefined functions.
15942 if (!Func->isDefined()) {
15943 if (mightHaveNonExternalLinkage(Func))
15944 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15945 else if (Func->getMostRecentDecl()->isInlined() &&
15946 !LangOpts.GNUInline &&
15947 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
15948 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15949 else if (isExternalWithNoLinkageType(Func))
15950 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
15951 }
15952
15953 // Some x86 Windows calling conventions mangle the size of the parameter
15954 // pack into the name. Computing the size of the parameters requires the
15955 // parameter types to be complete. Check that now.
15956 if (funcHasParameterSizeMangling(*this, Func))
15957 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
15958
15959 Func->markUsed(Context);
15960 }
15961
15962 if (LangOpts.OpenMP) {
15963 markOpenMPDeclareVariantFuncsReferenced(Loc, Func, MightBeOdrUse);
15964 if (LangOpts.OpenMPIsDevice)
15965 checkOpenMPDeviceFunction(Loc, Func);
15966 else
15967 checkOpenMPHostFunction(Loc, Func);
15968 }
15969}
15970
15971/// Directly mark a variable odr-used. Given a choice, prefer to use
15972/// MarkVariableReferenced since it does additional checks and then
15973/// calls MarkVarDeclODRUsed.
15974/// If the variable must be captured:
15975/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
15976/// - else capture it in the DeclContext that maps to the
15977/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
15978static void
15979MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
15980 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
15981 // Keep track of used but undefined variables.
15982 // FIXME: We shouldn't suppress this warning for static data members.
15983 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
15984 (!Var->isExternallyVisible() || Var->isInline() ||
15985 SemaRef.isExternalWithNoLinkageType(Var)) &&
15986 !(Var->isStaticDataMember() && Var->hasInit())) {
15987 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
15988 if (old.isInvalid())
15989 old = Loc;
15990 }
15991 QualType CaptureType, DeclRefType;
15992 if (SemaRef.LangOpts.OpenMP)
15993 SemaRef.tryCaptureOpenMPLambdas(Var);
15994 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
15995 /*EllipsisLoc*/ SourceLocation(),
15996 /*BuildAndDiagnose*/ true,
15997 CaptureType, DeclRefType,
15998 FunctionScopeIndexToStopAt);
15999
16000 Var->markUsed(SemaRef.Context);
16001}
16002
16003void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
16004 SourceLocation Loc,
16005 unsigned CapturingScopeIndex) {
16006 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
16007}
16008
16009static void
16010diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
16011 ValueDecl *var, DeclContext *DC) {
16012 DeclContext *VarDC = var->getDeclContext();
16013
16014 // If the parameter still belongs to the translation unit, then
16015 // we're actually just using one parameter in the declaration of
16016 // the next.
16017 if (isa<ParmVarDecl>(var) &&
16018 isa<TranslationUnitDecl>(VarDC))
16019 return;
16020
16021 // For C code, don't diagnose about capture if we're not actually in code
16022 // right now; it's impossible to write a non-constant expression outside of
16023 // function context, so we'll get other (more useful) diagnostics later.
16024 //
16025 // For C++, things get a bit more nasty... it would be nice to suppress this
16026 // diagnostic for certain cases like using a local variable in an array bound
16027 // for a member of a local class, but the correct predicate is not obvious.
16028 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
16029 return;
16030
16031 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
16032 unsigned ContextKind = 3; // unknown
16033 if (isa<CXXMethodDecl>(VarDC) &&
16034 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
16035 ContextKind = 2;
16036 } else if (isa<FunctionDecl>(VarDC)) {
16037 ContextKind = 0;
16038 } else if (isa<BlockDecl>(VarDC)) {
16039 ContextKind = 1;
16040 }
16041
16042 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
16043 << var << ValueKind << ContextKind << VarDC;
16044 S.Diag(var->getLocation(), diag::note_entity_declared_at)
16045 << var;
16046
16047 // FIXME: Add additional diagnostic info about class etc. which prevents
16048 // capture.
16049}
16050
16051
16052static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
16053 bool &SubCapturesAreNested,
16054 QualType &CaptureType,
16055 QualType &DeclRefType) {
16056 // Check whether we've already captured it.
16057 if (CSI->CaptureMap.count(Var)) {
16058 // If we found a capture, any subcaptures are nested.
16059 SubCapturesAreNested = true;
16060
16061 // Retrieve the capture type for this variable.
16062 CaptureType = CSI->getCapture(Var).getCaptureType();
16063
16064 // Compute the type of an expression that refers to this variable.
16065 DeclRefType = CaptureType.getNonReferenceType();
16066
16067 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
16068 // are mutable in the sense that user can change their value - they are
16069 // private instances of the captured declarations.
16070 const Capture &Cap = CSI->getCapture(Var);
16071 if (Cap.isCopyCapture() &&
16072 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
16073 !(isa<CapturedRegionScopeInfo>(CSI) &&
16074 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
16075 DeclRefType.addConst();
16076 return true;
16077 }
16078 return false;
16079}
16080
16081// Only block literals, captured statements, and lambda expressions can
16082// capture; other scopes don't work.
16083static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
16084 SourceLocation Loc,
16085 const bool Diagnose, Sema &S) {
16086 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
16087 return getLambdaAwareParentOfDeclContext(DC);
16088 else if (Var->hasLocalStorage()) {
16089 if (Diagnose)
16090 diagnoseUncapturableValueReference(S, Loc, Var, DC);
16091 }
16092 return nullptr;
16093}
16094
16095// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16096// certain types of variables (unnamed, variably modified types etc.)
16097// so check for eligibility.
16098static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
16099 SourceLocation Loc,
16100 const bool Diagnose, Sema &S) {
16101
16102 bool IsBlock = isa<BlockScopeInfo>(CSI);
16103 bool IsLambda = isa<LambdaScopeInfo>(CSI);
16104
16105 // Lambdas are not allowed to capture unnamed variables
16106 // (e.g. anonymous unions).
16107 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
16108 // assuming that's the intent.
16109 if (IsLambda && !Var->getDeclName()) {
16110 if (Diagnose) {
16111 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
16112 S.Diag(Var->getLocation(), diag::note_declared_at);
16113 }
16114 return false;
16115 }
16116
16117 // Prohibit variably-modified types in blocks; they're difficult to deal with.
16118 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
16119 if (Diagnose) {
16120 S.Diag(Loc, diag::err_ref_vm_type);
16121 S.Diag(Var->getLocation(), diag::note_previous_decl)
16122 << Var->getDeclName();
16123 }
16124 return false;
16125 }
16126 // Prohibit structs with flexible array members too.
16127 // We cannot capture what is in the tail end of the struct.
16128 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
16129 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
16130 if (Diagnose) {
16131 if (IsBlock)
16132 S.Diag(Loc, diag::err_ref_flexarray_type);
16133 else
16134 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
16135 << Var->getDeclName();
16136 S.Diag(Var->getLocation(), diag::note_previous_decl)
16137 << Var->getDeclName();
16138 }
16139 return false;
16140 }
16141 }
16142 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16143 // Lambdas and captured statements are not allowed to capture __block
16144 // variables; they don't support the expected semantics.
16145 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
16146 if (Diagnose) {
16147 S.Diag(Loc, diag::err_capture_block_variable)
16148 << Var->getDeclName() << !IsLambda;
16149 S.Diag(Var->getLocation(), diag::note_previous_decl)
16150 << Var->getDeclName();
16151 }
16152 return false;
16153 }
16154 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
16155 if (S.getLangOpts().OpenCL && IsBlock &&
16156 Var->getType()->isBlockPointerType()) {
16157 if (Diagnose)
16158 S.Diag(Loc, diag::err_opencl_block_ref_block);
16159 return false;
16160 }
16161
16162 return true;
16163}
16164
16165// Returns true if the capture by block was successful.
16166static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
16167 SourceLocation Loc,
16168 const bool BuildAndDiagnose,
16169 QualType &CaptureType,
16170 QualType &DeclRefType,
16171 const bool Nested,
16172 Sema &S, bool Invalid) {
16173 bool ByRef = false;
16174
16175 // Blocks are not allowed to capture arrays, excepting OpenCL.
16176 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
16177 // (decayed to pointers).
16178 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
16179 if (BuildAndDiagnose) {
16180 S.Diag(Loc, diag::err_ref_array_type);
16181 S.Diag(Var->getLocation(), diag::note_previous_decl)
16182 << Var->getDeclName();
16183 Invalid = true;
16184 } else {
16185 return false;
16186 }
16187 }
16188
16189 // Forbid the block-capture of autoreleasing variables.
16190 if (!Invalid &&
16191 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16192 if (BuildAndDiagnose) {
16193 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
16194 << /*block*/ 0;
16195 S.Diag(Var->getLocation(), diag::note_previous_decl)
16196 << Var->getDeclName();
16197 Invalid = true;
16198 } else {
16199 return false;
16200 }
16201 }
16202
16203 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
16204 if (const auto *PT = CaptureType->getAs<PointerType>()) {
16205 QualType PointeeTy = PT->getPointeeType();
16206
16207 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
16208 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
16209 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
16210 if (BuildAndDiagnose) {
16211 SourceLocation VarLoc = Var->getLocation();
16212 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
16213 S.Diag(VarLoc, diag::note_declare_parameter_strong);
16214 }
16215 }
16216 }
16217
16218 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
16219 if (HasBlocksAttr || CaptureType->isReferenceType() ||
16220 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
16221 // Block capture by reference does not change the capture or
16222 // declaration reference types.
16223 ByRef = true;
16224 } else {
16225 // Block capture by copy introduces 'const'.
16226 CaptureType = CaptureType.getNonReferenceType().withConst();
16227 DeclRefType = CaptureType;
16228 }
16229
16230 // Actually capture the variable.
16231 if (BuildAndDiagnose)
16232 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
16233 CaptureType, Invalid);
16234
16235 return !Invalid;
16236}
16237
16238
16239/// Capture the given variable in the captured region.
16240static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
16241 VarDecl *Var,
16242 SourceLocation Loc,
16243 const bool BuildAndDiagnose,
16244 QualType &CaptureType,
16245 QualType &DeclRefType,
16246 const bool RefersToCapturedVariable,
16247 Sema &S, bool Invalid) {
16248 // By default, capture variables by reference.
16249 bool ByRef = true;
16250 // Using an LValue reference type is consistent with Lambdas (see below).
16251 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
16252 if (S.isOpenMPCapturedDecl(Var)) {
16253 bool HasConst = DeclRefType.isConstQualified();
16254 DeclRefType = DeclRefType.getUnqualifiedType();
16255 // Don't lose diagnostics about assignments to const.
16256 if (HasConst)
16257 DeclRefType.addConst();
16258 }
16259 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
16260 RSI->OpenMPCaptureLevel);
16261 }
16262
16263 if (ByRef)
16264 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16265 else
16266 CaptureType = DeclRefType;
16267
16268 // Actually capture the variable.
16269 if (BuildAndDiagnose)
16270 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
16271 Loc, SourceLocation(), CaptureType, Invalid);
16272
16273 return !Invalid;
16274}
16275
16276/// Capture the given variable in the lambda.
16277static bool captureInLambda(LambdaScopeInfo *LSI,
16278 VarDecl *Var,
16279 SourceLocation Loc,
16280 const bool BuildAndDiagnose,
16281 QualType &CaptureType,
16282 QualType &DeclRefType,
16283 const bool RefersToCapturedVariable,
16284 const Sema::TryCaptureKind Kind,
16285 SourceLocation EllipsisLoc,
16286 const bool IsTopScope,
16287 Sema &S, bool Invalid) {
16288 // Determine whether we are capturing by reference or by value.
16289 bool ByRef = false;
16290 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
16291 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
16292 } else {
16293 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
16294 }
16295
16296 // Compute the type of the field that will capture this variable.
16297 if (ByRef) {
16298 // C++11 [expr.prim.lambda]p15:
16299 // An entity is captured by reference if it is implicitly or
16300 // explicitly captured but not captured by copy. It is
16301 // unspecified whether additional unnamed non-static data
16302 // members are declared in the closure type for entities
16303 // captured by reference.
16304 //
16305 // FIXME: It is not clear whether we want to build an lvalue reference
16306 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
16307 // to do the former, while EDG does the latter. Core issue 1249 will
16308 // clarify, but for now we follow GCC because it's a more permissive and
16309 // easily defensible position.
16310 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
16311 } else {
16312 // C++11 [expr.prim.lambda]p14:
16313 // For each entity captured by copy, an unnamed non-static
16314 // data member is declared in the closure type. The
16315 // declaration order of these members is unspecified. The type
16316 // of such a data member is the type of the corresponding
16317 // captured entity if the entity is not a reference to an
16318 // object, or the referenced type otherwise. [Note: If the
16319 // captured entity is a reference to a function, the
16320 // corresponding data member is also a reference to a
16321 // function. - end note ]
16322 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
16323 if (!RefType->getPointeeType()->isFunctionType())
16324 CaptureType = RefType->getPointeeType();
16325 }
16326
16327 // Forbid the lambda copy-capture of autoreleasing variables.
16328 if (!Invalid &&
16329 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
16330 if (BuildAndDiagnose) {
16331 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
16332 S.Diag(Var->getLocation(), diag::note_previous_decl)
16333 << Var->getDeclName();
16334 Invalid = true;
16335 } else {
16336 return false;
16337 }
16338 }
16339
16340 // Make sure that by-copy captures are of a complete and non-abstract type.
16341 if (!Invalid && BuildAndDiagnose) {
16342 if (!CaptureType->isDependentType() &&
16343 S.RequireCompleteType(Loc, CaptureType,
16344 diag::err_capture_of_incomplete_type,
16345 Var->getDeclName()))
16346 Invalid = true;
16347 else if (S.RequireNonAbstractType(Loc, CaptureType,
16348 diag::err_capture_of_abstract_type))
16349 Invalid = true;
16350 }
16351 }
16352
16353 // Compute the type of a reference to this captured variable.
16354 if (ByRef)
16355 DeclRefType = CaptureType.getNonReferenceType();
16356 else {
16357 // C++ [expr.prim.lambda]p5:
16358 // The closure type for a lambda-expression has a public inline
16359 // function call operator [...]. This function call operator is
16360 // declared const (9.3.1) if and only if the lambda-expression's
16361 // parameter-declaration-clause is not followed by mutable.
16362 DeclRefType = CaptureType.getNonReferenceType();
16363 if (!LSI->Mutable && !CaptureType->isReferenceType())
16364 DeclRefType.addConst();
16365 }
16366
16367 // Add the capture.
16368 if (BuildAndDiagnose)
16369 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
16370 Loc, EllipsisLoc, CaptureType, Invalid);
16371
16372 return !Invalid;
16373}
16374
16375bool Sema::tryCaptureVariable(
16376 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
16377 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
16378 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
16379 // An init-capture is notionally from the context surrounding its
16380 // declaration, but its parent DC is the lambda class.
16381 DeclContext *VarDC = Var->getDeclContext();
16382 if (Var->isInitCapture())
16383 VarDC = VarDC->getParent();
16384
16385 DeclContext *DC = CurContext;
16386 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
16387 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
16388 // We need to sync up the Declaration Context with the
16389 // FunctionScopeIndexToStopAt
16390 if (FunctionScopeIndexToStopAt) {
16391 unsigned FSIndex = FunctionScopes.size() - 1;
16392 while (FSIndex != MaxFunctionScopesIndex) {
16393 DC = getLambdaAwareParentOfDeclContext(DC);
16394 --FSIndex;
16395 }
16396 }
16397
16398
16399 // If the variable is declared in the current context, there is no need to
16400 // capture it.
16401 if (VarDC == DC) return true;
16402
16403 // Capture global variables if it is required to use private copy of this
16404 // variable.
16405 bool IsGlobal = !Var->hasLocalStorage();
16406 if (IsGlobal &&
16407 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
16408 MaxFunctionScopesIndex)))
16409 return true;
16410 Var = Var->getCanonicalDecl();
16411
16412 // Walk up the stack to determine whether we can capture the variable,
16413 // performing the "simple" checks that don't depend on type. We stop when
16414 // we've either hit the declared scope of the variable or find an existing
16415 // capture of that variable. We start from the innermost capturing-entity
16416 // (the DC) and ensure that all intervening capturing-entities
16417 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
16418 // declcontext can either capture the variable or have already captured
16419 // the variable.
16420 CaptureType = Var->getType();
16421 DeclRefType = CaptureType.getNonReferenceType();
16422 bool Nested = false;
16423 bool Explicit = (Kind != TryCapture_Implicit);
16424 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
16425 do {
16426 // Only block literals, captured statements, and lambda expressions can
16427 // capture; other scopes don't work.
16428 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
16429 ExprLoc,
16430 BuildAndDiagnose,
16431 *this);
16432 // We need to check for the parent *first* because, if we *have*
16433 // private-captured a global variable, we need to recursively capture it in
16434 // intermediate blocks, lambdas, etc.
16435 if (!ParentDC) {
16436 if (IsGlobal) {
16437 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
16438 break;
16439 }
16440 return true;
16441 }
16442
16443 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
16444 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
16445
16446
16447 // Check whether we've already captured it.
16448 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
16449 DeclRefType)) {
16450 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
16451 break;
16452 }
16453 // If we are instantiating a generic lambda call operator body,
16454 // we do not want to capture new variables. What was captured
16455 // during either a lambdas transformation or initial parsing
16456 // should be used.
16457 if (isGenericLambdaCallOperatorSpecialization(DC)) {
16458 if (BuildAndDiagnose) {
16459 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16460 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
16461 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16462 Diag(Var->getLocation(), diag::note_previous_decl)
16463 << Var->getDeclName();
16464 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
16465 } else
16466 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
16467 }
16468 return true;
16469 }
16470
16471 // Try to capture variable-length arrays types.
16472 if (Var->getType()->isVariablyModifiedType()) {
16473 // We're going to walk down into the type and look for VLA
16474 // expressions.
16475 QualType QTy = Var->getType();
16476 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16477 QTy = PVD->getOriginalType();
16478 captureVariablyModifiedType(Context, QTy, CSI);
16479 }
16480
16481 if (getLangOpts().OpenMP) {
16482 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16483 // OpenMP private variables should not be captured in outer scope, so
16484 // just break here. Similarly, global variables that are captured in a
16485 // target region should not be captured outside the scope of the region.
16486 if (RSI->CapRegionKind == CR_OpenMP) {
16487 bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
16488 // If the variable is private (i.e. not captured) and has variably
16489 // modified type, we still need to capture the type for correct
16490 // codegen in all regions, associated with the construct. Currently,
16491 // it is captured in the innermost captured region only.
16492 if (IsOpenMPPrivateDecl && Var->getType()->isVariablyModifiedType()) {
16493 QualType QTy = Var->getType();
16494 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
16495 QTy = PVD->getOriginalType();
16496 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
16497 I < E; ++I) {
16498 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
16499 FunctionScopes[FunctionScopesIndex - I]);
16500 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the "
"OpenMP construct.") ? static_cast<void> (0) : __assert_fail
("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 16502, __PRETTY_FUNCTION__))
16501 "Wrong number of captured regions associated with the "((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the "
"OpenMP construct.") ? static_cast<void> (0) : __assert_fail
("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 16502, __PRETTY_FUNCTION__))
16502 "OpenMP construct.")((RSI->OpenMPLevel == OuterRSI->OpenMPLevel && "Wrong number of captured regions associated with the "
"OpenMP construct.") ? static_cast<void> (0) : __assert_fail
("RSI->OpenMPLevel == OuterRSI->OpenMPLevel && \"Wrong number of captured regions associated with the \" \"OpenMP construct.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 16502, __PRETTY_FUNCTION__))
;
16503 captureVariablyModifiedType(Context, QTy, OuterRSI);
16504 }
16505 }
16506 bool IsTargetCap =
16507 !IsOpenMPPrivateDecl &&
16508 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
16509 RSI->OpenMPCaptureLevel);
16510 // When we detect target captures we are looking from inside the
16511 // target region, therefore we need to propagate the capture from the
16512 // enclosing region. Therefore, the capture is not initially nested.
16513 if (IsTargetCap)
16514 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
16515
16516 if (IsTargetCap || IsOpenMPPrivateDecl) {
16517 Nested = !IsTargetCap;
16518 DeclRefType = DeclRefType.getUnqualifiedType();
16519 CaptureType = Context.getLValueReferenceType(DeclRefType);
16520 break;
16521 }
16522 }
16523 }
16524 }
16525 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
16526 // No capture-default, and this is not an explicit capture
16527 // so cannot capture this variable.
16528 if (BuildAndDiagnose) {
16529 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
16530 Diag(Var->getLocation(), diag::note_previous_decl)
16531 << Var->getDeclName();
16532 if (cast<LambdaScopeInfo>(CSI)->Lambda)
16533 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
16534 diag::note_lambda_decl);
16535 // FIXME: If we error out because an outer lambda can not implicitly
16536 // capture a variable that an inner lambda explicitly captures, we
16537 // should have the inner lambda do the explicit capture - because
16538 // it makes for cleaner diagnostics later. This would purely be done
16539 // so that the diagnostic does not misleadingly claim that a variable
16540 // can not be captured by a lambda implicitly even though it is captured
16541 // explicitly. Suggestion:
16542 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
16543 // at the function head
16544 // - cache the StartingDeclContext - this must be a lambda
16545 // - captureInLambda in the innermost lambda the variable.
16546 }
16547 return true;
16548 }
16549
16550 FunctionScopesIndex--;
16551 DC = ParentDC;
16552 Explicit = false;
16553 } while (!VarDC->Equals(DC));
16554
16555 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
16556 // computing the type of the capture at each step, checking type-specific
16557 // requirements, and adding captures if requested.
16558 // If the variable had already been captured previously, we start capturing
16559 // at the lambda nested within that one.
16560 bool Invalid = false;
16561 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
16562 ++I) {
16563 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
16564
16565 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
16566 // certain types of variables (unnamed, variably modified types etc.)
16567 // so check for eligibility.
16568 if (!Invalid)
16569 Invalid =
16570 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
16571
16572 // After encountering an error, if we're actually supposed to capture, keep
16573 // capturing in nested contexts to suppress any follow-on diagnostics.
16574 if (Invalid && !BuildAndDiagnose)
16575 return true;
16576
16577 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
16578 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16579 DeclRefType, Nested, *this, Invalid);
16580 Nested = true;
16581 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
16582 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
16583 CaptureType, DeclRefType, Nested,
16584 *this, Invalid);
16585 Nested = true;
16586 } else {
16587 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
16588 Invalid =
16589 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
16590 DeclRefType, Nested, Kind, EllipsisLoc,
16591 /*IsTopScope*/ I == N - 1, *this, Invalid);
16592 Nested = true;
16593 }
16594
16595 if (Invalid && !BuildAndDiagnose)
16596 return true;
16597 }
16598 return Invalid;
16599}
16600
16601bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
16602 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
16603 QualType CaptureType;
16604 QualType DeclRefType;
16605 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
16606 /*BuildAndDiagnose=*/true, CaptureType,
16607 DeclRefType, nullptr);
16608}
16609
16610bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
16611 QualType CaptureType;
16612 QualType DeclRefType;
16613 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16614 /*BuildAndDiagnose=*/false, CaptureType,
16615 DeclRefType, nullptr);
16616}
16617
16618QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
16619 QualType CaptureType;
16620 QualType DeclRefType;
16621
16622 // Determine whether we can capture this variable.
16623 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
16624 /*BuildAndDiagnose=*/false, CaptureType,
16625 DeclRefType, nullptr))
16626 return QualType();
16627
16628 return DeclRefType;
16629}
16630
16631namespace {
16632// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
16633// The produced TemplateArgumentListInfo* points to data stored within this
16634// object, so should only be used in contexts where the pointer will not be
16635// used after the CopiedTemplateArgs object is destroyed.
16636class CopiedTemplateArgs {
16637 bool HasArgs;
16638 TemplateArgumentListInfo TemplateArgStorage;
16639public:
16640 template<typename RefExpr>
16641 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
16642 if (HasArgs)
16643 E->copyTemplateArgumentsInto(TemplateArgStorage);
16644 }
16645 operator TemplateArgumentListInfo*()
16646#ifdef __has_cpp_attribute
16647#if0 __has_cpp_attribute(clang::lifetimebound)1
16648 [[clang::lifetimebound]]
16649#endif
16650#endif
16651 {
16652 return HasArgs ? &TemplateArgStorage : nullptr;
16653 }
16654};
16655}
16656
16657/// Walk the set of potential results of an expression and mark them all as
16658/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
16659///
16660/// \return A new expression if we found any potential results, ExprEmpty() if
16661/// not, and ExprError() if we diagnosed an error.
16662static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
16663 NonOdrUseReason NOUR) {
16664 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
16665 // an object that satisfies the requirements for appearing in a
16666 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
16667 // is immediately applied." This function handles the lvalue-to-rvalue
16668 // conversion part.
16669 //
16670 // If we encounter a node that claims to be an odr-use but shouldn't be, we
16671 // transform it into the relevant kind of non-odr-use node and rebuild the
16672 // tree of nodes leading to it.
16673 //
16674 // This is a mini-TreeTransform that only transforms a restricted subset of
16675 // nodes (and only certain operands of them).
16676
16677 // Rebuild a subexpression.
16678 auto Rebuild = [&](Expr *Sub) {
16679 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
16680 };
16681
16682 // Check whether a potential result satisfies the requirements of NOUR.
16683 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
16684 // Any entity other than a VarDecl is always odr-used whenever it's named
16685 // in a potentially-evaluated expression.
16686 auto *VD = dyn_cast<VarDecl>(D);
16687 if (!VD)
16688 return true;
16689
16690 // C++2a [basic.def.odr]p4:
16691 // A variable x whose name appears as a potentially-evalauted expression
16692 // e is odr-used by e unless
16693 // -- x is a reference that is usable in constant expressions, or
16694 // -- x is a variable of non-reference type that is usable in constant
16695 // expressions and has no mutable subobjects, and e is an element of
16696 // the set of potential results of an expression of
16697 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
16698 // conversion is applied, or
16699 // -- x is a variable of non-reference type, and e is an element of the
16700 // set of potential results of a discarded-value expression to which
16701 // the lvalue-to-rvalue conversion is not applied
16702 //
16703 // We check the first bullet and the "potentially-evaluated" condition in
16704 // BuildDeclRefExpr. We check the type requirements in the second bullet
16705 // in CheckLValueToRValueConversionOperand below.
16706 switch (NOUR) {
16707 case NOUR_None:
16708 case NOUR_Unevaluated:
16709 llvm_unreachable("unexpected non-odr-use-reason")::llvm::llvm_unreachable_internal("unexpected non-odr-use-reason"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 16709)
;
16710
16711 case NOUR_Constant:
16712 // Constant references were handled when they were built.
16713 if (VD->getType()->isReferenceType())
16714 return true;
16715 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
16716 if (RD->hasMutableFields())
16717 return true;
16718 if (!VD->isUsableInConstantExpressions(S.Context))
16719 return true;
16720 break;
16721
16722 case NOUR_Discarded:
16723 if (VD->getType()->isReferenceType())
16724 return true;
16725 break;
16726 }
16727 return false;
16728 };
16729
16730 // Mark that this expression does not constitute an odr-use.
16731 auto MarkNotOdrUsed = [&] {
16732 S.MaybeODRUseExprs.erase(E);
16733 if (LambdaScopeInfo *LSI = S.getCurLambda())
16734 LSI->markVariableExprAsNonODRUsed(E);
16735 };
16736
16737 // C++2a [basic.def.odr]p2:
16738 // The set of potential results of an expression e is defined as follows:
16739 switch (E->getStmtClass()) {
16740 // -- If e is an id-expression, ...
16741 case Expr::DeclRefExprClass: {
16742 auto *DRE = cast<DeclRefExpr>(E);
16743 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
16744 break;
16745
16746 // Rebuild as a non-odr-use DeclRefExpr.
16747 MarkNotOdrUsed();
16748 return DeclRefExpr::Create(
16749 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
16750 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
16751 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
16752 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
16753 }
16754
16755 case Expr::FunctionParmPackExprClass: {
16756 auto *FPPE = cast<FunctionParmPackExpr>(E);
16757 // If any of the declarations in the pack is odr-used, then the expression
16758 // as a whole constitutes an odr-use.
16759 for (VarDecl *D : *FPPE)
16760 if (IsPotentialResultOdrUsed(D))
16761 return ExprEmpty();
16762
16763 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
16764 // nothing cares about whether we marked this as an odr-use, but it might
16765 // be useful for non-compiler tools.
16766 MarkNotOdrUsed();
16767 break;
16768 }
16769
16770 // -- If e is a subscripting operation with an array operand...
16771 case Expr::ArraySubscriptExprClass: {
16772 auto *ASE = cast<ArraySubscriptExpr>(E);
16773 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
16774 if (!OldBase->getType()->isArrayType())
16775 break;
16776 ExprResult Base = Rebuild(OldBase);
16777 if (!Base.isUsable())
16778 return Base;
16779 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
16780 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
16781 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
16782 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
16783 ASE->getRBracketLoc());
16784 }
16785
16786 case Expr::MemberExprClass: {
16787 auto *ME = cast<MemberExpr>(E);
16788 // -- If e is a class member access expression [...] naming a non-static
16789 // data member...
16790 if (isa<FieldDecl>(ME->getMemberDecl())) {
16791 ExprResult Base = Rebuild(ME->getBase());
16792 if (!Base.isUsable())
16793 return Base;
16794 return MemberExpr::Create(
16795 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
16796 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
16797 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
16798 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
16799 ME->getObjectKind(), ME->isNonOdrUse());
16800 }
16801
16802 if (ME->getMemberDecl()->isCXXInstanceMember())
16803 break;
16804
16805 // -- If e is a class member access expression naming a static data member,
16806 // ...
16807 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
16808 break;
16809
16810 // Rebuild as a non-odr-use MemberExpr.
16811 MarkNotOdrUsed();
16812 return MemberExpr::Create(
16813 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
16814 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
16815 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
16816 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
16817 return ExprEmpty();
16818 }
16819
16820 case Expr::BinaryOperatorClass: {
16821 auto *BO = cast<BinaryOperator>(E);
16822 Expr *LHS = BO->getLHS();
16823 Expr *RHS = BO->getRHS();
16824 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
16825 if (BO->getOpcode() == BO_PtrMemD) {
16826 ExprResult Sub = Rebuild(LHS);
16827 if (!Sub.isUsable())
16828 return Sub;
16829 LHS = Sub.get();
16830 // -- If e is a comma expression, ...
16831 } else if (BO->getOpcode() == BO_Comma) {
16832 ExprResult Sub = Rebuild(RHS);
16833 if (!Sub.isUsable())
16834 return Sub;
16835 RHS = Sub.get();
16836 } else {
16837 break;
16838 }
16839 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
16840 LHS, RHS);
16841 }
16842
16843 // -- If e has the form (e1)...
16844 case Expr::ParenExprClass: {
16845 auto *PE = cast<ParenExpr>(E);
16846 ExprResult Sub = Rebuild(PE->getSubExpr());
16847 if (!Sub.isUsable())
16848 return Sub;
16849 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
16850 }
16851
16852 // -- If e is a glvalue conditional expression, ...
16853 // We don't apply this to a binary conditional operator. FIXME: Should we?
16854 case Expr::ConditionalOperatorClass: {
16855 auto *CO = cast<ConditionalOperator>(E);
16856 ExprResult LHS = Rebuild(CO->getLHS());
16857 if (LHS.isInvalid())
16858 return ExprError();
16859 ExprResult RHS = Rebuild(CO->getRHS());
16860 if (RHS.isInvalid())
16861 return ExprError();
16862 if (!LHS.isUsable() && !RHS.isUsable())
16863 return ExprEmpty();
16864 if (!LHS.isUsable())
16865 LHS = CO->getLHS();
16866 if (!RHS.isUsable())
16867 RHS = CO->getRHS();
16868 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
16869 CO->getCond(), LHS.get(), RHS.get());
16870 }
16871
16872 // [Clang extension]
16873 // -- If e has the form __extension__ e1...
16874 case Expr::UnaryOperatorClass: {
16875 auto *UO = cast<UnaryOperator>(E);
16876 if (UO->getOpcode() != UO_Extension)
16877 break;
16878 ExprResult Sub = Rebuild(UO->getSubExpr());
16879 if (!Sub.isUsable())
16880 return Sub;
16881 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
16882 Sub.get());
16883 }
16884
16885 // [Clang extension]
16886 // -- If e has the form _Generic(...), the set of potential results is the
16887 // union of the sets of potential results of the associated expressions.
16888 case Expr::GenericSelectionExprClass: {
16889 auto *GSE = cast<GenericSelectionExpr>(E);
16890
16891 SmallVector<Expr *, 4> AssocExprs;
16892 bool AnyChanged = false;
16893 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
16894 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
16895 if (AssocExpr.isInvalid())
16896 return ExprError();
16897 if (AssocExpr.isUsable()) {
16898 AssocExprs.push_back(AssocExpr.get());
16899 AnyChanged = true;
16900 } else {
16901 AssocExprs.push_back(OrigAssocExpr);
16902 }
16903 }
16904
16905 return AnyChanged ? S.CreateGenericSelectionExpr(
16906 GSE->getGenericLoc(), GSE->getDefaultLoc(),
16907 GSE->getRParenLoc(), GSE->getControllingExpr(),
16908 GSE->getAssocTypeSourceInfos(), AssocExprs)
16909 : ExprEmpty();
16910 }
16911
16912 // [Clang extension]
16913 // -- If e has the form __builtin_choose_expr(...), the set of potential
16914 // results is the union of the sets of potential results of the
16915 // second and third subexpressions.
16916 case Expr::ChooseExprClass: {
16917 auto *CE = cast<ChooseExpr>(E);
16918
16919 ExprResult LHS = Rebuild(CE->getLHS());
16920 if (LHS.isInvalid())
16921 return ExprError();
16922
16923 ExprResult RHS = Rebuild(CE->getLHS());
16924 if (RHS.isInvalid())
16925 return ExprError();
16926
16927 if (!LHS.get() && !RHS.get())
16928 return ExprEmpty();
16929 if (!LHS.isUsable())
16930 LHS = CE->getLHS();
16931 if (!RHS.isUsable())
16932 RHS = CE->getRHS();
16933
16934 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
16935 RHS.get(), CE->getRParenLoc());
16936 }
16937
16938 // Step through non-syntactic nodes.
16939 case Expr::ConstantExprClass: {
16940 auto *CE = cast<ConstantExpr>(E);
16941 ExprResult Sub = Rebuild(CE->getSubExpr());
16942 if (!Sub.isUsable())
16943 return Sub;
16944 return ConstantExpr::Create(S.Context, Sub.get());
16945 }
16946
16947 // We could mostly rely on the recursive rebuilding to rebuild implicit
16948 // casts, but not at the top level, so rebuild them here.
16949 case Expr::ImplicitCastExprClass: {
16950 auto *ICE = cast<ImplicitCastExpr>(E);
16951 // Only step through the narrow set of cast kinds we expect to encounter.
16952 // Anything else suggests we've left the region in which potential results
16953 // can be found.
16954 switch (ICE->getCastKind()) {
16955 case CK_NoOp:
16956 case CK_DerivedToBase:
16957 case CK_UncheckedDerivedToBase: {
16958 ExprResult Sub = Rebuild(ICE->getSubExpr());
16959 if (!Sub.isUsable())
16960 return Sub;
16961 CXXCastPath Path(ICE->path());
16962 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
16963 ICE->getValueKind(), &Path);
16964 }
16965
16966 default:
16967 break;
16968 }
16969 break;
16970 }
16971
16972 default:
16973 break;
16974 }
16975
16976 // Can't traverse through this node. Nothing to do.
16977 return ExprEmpty();
16978}
16979
16980ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
16981 // Check whether the operand is or contains an object of non-trivial C union
16982 // type.
16983 if (E->getType().isVolatileQualified() &&
16984 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
16985 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
16986 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
16987 Sema::NTCUC_LValueToRValueVolatile,
16988 NTCUK_Destruct|NTCUK_Copy);
16989
16990 // C++2a [basic.def.odr]p4:
16991 // [...] an expression of non-volatile-qualified non-class type to which
16992 // the lvalue-to-rvalue conversion is applied [...]
16993 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
16994 return E;
16995
16996 ExprResult Result =
16997 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
16998 if (Result.isInvalid())
16999 return ExprError();
17000 return Result.get() ? Result : E;
17001}
17002
17003ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
17004 Res = CorrectDelayedTyposInExpr(Res);
17005
17006 if (!Res.isUsable())
17007 return Res;
17008
17009 // If a constant-expression is a reference to a variable where we delay
17010 // deciding whether it is an odr-use, just assume we will apply the
17011 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
17012 // (a non-type template argument), we have special handling anyway.
17013 return CheckLValueToRValueConversionOperand(Res.get());
17014}
17015
17016void Sema::CleanupVarDeclMarking() {
17017 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
17018 // call.
17019 MaybeODRUseExprSet LocalMaybeODRUseExprs;
17020 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
17021
17022 for (Expr *E : LocalMaybeODRUseExprs) {
17023 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
17024 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
17025 DRE->getLocation(), *this);
17026 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
17027 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
17028 *this);
17029 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
17030 for (VarDecl *VD : *FP)
17031 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
17032 } else {
17033 llvm_unreachable("Unexpected expression")::llvm::llvm_unreachable_internal("Unexpected expression", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17033)
;
17034 }
17035 }
17036
17037 assert(MaybeODRUseExprs.empty() &&((MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"
) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17038, __PRETTY_FUNCTION__))
17038 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?")((MaybeODRUseExprs.empty() && "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?"
) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17038, __PRETTY_FUNCTION__))
;
17039}
17040
17041static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
17042 VarDecl *Var, Expr *E) {
17043 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E
) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced"
) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17045, __PRETTY_FUNCTION__))
17044 isa<FunctionParmPackExpr>(E)) &&(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E
) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced"
) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17045, __PRETTY_FUNCTION__))
17045 "Invalid Expr argument to DoMarkVarDeclReferenced")(((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E
) || isa<FunctionParmPackExpr>(E)) && "Invalid Expr argument to DoMarkVarDeclReferenced"
) ? static_cast<void> (0) : __assert_fail ("(!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) || isa<FunctionParmPackExpr>(E)) && \"Invalid Expr argument to DoMarkVarDeclReferenced\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17045, __PRETTY_FUNCTION__))
;
17046 Var->setReferenced();
17047
17048 if (Var->isInvalidDecl())
17049 return;
17050
17051 auto *MSI = Var->getMemberSpecializationInfo();
17052 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
17053 : Var->getTemplateSpecializationKind();
17054
17055 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
17056 bool UsableInConstantExpr =
17057 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
17058
17059 // C++20 [expr.const]p12:
17060 // A variable [...] is needed for constant evaluation if it is [...] a
17061 // variable whose name appears as a potentially constant evaluated
17062 // expression that is either a contexpr variable or is of non-volatile
17063 // const-qualified integral type or of reference type
17064 bool NeededForConstantEvaluation =
17065 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
17066
17067 bool NeedDefinition =
17068 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
17069
17070 VarTemplateSpecializationDecl *VarSpec =
17071 dyn_cast<VarTemplateSpecializationDecl>(Var);
17072 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&((!isa<VarTemplatePartialSpecializationDecl>(Var) &&
"Can't instantiate a partial template specialization.") ? static_cast
<void> (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17073, __PRETTY_FUNCTION__))
17073 "Can't instantiate a partial template specialization.")((!isa<VarTemplatePartialSpecializationDecl>(Var) &&
"Can't instantiate a partial template specialization.") ? static_cast
<void> (0) : __assert_fail ("!isa<VarTemplatePartialSpecializationDecl>(Var) && \"Can't instantiate a partial template specialization.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17073, __PRETTY_FUNCTION__))
;
17074
17075 // If this might be a member specialization of a static data member, check
17076 // the specialization is visible. We already did the checks for variable
17077 // template specializations when we created them.
17078 if (NeedDefinition && TSK != TSK_Undeclared &&
17079 !isa<VarTemplateSpecializationDecl>(Var))
17080 SemaRef.checkSpecializationVisibility(Loc, Var);
17081
17082 // Perform implicit instantiation of static data members, static data member
17083 // templates of class templates, and variable template specializations. Delay
17084 // instantiations of variable templates, except for those that could be used
17085 // in a constant expression.
17086 if (NeedDefinition && isTemplateInstantiation(TSK)) {
17087 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
17088 // instantiation declaration if a variable is usable in a constant
17089 // expression (among other cases).
17090 bool TryInstantiating =
17091 TSK == TSK_ImplicitInstantiation ||
17092 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
17093
17094 if (TryInstantiating) {
17095 SourceLocation PointOfInstantiation =
17096 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
17097 bool FirstInstantiation = PointOfInstantiation.isInvalid();
17098 if (FirstInstantiation) {
17099 PointOfInstantiation = Loc;
17100 if (MSI)
17101 MSI->setPointOfInstantiation(PointOfInstantiation);
17102 else
17103 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17104 }
17105
17106 bool InstantiationDependent = false;
17107 bool IsNonDependent =
17108 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
17109 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
17110 : true;
17111
17112 // Do not instantiate specializations that are still type-dependent.
17113 if (IsNonDependent) {
17114 if (UsableInConstantExpr) {
17115 // Do not defer instantiations of variables that could be used in a
17116 // constant expression.
17117 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
17118 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
17119 });
17120 } else if (FirstInstantiation ||
17121 isa<VarTemplateSpecializationDecl>(Var)) {
17122 // FIXME: For a specialization of a variable template, we don't
17123 // distinguish between "declaration and type implicitly instantiated"
17124 // and "implicit instantiation of definition requested", so we have
17125 // no direct way to avoid enqueueing the pending instantiation
17126 // multiple times.
17127 SemaRef.PendingInstantiations
17128 .push_back(std::make_pair(Var, PointOfInstantiation));
17129 }
17130 }
17131 }
17132 }
17133
17134 // C++2a [basic.def.odr]p4:
17135 // A variable x whose name appears as a potentially-evaluated expression e
17136 // is odr-used by e unless
17137 // -- x is a reference that is usable in constant expressions
17138 // -- x is a variable of non-reference type that is usable in constant
17139 // expressions and has no mutable subobjects [FIXME], and e is an
17140 // element of the set of potential results of an expression of
17141 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
17142 // conversion is applied
17143 // -- x is a variable of non-reference type, and e is an element of the set
17144 // of potential results of a discarded-value expression to which the
17145 // lvalue-to-rvalue conversion is not applied [FIXME]
17146 //
17147 // We check the first part of the second bullet here, and
17148 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
17149 // FIXME: To get the third bullet right, we need to delay this even for
17150 // variables that are not usable in constant expressions.
17151
17152 // If we already know this isn't an odr-use, there's nothing more to do.
17153 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
17154 if (DRE->isNonOdrUse())
17155 return;
17156 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
17157 if (ME->isNonOdrUse())
17158 return;
17159
17160 switch (OdrUse) {
17161 case OdrUseContext::None:
17162 assert((!E || isa<FunctionParmPackExpr>(E)) &&(((!E || isa<FunctionParmPackExpr>(E)) && "missing non-odr-use marking for unevaluated decl ref"
) ? static_cast<void> (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17163, __PRETTY_FUNCTION__))
17163 "missing non-odr-use marking for unevaluated decl ref")(((!E || isa<FunctionParmPackExpr>(E)) && "missing non-odr-use marking for unevaluated decl ref"
) ? static_cast<void> (0) : __assert_fail ("(!E || isa<FunctionParmPackExpr>(E)) && \"missing non-odr-use marking for unevaluated decl ref\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17163, __PRETTY_FUNCTION__))
;
17164 break;
17165
17166 case OdrUseContext::FormallyOdrUsed:
17167 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
17168 // behavior.
17169 break;
17170
17171 case OdrUseContext::Used:
17172 // If we might later find that this expression isn't actually an odr-use,
17173 // delay the marking.
17174 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
17175 SemaRef.MaybeODRUseExprs.insert(E);
17176 else
17177 MarkVarDeclODRUsed(Var, Loc, SemaRef);
17178 break;
17179
17180 case OdrUseContext::Dependent:
17181 // If this is a dependent context, we don't need to mark variables as
17182 // odr-used, but we may still need to track them for lambda capture.
17183 // FIXME: Do we also need to do this inside dependent typeid expressions
17184 // (which are modeled as unevaluated at this point)?
17185 const bool RefersToEnclosingScope =
17186 (SemaRef.CurContext != Var->getDeclContext() &&
17187 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
17188 if (RefersToEnclosingScope) {
17189 LambdaScopeInfo *const LSI =
17190 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
17191 if (LSI && (!LSI->CallOperator ||
17192 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
17193 // If a variable could potentially be odr-used, defer marking it so
17194 // until we finish analyzing the full expression for any
17195 // lvalue-to-rvalue
17196 // or discarded value conversions that would obviate odr-use.
17197 // Add it to the list of potential captures that will be analyzed
17198 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
17199 // unless the variable is a reference that was initialized by a constant
17200 // expression (this will never need to be captured or odr-used).
17201 //
17202 // FIXME: We can simplify this a lot after implementing P0588R1.
17203 assert(E && "Capture variable should be used in an expression.")((E && "Capture variable should be used in an expression."
) ? static_cast<void> (0) : __assert_fail ("E && \"Capture variable should be used in an expression.\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17203, __PRETTY_FUNCTION__))
;
17204 if (!Var->getType()->isReferenceType() ||
17205 !Var->isUsableInConstantExpressions(SemaRef.Context))
17206 LSI->addPotentialCapture(E->IgnoreParens());
17207 }
17208 }
17209 break;
17210 }
17211}
17212
17213/// Mark a variable referenced, and check whether it is odr-used
17214/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
17215/// used directly for normal expressions referring to VarDecl.
17216void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
17217 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
17218}
17219
17220static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
17221 Decl *D, Expr *E, bool MightBeOdrUse) {
17222 if (SemaRef.isInOpenMPDeclareTargetContext())
17223 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
17224
17225 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
17226 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
17227 return;
17228 }
17229
17230 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
17231
17232 // If this is a call to a method via a cast, also mark the method in the
17233 // derived class used in case codegen can devirtualize the call.
17234 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
17235 if (!ME)
17236 return;
17237 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
17238 if (!MD)
17239 return;
17240 // Only attempt to devirtualize if this is truly a virtual call.
17241 bool IsVirtualCall = MD->isVirtual() &&
17242 ME->performsVirtualDispatch(SemaRef.getLangOpts());
17243 if (!IsVirtualCall)
17244 return;
17245
17246 // If it's possible to devirtualize the call, mark the called function
17247 // referenced.
17248 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
17249 ME->getBase(), SemaRef.getLangOpts().AppleKext);
17250 if (DM)
17251 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
17252}
17253
17254/// Perform reference-marking and odr-use handling for a DeclRefExpr.
17255void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
17256 // TODO: update this with DR# once a defect report is filed.
17257 // C++11 defect. The address of a pure member should not be an ODR use, even
17258 // if it's a qualified reference.
17259 bool OdrUse = true;
17260 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
17261 if (Method->isVirtual() &&
17262 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
17263 OdrUse = false;
17264
17265 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
17266 if (!isConstantEvaluated() && FD->isConsteval() &&
17267 !RebuildingImmediateInvocation)
17268 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
17269 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
17270}
17271
17272/// Perform reference-marking and odr-use handling for a MemberExpr.
17273void Sema::MarkMemberReferenced(MemberExpr *E) {
17274 // C++11 [basic.def.odr]p2:
17275 // A non-overloaded function whose name appears as a potentially-evaluated
17276 // expression or a member of a set of candidate functions, if selected by
17277 // overload resolution when referred to from a potentially-evaluated
17278 // expression, is odr-used, unless it is a pure virtual function and its
17279 // name is not explicitly qualified.
17280 bool MightBeOdrUse = true;
17281 if (E->performsVirtualDispatch(getLangOpts())) {
17282 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
17283 if (Method->isPure())
17284 MightBeOdrUse = false;
17285 }
17286 SourceLocation Loc =
17287 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
17288 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
17289}
17290
17291/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
17292void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
17293 for (VarDecl *VD : *E)
17294 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
17295}
17296
17297/// Perform marking for a reference to an arbitrary declaration. It
17298/// marks the declaration referenced, and performs odr-use checking for
17299/// functions and variables. This method should not be used when building a
17300/// normal expression which refers to a variable.
17301void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
17302 bool MightBeOdrUse) {
17303 if (MightBeOdrUse) {
17304 if (auto *VD = dyn_cast<VarDecl>(D)) {
17305 MarkVariableReferenced(Loc, VD);
17306 return;
17307 }
17308 }
17309 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
17310 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
17311 return;
17312 }
17313 D->setReferenced();
17314}
17315
17316namespace {
17317 // Mark all of the declarations used by a type as referenced.
17318 // FIXME: Not fully implemented yet! We need to have a better understanding
17319 // of when we're entering a context we should not recurse into.
17320 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
17321 // TreeTransforms rebuilding the type in a new context. Rather than
17322 // duplicating the TreeTransform logic, we should consider reusing it here.
17323 // Currently that causes problems when rebuilding LambdaExprs.
17324 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
17325 Sema &S;
17326 SourceLocation Loc;
17327
17328 public:
17329 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
17330
17331 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
17332
17333 bool TraverseTemplateArgument(const TemplateArgument &Arg);
17334 };
17335}
17336
17337bool MarkReferencedDecls::TraverseTemplateArgument(
17338 const TemplateArgument &Arg) {
17339 {
17340 // A non-type template argument is a constant-evaluated context.
17341 EnterExpressionEvaluationContext Evaluated(
17342 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
17343 if (Arg.getKind() == TemplateArgument::Declaration) {
17344 if (Decl *D = Arg.getAsDecl())
17345 S.MarkAnyDeclReferenced(Loc, D, true);
17346 } else if (Arg.getKind() == TemplateArgument::Expression) {
17347 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
17348 }
17349 }
17350
17351 return Inherited::TraverseTemplateArgument(Arg);
17352}
17353
17354void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
17355 MarkReferencedDecls Marker(*this, Loc);
17356 Marker.TraverseType(T);
17357}
17358
17359namespace {
17360 /// Helper class that marks all of the declarations referenced by
17361 /// potentially-evaluated subexpressions as "referenced".
17362 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
17363 Sema &S;
17364 bool SkipLocalVariables;
17365
17366 public:
17367 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
17368
17369 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
17370 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
17371
17372 void VisitDeclRefExpr(DeclRefExpr *E) {
17373 // If we were asked not to visit local variables, don't.
17374 if (SkipLocalVariables) {
17375 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
17376 if (VD->hasLocalStorage())
17377 return;
17378 }
17379
17380 S.MarkDeclRefReferenced(E);
17381 }
17382
17383 void VisitMemberExpr(MemberExpr *E) {
17384 S.MarkMemberReferenced(E);
17385 Inherited::VisitMemberExpr(E);
17386 }
17387
17388 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
17389 S.MarkFunctionReferenced(
17390 E->getBeginLoc(),
17391 const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
17392 Visit(E->getSubExpr());
17393 }
17394
17395 void VisitCXXNewExpr(CXXNewExpr *E) {
17396 if (E->getOperatorNew())
17397 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
17398 if (E->getOperatorDelete())
17399 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
17400 Inherited::VisitCXXNewExpr(E);
17401 }
17402
17403 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
17404 if (E->getOperatorDelete())
17405 S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
17406 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
17407 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
17408 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
17409 S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
17410 }
17411
17412 Inherited::VisitCXXDeleteExpr(E);
17413 }
17414
17415 void VisitCXXConstructExpr(CXXConstructExpr *E) {
17416 S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
17417 Inherited::VisitCXXConstructExpr(E);
17418 }
17419
17420 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
17421 Visit(E->getExpr());
17422 }
17423 };
17424}
17425
17426/// Mark any declarations that appear within this expression or any
17427/// potentially-evaluated subexpressions as "referenced".
17428///
17429/// \param SkipLocalVariables If true, don't mark local variables as
17430/// 'referenced'.
17431void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
17432 bool SkipLocalVariables) {
17433 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
17434}
17435
17436/// Emit a diagnostic that describes an effect on the run-time behavior
17437/// of the program being compiled.
17438///
17439/// This routine emits the given diagnostic when the code currently being
17440/// type-checked is "potentially evaluated", meaning that there is a
17441/// possibility that the code will actually be executable. Code in sizeof()
17442/// expressions, code used only during overload resolution, etc., are not
17443/// potentially evaluated. This routine will suppress such diagnostics or,
17444/// in the absolutely nutty case of potentially potentially evaluated
17445/// expressions (C++ typeid), queue the diagnostic to potentially emit it
17446/// later.
17447///
17448/// This routine should be used for all diagnostics that describe the run-time
17449/// behavior of a program, such as passing a non-POD value through an ellipsis.
17450/// Failure to do so will likely result in spurious diagnostics or failures
17451/// during overload resolution or within sizeof/alignof/typeof/typeid.
17452bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
17453 const PartialDiagnostic &PD) {
17454 switch (ExprEvalContexts.back().Context) {
17455 case ExpressionEvaluationContext::Unevaluated:
17456 case ExpressionEvaluationContext::UnevaluatedList:
17457 case ExpressionEvaluationContext::UnevaluatedAbstract:
17458 case ExpressionEvaluationContext::DiscardedStatement:
17459 // The argument will never be evaluated, so don't complain.
17460 break;
17461
17462 case ExpressionEvaluationContext::ConstantEvaluated:
17463 // Relevant diagnostics should be produced by constant evaluation.
17464 break;
17465
17466 case ExpressionEvaluationContext::PotentiallyEvaluated:
17467 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
17468 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
17469 FunctionScopes.back()->PossiblyUnreachableDiags.
17470 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
17471 return true;
17472 }
17473
17474 // The initializer of a constexpr variable or of the first declaration of a
17475 // static data member is not syntactically a constant evaluated constant,
17476 // but nonetheless is always required to be a constant expression, so we
17477 // can skip diagnosing.
17478 // FIXME: Using the mangling context here is a hack.
17479 if (auto *VD = dyn_cast_or_null<VarDecl>(
17480 ExprEvalContexts.back().ManglingContextDecl)) {
17481 if (VD->isConstexpr() ||
17482 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
17483 break;
17484 // FIXME: For any other kind of variable, we should build a CFG for its
17485 // initializer and check whether the context in question is reachable.
17486 }
17487
17488 Diag(Loc, PD);
17489 return true;
17490 }
17491
17492 return false;
17493}
17494
17495bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
17496 const PartialDiagnostic &PD) {
17497 return DiagRuntimeBehavior(
17498 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
17499}
17500
17501bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
17502 CallExpr *CE, FunctionDecl *FD) {
17503 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
17504 return false;
17505
17506 // If we're inside a decltype's expression, don't check for a valid return
17507 // type or construct temporaries until we know whether this is the last call.
17508 if (ExprEvalContexts.back().ExprContext ==
17509 ExpressionEvaluationContextRecord::EK_Decltype) {
17510 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
17511 return false;
17512 }
17513
17514 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
17515 FunctionDecl *FD;
17516 CallExpr *CE;
17517
17518 public:
17519 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
17520 : FD(FD), CE(CE) { }
17521
17522 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17523 if (!FD) {
17524 S.Diag(Loc, diag::err_call_incomplete_return)
17525 << T << CE->getSourceRange();
17526 return;
17527 }
17528
17529 S.Diag(Loc, diag::err_call_function_incomplete_return)
17530 << CE->getSourceRange() << FD->getDeclName() << T;
17531 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
17532 << FD->getDeclName();
17533 }
17534 } Diagnoser(FD, CE);
17535
17536 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
17537 return true;
17538
17539 return false;
17540}
17541
17542// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
17543// will prevent this condition from triggering, which is what we want.
17544void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
17545 SourceLocation Loc;
17546
17547 unsigned diagnostic = diag::warn_condition_is_assignment;
17548 bool IsOrAssign = false;
17549
17550 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
17551 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
17552 return;
17553
17554 IsOrAssign = Op->getOpcode() == BO_OrAssign;
17555
17556 // Greylist some idioms by putting them into a warning subcategory.
17557 if (ObjCMessageExpr *ME
17558 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
17559 Selector Sel = ME->getSelector();
17560
17561 // self = [<foo> init...]
17562 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
17563 diagnostic = diag::warn_condition_is_idiomatic_assignment;
17564
17565 // <foo> = [<bar> nextObject]
17566 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
17567 diagnostic = diag::warn_condition_is_idiomatic_assignment;
17568 }
17569
17570 Loc = Op->getOperatorLoc();
17571 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
17572 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
17573 return;
17574
17575 IsOrAssign = Op->getOperator() == OO_PipeEqual;
17576 Loc = Op->getOperatorLoc();
17577 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
17578 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
17579 else {
17580 // Not an assignment.
17581 return;
17582 }
17583
17584 Diag(Loc, diagnostic) << E->getSourceRange();
17585
17586 SourceLocation Open = E->getBeginLoc();
17587 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
17588 Diag(Loc, diag::note_condition_assign_silence)
17589 << FixItHint::CreateInsertion(Open, "(")
17590 << FixItHint::CreateInsertion(Close, ")");
17591
17592 if (IsOrAssign)
17593 Diag(Loc, diag::note_condition_or_assign_to_comparison)
17594 << FixItHint::CreateReplacement(Loc, "!=");
17595 else
17596 Diag(Loc, diag::note_condition_assign_to_comparison)
17597 << FixItHint::CreateReplacement(Loc, "==");
17598}
17599
17600/// Redundant parentheses over an equality comparison can indicate
17601/// that the user intended an assignment used as condition.
17602void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
17603 // Don't warn if the parens came from a macro.
17604 SourceLocation parenLoc = ParenE->getBeginLoc();
17605 if (parenLoc.isInvalid() || parenLoc.isMacroID())
17606 return;
17607 // Don't warn for dependent expressions.
17608 if (ParenE->isTypeDependent())
17609 return;
17610
17611 Expr *E = ParenE->IgnoreParens();
17612
17613 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
17614 if (opE->getOpcode() == BO_EQ &&
17615 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
17616 == Expr::MLV_Valid) {
17617 SourceLocation Loc = opE->getOperatorLoc();
17618
17619 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
17620 SourceRange ParenERange = ParenE->getSourceRange();
17621 Diag(Loc, diag::note_equality_comparison_silence)
17622 << FixItHint::CreateRemoval(ParenERange.getBegin())
17623 << FixItHint::CreateRemoval(ParenERange.getEnd());
17624 Diag(Loc, diag::note_equality_comparison_to_assign)
17625 << FixItHint::CreateReplacement(Loc, "=");
17626 }
17627}
17628
17629ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
17630 bool IsConstexpr) {
17631 DiagnoseAssignmentAsCondition(E);
17632 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
17633 DiagnoseEqualityWithExtraParens(parenE);
17634
17635 ExprResult result = CheckPlaceholderExpr(E);
17636 if (result.isInvalid()) return ExprError();
17637 E = result.get();
17638
17639 if (!E->isTypeDependent()) {
17640 if (getLangOpts().CPlusPlus)
17641 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
17642
17643 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
17644 if (ERes.isInvalid())
17645 return ExprError();
17646 E = ERes.get();
17647
17648 QualType T = E->getType();
17649 if (!T->isScalarType()) { // C99 6.8.4.1p1
17650 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
17651 << T << E->getSourceRange();
17652 return ExprError();
17653 }
17654 CheckBoolLikeConversion(E, Loc);
17655 }
17656
17657 return E;
17658}
17659
17660Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
17661 Expr *SubExpr, ConditionKind CK) {
17662 // Empty conditions are valid in for-statements.
17663 if (!SubExpr)
17664 return ConditionResult();
17665
17666 ExprResult Cond;
17667 switch (CK) {
17668 case ConditionKind::Boolean:
17669 Cond = CheckBooleanCondition(Loc, SubExpr);
17670 break;
17671
17672 case ConditionKind::ConstexprIf:
17673 Cond = CheckBooleanCondition(Loc, SubExpr, true);
17674 break;
17675
17676 case ConditionKind::Switch:
17677 Cond = CheckSwitchCondition(Loc, SubExpr);
17678 break;
17679 }
17680 if (Cond.isInvalid())
17681 return ConditionError();
17682
17683 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
17684 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
17685 if (!FullExpr.get())
17686 return ConditionError();
17687
17688 return ConditionResult(*this, nullptr, FullExpr,
17689 CK == ConditionKind::ConstexprIf);
17690}
17691
17692namespace {
17693 /// A visitor for rebuilding a call to an __unknown_any expression
17694 /// to have an appropriate type.
17695 struct RebuildUnknownAnyFunction
17696 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
17697
17698 Sema &S;
17699
17700 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
17701
17702 ExprResult VisitStmt(Stmt *S) {
17703 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17703)
;
17704 }
17705
17706 ExprResult VisitExpr(Expr *E) {
17707 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
17708 << E->getSourceRange();
17709 return ExprError();
17710 }
17711
17712 /// Rebuild an expression which simply semantically wraps another
17713 /// expression which it shares the type and value kind of.
17714 template <class T> ExprResult rebuildSugarExpr(T *E) {
17715 ExprResult SubResult = Visit(E->getSubExpr());
17716 if (SubResult.isInvalid()) return ExprError();
17717
17718 Expr *SubExpr = SubResult.get();
17719 E->setSubExpr(SubExpr);
17720 E->setType(SubExpr->getType());
17721 E->setValueKind(SubExpr->getValueKind());
17722 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17722, __PRETTY_FUNCTION__))
;
17723 return E;
17724 }
17725
17726 ExprResult VisitParenExpr(ParenExpr *E) {
17727 return rebuildSugarExpr(E);
17728 }
17729
17730 ExprResult VisitUnaryExtension(UnaryOperator *E) {
17731 return rebuildSugarExpr(E);
17732 }
17733
17734 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17735 ExprResult SubResult = Visit(E->getSubExpr());
17736 if (SubResult.isInvalid()) return ExprError();
17737
17738 Expr *SubExpr = SubResult.get();
17739 E->setSubExpr(SubExpr);
17740 E->setType(S.Context.getPointerType(SubExpr->getType()));
17741 assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void>
(0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17741, __PRETTY_FUNCTION__))
;
17742 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17742, __PRETTY_FUNCTION__))
;
17743 return E;
17744 }
17745
17746 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
17747 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
17748
17749 E->setType(VD->getType());
17750
17751 assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void>
(0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17751, __PRETTY_FUNCTION__))
;
17752 if (S.getLangOpts().CPlusPlus &&
17753 !(isa<CXXMethodDecl>(VD) &&
17754 cast<CXXMethodDecl>(VD)->isInstance()))
17755 E->setValueKind(VK_LValue);
17756
17757 return E;
17758 }
17759
17760 ExprResult VisitMemberExpr(MemberExpr *E) {
17761 return resolveDecl(E, E->getMemberDecl());
17762 }
17763
17764 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17765 return resolveDecl(E, E->getDecl());
17766 }
17767 };
17768}
17769
17770/// Given a function expression of unknown-any type, try to rebuild it
17771/// to have a function type.
17772static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
17773 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
17774 if (Result.isInvalid()) return ExprError();
17775 return S.DefaultFunctionArrayConversion(Result.get());
17776}
17777
17778namespace {
17779 /// A visitor for rebuilding an expression of type __unknown_anytype
17780 /// into one which resolves the type directly on the referring
17781 /// expression. Strict preservation of the original source
17782 /// structure is not a goal.
17783 struct RebuildUnknownAnyExpr
17784 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
17785
17786 Sema &S;
17787
17788 /// The current destination type.
17789 QualType DestType;
17790
17791 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
17792 : S(S), DestType(CastType) {}
17793
17794 ExprResult VisitStmt(Stmt *S) {
17795 llvm_unreachable("unexpected statement!")::llvm::llvm_unreachable_internal("unexpected statement!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17795)
;
17796 }
17797
17798 ExprResult VisitExpr(Expr *E) {
17799 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
17800 << E->getSourceRange();
17801 return ExprError();
17802 }
17803
17804 ExprResult VisitCallExpr(CallExpr *E);
17805 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
17806
17807 /// Rebuild an expression which simply semantically wraps another
17808 /// expression which it shares the type and value kind of.
17809 template <class T> ExprResult rebuildSugarExpr(T *E) {
17810 ExprResult SubResult = Visit(E->getSubExpr());
17811 if (SubResult.isInvalid()) return ExprError();
17812 Expr *SubExpr = SubResult.get();
17813 E->setSubExpr(SubExpr);
17814 E->setType(SubExpr->getType());
17815 E->setValueKind(SubExpr->getValueKind());
17816 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17816, __PRETTY_FUNCTION__))
;
17817 return E;
17818 }
17819
17820 ExprResult VisitParenExpr(ParenExpr *E) {
17821 return rebuildSugarExpr(E);
17822 }
17823
17824 ExprResult VisitUnaryExtension(UnaryOperator *E) {
17825 return rebuildSugarExpr(E);
17826 }
17827
17828 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
17829 const PointerType *Ptr = DestType->getAs<PointerType>();
17830 if (!Ptr) {
17831 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
17832 << E->getSourceRange();
17833 return ExprError();
17834 }
17835
17836 if (isa<CallExpr>(E->getSubExpr())) {
17837 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
17838 << E->getSourceRange();
17839 return ExprError();
17840 }
17841
17842 assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void>
(0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17842, __PRETTY_FUNCTION__))
;
17843 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17843, __PRETTY_FUNCTION__))
;
17844 E->setType(DestType);
17845
17846 // Build the sub-expression as if it were an object of the pointee type.
17847 DestType = Ptr->getPointeeType();
17848 ExprResult SubResult = Visit(E->getSubExpr());
17849 if (SubResult.isInvalid()) return ExprError();
17850 E->setSubExpr(SubResult.get());
17851 return E;
17852 }
17853
17854 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
17855
17856 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
17857
17858 ExprResult VisitMemberExpr(MemberExpr *E) {
17859 return resolveDecl(E, E->getMemberDecl());
17860 }
17861
17862 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
17863 return resolveDecl(E, E->getDecl());
17864 }
17865 };
17866}
17867
17868/// Rebuilds a call expression which yielded __unknown_anytype.
17869ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
17870 Expr *CalleeExpr = E->getCallee();
17871
17872 enum FnKind {
17873 FK_MemberFunction,
17874 FK_FunctionPointer,
17875 FK_BlockPointer
17876 };
17877
17878 FnKind Kind;
17879 QualType CalleeType = CalleeExpr->getType();
17880 if (CalleeType == S.Context.BoundMemberTy) {
17881 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E))((isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr
>(E)) ? static_cast<void> (0) : __assert_fail ("isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E)"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17881, __PRETTY_FUNCTION__))
;
17882 Kind = FK_MemberFunction;
17883 CalleeType = Expr::findBoundMemberType(CalleeExpr);
17884 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
17885 CalleeType = Ptr->getPointeeType();
17886 Kind = FK_FunctionPointer;
17887 } else {
17888 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
17889 Kind = FK_BlockPointer;
17890 }
17891 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
17892
17893 // Verify that this is a legal result type of a function.
17894 if (DestType->isArrayType() || DestType->isFunctionType()) {
17895 unsigned diagID = diag::err_func_returning_array_function;
17896 if (Kind == FK_BlockPointer)
17897 diagID = diag::err_block_returning_array_function;
17898
17899 S.Diag(E->getExprLoc(), diagID)
17900 << DestType->isFunctionType() << DestType;
17901 return ExprError();
17902 }
17903
17904 // Otherwise, go ahead and set DestType as the call's result.
17905 E->setType(DestType.getNonLValueExprType(S.Context));
17906 E->setValueKind(Expr::getValueKindForType(DestType));
17907 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17907, __PRETTY_FUNCTION__))
;
17908
17909 // Rebuild the function type, replacing the result type with DestType.
17910 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
17911 if (Proto) {
17912 // __unknown_anytype(...) is a special case used by the debugger when
17913 // it has no idea what a function's signature is.
17914 //
17915 // We want to build this call essentially under the K&R
17916 // unprototyped rules, but making a FunctionNoProtoType in C++
17917 // would foul up all sorts of assumptions. However, we cannot
17918 // simply pass all arguments as variadic arguments, nor can we
17919 // portably just call the function under a non-variadic type; see
17920 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
17921 // However, it turns out that in practice it is generally safe to
17922 // call a function declared as "A foo(B,C,D);" under the prototype
17923 // "A foo(B,C,D,...);". The only known exception is with the
17924 // Windows ABI, where any variadic function is implicitly cdecl
17925 // regardless of its normal CC. Therefore we change the parameter
17926 // types to match the types of the arguments.
17927 //
17928 // This is a hack, but it is far superior to moving the
17929 // corresponding target-specific code from IR-gen to Sema/AST.
17930
17931 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
17932 SmallVector<QualType, 8> ArgTypes;
17933 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
17934 ArgTypes.reserve(E->getNumArgs());
17935 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
17936 Expr *Arg = E->getArg(i);
17937 QualType ArgType = Arg->getType();
17938 if (E->isLValue()) {
17939 ArgType = S.Context.getLValueReferenceType(ArgType);
17940 } else if (E->isXValue()) {
17941 ArgType = S.Context.getRValueReferenceType(ArgType);
17942 }
17943 ArgTypes.push_back(ArgType);
17944 }
17945 ParamTypes = ArgTypes;
17946 }
17947 DestType = S.Context.getFunctionType(DestType, ParamTypes,
17948 Proto->getExtProtoInfo());
17949 } else {
17950 DestType = S.Context.getFunctionNoProtoType(DestType,
17951 FnType->getExtInfo());
17952 }
17953
17954 // Rebuild the appropriate pointer-to-function type.
17955 switch (Kind) {
17956 case FK_MemberFunction:
17957 // Nothing to do.
17958 break;
17959
17960 case FK_FunctionPointer:
17961 DestType = S.Context.getPointerType(DestType);
17962 break;
17963
17964 case FK_BlockPointer:
17965 DestType = S.Context.getBlockPointerType(DestType);
17966 break;
17967 }
17968
17969 // Finally, we can recurse.
17970 ExprResult CalleeResult = Visit(CalleeExpr);
17971 if (!CalleeResult.isUsable()) return ExprError();
17972 E->setCallee(CalleeResult.get());
17973
17974 // Bind a temporary if necessary.
17975 return S.MaybeBindToTemporary(E);
17976}
17977
17978ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
17979 // Verify that this is a legal result type of a call.
17980 if (DestType->isArrayType() || DestType->isFunctionType()) {
17981 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
17982 << DestType->isFunctionType() << DestType;
17983 return ExprError();
17984 }
17985
17986 // Rewrite the method result type if available.
17987 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
17988 assert(Method->getReturnType() == S.Context.UnknownAnyTy)((Method->getReturnType() == S.Context.UnknownAnyTy) ? static_cast
<void> (0) : __assert_fail ("Method->getReturnType() == S.Context.UnknownAnyTy"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 17988, __PRETTY_FUNCTION__))
;
17989 Method->setReturnType(DestType);
17990 }
17991
17992 // Change the type of the message.
17993 E->setType(DestType.getNonReferenceType());
17994 E->setValueKind(Expr::getValueKindForType(DestType));
17995
17996 return S.MaybeBindToTemporary(E);
17997}
17998
17999ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
18000 // The only case we should ever see here is a function-to-pointer decay.
18001 if (E->getCastKind() == CK_FunctionToPointerDecay) {
18002 assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void>
(0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 18002, __PRETTY_FUNCTION__))
;
18003 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 18003, __PRETTY_FUNCTION__))
;
18004
18005 E->setType(DestType);
18006
18007 // Rebuild the sub-expression as the pointee (function) type.
18008 DestType = DestType->castAs<PointerType>()->getPointeeType();
18009
18010 ExprResult Result = Visit(E->getSubExpr());
18011 if (!Result.isUsable()) return ExprError();
18012
18013 E->setSubExpr(Result.get());
18014 return E;
18015 } else if (E->getCastKind() == CK_LValueToRValue) {
18016 assert(E->getValueKind() == VK_RValue)((E->getValueKind() == VK_RValue) ? static_cast<void>
(0) : __assert_fail ("E->getValueKind() == VK_RValue", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 18016, __PRETTY_FUNCTION__))
;
18017 assert(E->getObjectKind() == OK_Ordinary)((E->getObjectKind() == OK_Ordinary) ? static_cast<void
> (0) : __assert_fail ("E->getObjectKind() == OK_Ordinary"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 18017, __PRETTY_FUNCTION__))
;
18018
18019 assert(isa<BlockPointerType>(E->getType()))((isa<BlockPointerType>(E->getType())) ? static_cast
<void> (0) : __assert_fail ("isa<BlockPointerType>(E->getType())"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 18019, __PRETTY_FUNCTION__))
;
18020
18021 E->setType(DestType);
18022
18023 // The sub-expression has to be a lvalue reference, so rebuild it as such.
18024 DestType = S.Context.getLValueReferenceType(DestType);
18025
18026 ExprResult Result = Visit(E->getSubExpr());
18027 if (!Result.isUsable()) return ExprError();
18028
18029 E->setSubExpr(Result.get());
18030 return E;
18031 } else {
18032 llvm_unreachable("Unhandled cast type!")::llvm::llvm_unreachable_internal("Unhandled cast type!", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 18032)
;
18033 }
18034}
18035
18036ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
18037 ExprValueKind ValueKind = VK_LValue;
18038 QualType Type = DestType;
18039
18040 // We know how to make this work for certain kinds of decls:
18041
18042 // - functions
18043 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
18044 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
18045 DestType = Ptr->getPointeeType();
18046 ExprResult Result = resolveDecl(E, VD);
18047 if (Result.isInvalid()) return ExprError();
18048 return S.ImpCastExprToType(Result.get(), Type,
18049 CK_FunctionToPointerDecay, VK_RValue);
18050 }
18051
18052 if (!Type->isFunctionType()) {
18053 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
18054 << VD << E->getSourceRange();
18055 return ExprError();
18056 }
18057 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
18058 // We must match the FunctionDecl's type to the hack introduced in
18059 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
18060 // type. See the lengthy commentary in that routine.
18061 QualType FDT = FD->getType();
18062 const FunctionType *FnType = FDT->castAs<FunctionType>();
18063 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
18064 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
18065 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
18066 SourceLocation Loc = FD->getLocation();
18067 FunctionDecl *NewFD = FunctionDecl::Create(
18068 S.Context, FD->getDeclContext(), Loc, Loc,
18069 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
18070 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
18071 /*ConstexprKind*/ CSK_unspecified);
18072
18073 if (FD->getQualifier())
18074 NewFD->setQualifierInfo(FD->getQualifierLoc());
18075
18076 SmallVector<ParmVarDecl*, 16> Params;
18077 for (const auto &AI : FT->param_types()) {
18078 ParmVarDecl *Param =
18079 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
18080 Param->setScopeInfo(0, Params.size());
18081 Params.push_back(Param);
18082 }
18083 NewFD->setParams(Params);
18084 DRE->setDecl(NewFD);
18085 VD = DRE->getDecl();
18086 }
18087 }
18088
18089 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
18090 if (MD->isInstance()) {
18091 ValueKind = VK_RValue;
18092 Type = S.Context.BoundMemberTy;
18093 }
18094
18095 // Function references aren't l-values in C.
18096 if (!S.getLangOpts().CPlusPlus)
18097 ValueKind = VK_RValue;
18098
18099 // - variables
18100 } else if (isa<VarDecl>(VD)) {
18101 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
18102 Type = RefTy->getPointeeType();
18103 } else if (Type->isFunctionType()) {
18104 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
18105 << VD << E->getSourceRange();
18106 return ExprError();
18107 }
18108
18109 // - nothing else
18110 } else {
18111 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
18112 << VD << E->getSourceRange();
18113 return ExprError();
18114 }
18115
18116 // Modifying the declaration like this is friendly to IR-gen but
18117 // also really dangerous.
18118 VD->setType(DestType);
18119 E->setType(Type);
18120 E->setValueKind(ValueKind);
18121 return E;
18122}
18123
18124/// Check a cast of an unknown-any type. We intentionally only
18125/// trigger this for C-style casts.
18126ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
18127 Expr *CastExpr, CastKind &CastKind,
18128 ExprValueKind &VK, CXXCastPath &Path) {
18129 // The type we're casting to must be either void or complete.
18130 if (!CastType->isVoidType() &&
18131 RequireCompleteType(TypeRange.getBegin(), CastType,
18132 diag::err_typecheck_cast_to_incomplete))
18133 return ExprError();
18134
18135 // Rewrite the casted expression from scratch.
18136 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
18137 if (!result.isUsable()) return ExprError();
18138
18139 CastExpr = result.get();
18140 VK = CastExpr->getValueKind();
18141 CastKind = CK_NoOp;
18142
18143 return CastExpr;
18144}
18145
18146ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
18147 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
18148}
18149
18150ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
18151 Expr *arg, QualType &paramType) {
18152 // If the syntactic form of the argument is not an explicit cast of
18153 // any sort, just do default argument promotion.
18154 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
18155 if (!castArg) {
18156 ExprResult result = DefaultArgumentPromotion(arg);
18157 if (result.isInvalid()) return ExprError();
18158 paramType = result.get()->getType();
18159 return result;
18160 }
18161
18162 // Otherwise, use the type that was written in the explicit cast.
18163 assert(!arg->hasPlaceholderType())((!arg->hasPlaceholderType()) ? static_cast<void> (0
) : __assert_fail ("!arg->hasPlaceholderType()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 18163, __PRETTY_FUNCTION__))
;
18164 paramType = castArg->getTypeAsWritten();
18165
18166 // Copy-initialize a parameter of that type.
18167 InitializedEntity entity =
18168 InitializedEntity::InitializeParameter(Context, paramType,
18169 /*consumed*/ false);
18170 return PerformCopyInitialization(entity, callLoc, arg);
18171}
18172
18173static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
18174 Expr *orig = E;
18175 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
18176 while (true) {
18177 E = E->IgnoreParenImpCasts();
18178 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
18179 E = call->getCallee();
18180 diagID = diag::err_uncasted_call_of_unknown_any;
18181 } else {
18182 break;
18183 }
18184 }
18185
18186 SourceLocation loc;
18187 NamedDecl *d;
18188 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
18189 loc = ref->getLocation();
18190 d = ref->getDecl();
18191 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
18192 loc = mem->getMemberLoc();
18193 d = mem->getMemberDecl();
18194 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
18195 diagID = diag::err_uncasted_call_of_unknown_any;
18196 loc = msg->getSelectorStartLoc();
18197 d = msg->getMethodDecl();
18198 if (!d) {
18199 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
18200 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
18201 << orig->getSourceRange();
18202 return ExprError();
18203 }
18204 } else {
18205 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18206 << E->getSourceRange();
18207 return ExprError();
18208 }
18209
18210 S.Diag(loc, diagID) << d << orig->getSourceRange();
18211
18212 // Never recoverable.
18213 return ExprError();
18214}
18215
18216/// Check for operands with placeholder types and complain if found.
18217/// Returns ExprError() if there was an error and no recovery was possible.
18218ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
18219 if (!getLangOpts().CPlusPlus) {
18220 // C cannot handle TypoExpr nodes on either side of a binop because it
18221 // doesn't handle dependent types properly, so make sure any TypoExprs have
18222 // been dealt with before checking the operands.
18223 ExprResult Result = CorrectDelayedTyposInExpr(E);
18224 if (!Result.isUsable()) return ExprError();
18225 E = Result.get();
18226 }
18227
18228 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
18229 if (!placeholderType) return E;
18230
18231 switch (placeholderType->getKind()) {
18232
18233 // Overloaded expressions.
18234 case BuiltinType::Overload: {
18235 // Try to resolve a single function template specialization.
18236 // This is obligatory.
18237 ExprResult Result = E;
18238 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
18239 return Result;
18240
18241 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
18242 // leaves Result unchanged on failure.
18243 Result = E;
18244 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
18245 return Result;
18246
18247 // If that failed, try to recover with a call.
18248 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
18249 /*complain*/ true);
18250 return Result;
18251 }
18252
18253 // Bound member functions.
18254 case BuiltinType::BoundMember: {
18255 ExprResult result = E;
18256 const Expr *BME = E->IgnoreParens();
18257 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
18258 // Try to give a nicer diagnostic if it is a bound member that we recognize.
18259 if (isa<CXXPseudoDestructorExpr>(BME)) {
18260 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
18261 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
18262 if (ME->getMemberNameInfo().getName().getNameKind() ==
18263 DeclarationName::CXXDestructorName)
18264 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
18265 }
18266 tryToRecoverWithCall(result, PD,
18267 /*complain*/ true);
18268 return result;
18269 }
18270
18271 // ARC unbridged casts.
18272 case BuiltinType::ARCUnbridgedCast: {
18273 Expr *realCast = stripARCUnbridgedCast(E);
18274 diagnoseARCUnbridgedCast(realCast);
18275 return realCast;
18276 }
18277
18278 // Expressions of unknown type.
18279 case BuiltinType::UnknownAny:
18280 return diagnoseUnknownAnyExpr(*this, E);
18281
18282 // Pseudo-objects.
18283 case BuiltinType::PseudoObject:
18284 return checkPseudoObjectRValue(E);
18285
18286 case BuiltinType::BuiltinFn: {
18287 // Accept __noop without parens by implicitly converting it to a call expr.
18288 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
18289 if (DRE) {
18290 auto *FD = cast<FunctionDecl>(DRE->getDecl());
18291 if (FD->getBuiltinID() == Builtin::BI__noop) {
18292 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
18293 CK_BuiltinFnToFnPtr)
18294 .get();
18295 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
18296 VK_RValue, SourceLocation());
18297 }
18298 }
18299
18300 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
18301 return ExprError();
18302 }
18303
18304 // Expressions of unknown type.
18305 case BuiltinType::OMPArraySection:
18306 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
18307 return ExprError();
18308
18309 // Everything else should be impossible.
18310#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
18311 case BuiltinType::Id:
18312#include "clang/Basic/OpenCLImageTypes.def"
18313#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
18314 case BuiltinType::Id:
18315#include "clang/Basic/OpenCLExtensionTypes.def"
18316#define SVE_TYPE(Name, Id, SingletonId) \
18317 case BuiltinType::Id:
18318#include "clang/Basic/AArch64SVEACLETypes.def"
18319#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
18320#define PLACEHOLDER_TYPE(Id, SingletonId)
18321#include "clang/AST/BuiltinTypes.def"
18322 break;
18323 }
18324
18325 llvm_unreachable("invalid placeholder type!")::llvm::llvm_unreachable_internal("invalid placeholder type!"
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 18325)
;
18326}
18327
18328bool Sema::CheckCaseExpression(Expr *E) {
18329 if (E->isTypeDependent())
18330 return true;
18331 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
18332 return E->getType()->isIntegralOrEnumerationType();
18333 return false;
18334}
18335
18336/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
18337ExprResult
18338Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
18339 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&(((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
"Unknown Objective-C Boolean value!") ? static_cast<void>
(0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 18340, __PRETTY_FUNCTION__))
18340 "Unknown Objective-C Boolean value!")(((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
"Unknown Objective-C Boolean value!") ? static_cast<void>
(0) : __assert_fail ("(Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) && \"Unknown Objective-C Boolean value!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 18340, __PRETTY_FUNCTION__))
;
18341 QualType BoolT = Context.ObjCBuiltinBoolTy;
18342 if (!Context.getBOOLDecl()) {
18343 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
18344 Sema::LookupOrdinaryName);
18345 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
18346 NamedDecl *ND = Result.getFoundDecl();
18347 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
18348 Context.setBOOLDecl(TD);
18349 }
18350 }
18351 if (Context.getBOOLDecl())
18352 BoolT = Context.getBOOLType();
18353 return new (Context)
18354 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
18355}
18356
18357ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
18358 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
18359 SourceLocation RParen) {
18360
18361 StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
18362
18363 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
18364 return Spec.getPlatform() == Platform;
18365 });
18366
18367 VersionTuple Version;
18368 if (Spec != AvailSpecs.end())
18369 Version = Spec->getVersion();
18370
18371 // The use of `@available` in the enclosing function should be analyzed to
18372 // warn when it's used inappropriately (i.e. not if(@available)).
18373 if (getCurFunctionOrMethodDecl())
18374 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
18375 else if (getCurBlock() || getCurLambda())
18376 getCurFunction()->HasPotentialAvailabilityViolations = true;
18377
18378 return new (Context)
18379 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
18380}
18381
18382bool Sema::IsDependentFunctionNameExpr(Expr *E) {
18383 assert(E->isTypeDependent())((E->isTypeDependent()) ? static_cast<void> (0) : __assert_fail
("E->isTypeDependent()", "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/Sema/SemaExpr.cpp"
, 18383, __PRETTY_FUNCTION__))
;
18384 return isa<UnresolvedLookupExpr>(E);
18385}