1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for expressions.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/OperationKinds.h"
28 #include "clang/AST/RecursiveASTVisitor.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/Builtins.h"
31 #include "clang/Basic/PartialDiagnostic.h"
32 #include "clang/Basic/SourceManager.h"
33 #include "clang/Basic/TargetInfo.h"
34 #include "clang/Lex/LiteralSupport.h"
35 #include "clang/Lex/Preprocessor.h"
36 #include "clang/Sema/AnalysisBasedWarnings.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Designator.h"
40 #include "clang/Sema/Initialization.h"
41 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/Overload.h"
43 #include "clang/Sema/ParsedTemplate.h"
44 #include "clang/Sema/Scope.h"
45 #include "clang/Sema/ScopeInfo.h"
46 #include "clang/Sema/SemaFixItUtils.h"
47 #include "clang/Sema/SemaInternal.h"
48 #include "clang/Sema/Template.h"
49 #include "llvm/ADT/STLExtras.h"
50 #include "llvm/Support/ConvertUTF.h"
51 #include "llvm/Support/SaveAndRestore.h"
52 using namespace clang;
53 using namespace sema;
54 using llvm::RoundingMode;
55
56 /// Determine whether the use of this declaration is valid, without
57 /// emitting diagnostics.
CanUseDecl(NamedDecl * D,bool TreatUnavailableAsInvalid)58 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
59 // See if this is an auto-typed variable whose initializer we are parsing.
60 if (ParsingInitForAutoVars.count(D))
61 return false;
62
63 // See if this is a deleted function.
64 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
65 if (FD->isDeleted())
66 return false;
67
68 // If the function has a deduced return type, and we can't deduce it,
69 // then we can't use it either.
70 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
71 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
72 return false;
73
74 // See if this is an aligned allocation/deallocation function that is
75 // unavailable.
76 if (TreatUnavailableAsInvalid &&
77 isUnavailableAlignedAllocationFunction(*FD))
78 return false;
79 }
80
81 // See if this function is unavailable.
82 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
83 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
84 return false;
85
86 return true;
87 }
88
DiagnoseUnusedOfDecl(Sema & S,NamedDecl * D,SourceLocation Loc)89 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
90 // Warn if this is used but marked unused.
91 if (const auto *A = D->getAttr<UnusedAttr>()) {
92 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
93 // should diagnose them.
94 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
95 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
96 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
97 if (DC && !DC->hasAttr<UnusedAttr>())
98 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
99 }
100 }
101 }
102
103 /// Emit a note explaining that this function is deleted.
NoteDeletedFunction(FunctionDecl * Decl)104 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
105 assert(Decl && Decl->isDeleted());
106
107 if (Decl->isDefaulted()) {
108 // If the method was explicitly defaulted, point at that declaration.
109 if (!Decl->isImplicit())
110 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
111
112 // Try to diagnose why this special member function was implicitly
113 // deleted. This might fail, if that reason no longer applies.
114 DiagnoseDeletedDefaultedFunction(Decl);
115 return;
116 }
117
118 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
119 if (Ctor && Ctor->isInheritingConstructor())
120 return NoteDeletedInheritingConstructor(Ctor);
121
122 Diag(Decl->getLocation(), diag::note_availability_specified_here)
123 << Decl << 1;
124 }
125
126 /// Determine whether a FunctionDecl was ever declared with an
127 /// explicit storage class.
hasAnyExplicitStorageClass(const FunctionDecl * D)128 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
129 for (auto I : D->redecls()) {
130 if (I->getStorageClass() != SC_None)
131 return true;
132 }
133 return false;
134 }
135
136 /// Check whether we're in an extern inline function and referring to a
137 /// variable or function with internal linkage (C11 6.7.4p3).
138 ///
139 /// This is only a warning because we used to silently accept this code, but
140 /// in many cases it will not behave correctly. This is not enabled in C++ mode
141 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
142 /// and so while there may still be user mistakes, most of the time we can't
143 /// prove that there are errors.
diagnoseUseOfInternalDeclInInlineFunction(Sema & S,const NamedDecl * D,SourceLocation Loc)144 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
145 const NamedDecl *D,
146 SourceLocation Loc) {
147 // This is disabled under C++; there are too many ways for this to fire in
148 // contexts where the warning is a false positive, or where it is technically
149 // correct but benign.
150 if (S.getLangOpts().CPlusPlus)
151 return;
152
153 // Check if this is an inlined function or method.
154 FunctionDecl *Current = S.getCurFunctionDecl();
155 if (!Current)
156 return;
157 if (!Current->isInlined())
158 return;
159 if (!Current->isExternallyVisible())
160 return;
161
162 // Check if the decl has internal linkage.
163 if (D->getFormalLinkage() != InternalLinkage)
164 return;
165
166 // Downgrade from ExtWarn to Extension if
167 // (1) the supposedly external inline function is in the main file,
168 // and probably won't be included anywhere else.
169 // (2) the thing we're referencing is a pure function.
170 // (3) the thing we're referencing is another inline function.
171 // This last can give us false negatives, but it's better than warning on
172 // wrappers for simple C library functions.
173 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
174 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
175 if (!DowngradeWarning && UsedFn)
176 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
177
178 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
179 : diag::ext_internal_in_extern_inline)
180 << /*IsVar=*/!UsedFn << D;
181
182 S.MaybeSuggestAddingStaticToDecl(Current);
183
184 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
185 << D;
186 }
187
MaybeSuggestAddingStaticToDecl(const FunctionDecl * Cur)188 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
189 const FunctionDecl *First = Cur->getFirstDecl();
190
191 // Suggest "static" on the function, if possible.
192 if (!hasAnyExplicitStorageClass(First)) {
193 SourceLocation DeclBegin = First->getSourceRange().getBegin();
194 Diag(DeclBegin, diag::note_convert_inline_to_static)
195 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
196 }
197 }
198
199 /// Determine whether the use of this declaration is valid, and
200 /// emit any corresponding diagnostics.
201 ///
202 /// This routine diagnoses various problems with referencing
203 /// declarations that can occur when using a declaration. For example,
204 /// it might warn if a deprecated or unavailable declaration is being
205 /// used, or produce an error (and return true) if a C++0x deleted
206 /// function is being used.
207 ///
208 /// \returns true if there was an error (this declaration cannot be
209 /// referenced), false otherwise.
210 ///
DiagnoseUseOfDecl(NamedDecl * D,ArrayRef<SourceLocation> Locs,const ObjCInterfaceDecl * UnknownObjCClass,bool ObjCPropertyAccess,bool AvoidPartialAvailabilityChecks,ObjCInterfaceDecl * ClassReceiver)211 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
212 const ObjCInterfaceDecl *UnknownObjCClass,
213 bool ObjCPropertyAccess,
214 bool AvoidPartialAvailabilityChecks,
215 ObjCInterfaceDecl *ClassReceiver) {
216 SourceLocation Loc = Locs.front();
217 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
218 // If there were any diagnostics suppressed by template argument deduction,
219 // emit them now.
220 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
221 if (Pos != SuppressedDiagnostics.end()) {
222 for (const PartialDiagnosticAt &Suppressed : Pos->second)
223 Diag(Suppressed.first, Suppressed.second);
224
225 // Clear out the list of suppressed diagnostics, so that we don't emit
226 // them again for this specialization. However, we don't obsolete this
227 // entry from the table, because we want to avoid ever emitting these
228 // diagnostics again.
229 Pos->second.clear();
230 }
231
232 // C++ [basic.start.main]p3:
233 // The function 'main' shall not be used within a program.
234 if (cast<FunctionDecl>(D)->isMain())
235 Diag(Loc, diag::ext_main_used);
236
237 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
238 }
239
240 // See if this is an auto-typed variable whose initializer we are parsing.
241 if (ParsingInitForAutoVars.count(D)) {
242 if (isa<BindingDecl>(D)) {
243 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
244 << D->getDeclName();
245 } else {
246 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
247 << D->getDeclName() << cast<VarDecl>(D)->getType();
248 }
249 return true;
250 }
251
252 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
253 // See if this is a deleted function.
254 if (FD->isDeleted()) {
255 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
256 if (Ctor && Ctor->isInheritingConstructor())
257 Diag(Loc, diag::err_deleted_inherited_ctor_use)
258 << Ctor->getParent()
259 << Ctor->getInheritedConstructor().getConstructor()->getParent();
260 else
261 Diag(Loc, diag::err_deleted_function_use);
262 NoteDeletedFunction(FD);
263 return true;
264 }
265
266 // [expr.prim.id]p4
267 // A program that refers explicitly or implicitly to a function with a
268 // trailing requires-clause whose constraint-expression is not satisfied,
269 // other than to declare it, is ill-formed. [...]
270 //
271 // See if this is a function with constraints that need to be satisfied.
272 // Check this before deducing the return type, as it might instantiate the
273 // definition.
274 if (FD->getTrailingRequiresClause()) {
275 ConstraintSatisfaction Satisfaction;
276 if (CheckFunctionConstraints(FD, Satisfaction, Loc))
277 // A diagnostic will have already been generated (non-constant
278 // constraint expression, for example)
279 return true;
280 if (!Satisfaction.IsSatisfied) {
281 Diag(Loc,
282 diag::err_reference_to_function_with_unsatisfied_constraints)
283 << D;
284 DiagnoseUnsatisfiedConstraint(Satisfaction);
285 return true;
286 }
287 }
288
289 // If the function has a deduced return type, and we can't deduce it,
290 // then we can't use it either.
291 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
292 DeduceReturnType(FD, Loc))
293 return true;
294
295 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
296 return true;
297
298 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
299 return true;
300 }
301
302 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
303 // Lambdas are only default-constructible or assignable in C++2a onwards.
304 if (MD->getParent()->isLambda() &&
305 ((isa<CXXConstructorDecl>(MD) &&
306 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
307 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
308 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
309 << !isa<CXXConstructorDecl>(MD);
310 }
311 }
312
313 auto getReferencedObjCProp = [](const NamedDecl *D) ->
314 const ObjCPropertyDecl * {
315 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
316 return MD->findPropertyDecl();
317 return nullptr;
318 };
319 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
320 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
321 return true;
322 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
323 return true;
324 }
325
326 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
327 // Only the variables omp_in and omp_out are allowed in the combiner.
328 // Only the variables omp_priv and omp_orig are allowed in the
329 // initializer-clause.
330 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
331 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
332 isa<VarDecl>(D)) {
333 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
334 << getCurFunction()->HasOMPDeclareReductionCombiner;
335 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
336 return true;
337 }
338
339 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
340 // List-items in map clauses on this construct may only refer to the declared
341 // variable var and entities that could be referenced by a procedure defined
342 // at the same location
343 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
344 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
345 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
346 << getOpenMPDeclareMapperVarName();
347 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348 return true;
349 }
350
351 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
352 AvoidPartialAvailabilityChecks, ClassReceiver);
353
354 DiagnoseUnusedOfDecl(*this, D, Loc);
355
356 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
357
358 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
359 if (auto *VD = dyn_cast<ValueDecl>(D))
360 checkDeviceDecl(VD, Loc);
361
362 if (!Context.getTargetInfo().isTLSSupported())
363 if (const auto *VD = dyn_cast<VarDecl>(D))
364 if (VD->getTLSKind() != VarDecl::TLS_None)
365 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
366 }
367
368 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
369 !isUnevaluatedContext()) {
370 // C++ [expr.prim.req.nested] p3
371 // A local parameter shall only appear as an unevaluated operand
372 // (Clause 8) within the constraint-expression.
373 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
374 << D;
375 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
376 return true;
377 }
378
379 return false;
380 }
381
382 /// DiagnoseSentinelCalls - This routine checks whether a call or
383 /// message-send is to a declaration with the sentinel attribute, and
384 /// if so, it checks that the requirements of the sentinel are
385 /// satisfied.
DiagnoseSentinelCalls(NamedDecl * D,SourceLocation Loc,ArrayRef<Expr * > Args)386 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
387 ArrayRef<Expr *> Args) {
388 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
389 if (!attr)
390 return;
391
392 // The number of formal parameters of the declaration.
393 unsigned numFormalParams;
394
395 // The kind of declaration. This is also an index into a %select in
396 // the diagnostic.
397 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
398
399 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
400 numFormalParams = MD->param_size();
401 calleeType = CT_Method;
402 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
403 numFormalParams = FD->param_size();
404 calleeType = CT_Function;
405 } else if (isa<VarDecl>(D)) {
406 QualType type = cast<ValueDecl>(D)->getType();
407 const FunctionType *fn = nullptr;
408 if (const PointerType *ptr = type->getAs<PointerType>()) {
409 fn = ptr->getPointeeType()->getAs<FunctionType>();
410 if (!fn) return;
411 calleeType = CT_Function;
412 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
413 fn = ptr->getPointeeType()->castAs<FunctionType>();
414 calleeType = CT_Block;
415 } else {
416 return;
417 }
418
419 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
420 numFormalParams = proto->getNumParams();
421 } else {
422 numFormalParams = 0;
423 }
424 } else {
425 return;
426 }
427
428 // "nullPos" is the number of formal parameters at the end which
429 // effectively count as part of the variadic arguments. This is
430 // useful if you would prefer to not have *any* formal parameters,
431 // but the language forces you to have at least one.
432 unsigned nullPos = attr->getNullPos();
433 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
434 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
435
436 // The number of arguments which should follow the sentinel.
437 unsigned numArgsAfterSentinel = attr->getSentinel();
438
439 // If there aren't enough arguments for all the formal parameters,
440 // the sentinel, and the args after the sentinel, complain.
441 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
442 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
443 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
444 return;
445 }
446
447 // Otherwise, find the sentinel expression.
448 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
449 if (!sentinelExpr) return;
450 if (sentinelExpr->isValueDependent()) return;
451 if (Context.isSentinelNullExpr(sentinelExpr)) return;
452
453 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
454 // or 'NULL' if those are actually defined in the context. Only use
455 // 'nil' for ObjC methods, where it's much more likely that the
456 // variadic arguments form a list of object pointers.
457 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
458 std::string NullValue;
459 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
460 NullValue = "nil";
461 else if (getLangOpts().CPlusPlus11)
462 NullValue = "nullptr";
463 else if (PP.isMacroDefined("NULL"))
464 NullValue = "NULL";
465 else
466 NullValue = "(void*) 0";
467
468 if (MissingNilLoc.isInvalid())
469 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
470 else
471 Diag(MissingNilLoc, diag::warn_missing_sentinel)
472 << int(calleeType)
473 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
474 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
475 }
476
getExprRange(Expr * E) const477 SourceRange Sema::getExprRange(Expr *E) const {
478 return E ? E->getSourceRange() : SourceRange();
479 }
480
481 //===----------------------------------------------------------------------===//
482 // Standard Promotions and Conversions
483 //===----------------------------------------------------------------------===//
484
485 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
DefaultFunctionArrayConversion(Expr * E,bool Diagnose)486 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
487 // Handle any placeholder expressions which made it here.
488 if (E->getType()->isPlaceholderType()) {
489 ExprResult result = CheckPlaceholderExpr(E);
490 if (result.isInvalid()) return ExprError();
491 E = result.get();
492 }
493
494 QualType Ty = E->getType();
495 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
496
497 if (Ty->isFunctionType()) {
498 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
499 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
500 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
501 return ExprError();
502
503 E = ImpCastExprToType(E, Context.getPointerType(Ty),
504 CK_FunctionToPointerDecay).get();
505 } else if (Ty->isArrayType()) {
506 // In C90 mode, arrays only promote to pointers if the array expression is
507 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
508 // type 'array of type' is converted to an expression that has type 'pointer
509 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
510 // that has type 'array of type' ...". The relevant change is "an lvalue"
511 // (C90) to "an expression" (C99).
512 //
513 // C++ 4.2p1:
514 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
515 // T" can be converted to an rvalue of type "pointer to T".
516 //
517 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
518 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
519 CK_ArrayToPointerDecay).get();
520 }
521 return E;
522 }
523
CheckForNullPointerDereference(Sema & S,Expr * E)524 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
525 // Check to see if we are dereferencing a null pointer. If so,
526 // and if not volatile-qualified, this is undefined behavior that the
527 // optimizer will delete, so warn about it. People sometimes try to use this
528 // to get a deterministic trap and are surprised by clang's behavior. This
529 // only handles the pattern "*null", which is a very syntactic check.
530 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
531 if (UO && UO->getOpcode() == UO_Deref &&
532 UO->getSubExpr()->getType()->isPointerType()) {
533 const LangAS AS =
534 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
535 if ((!isTargetAddressSpace(AS) ||
536 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
537 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
538 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
539 !UO->getType().isVolatileQualified()) {
540 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
541 S.PDiag(diag::warn_indirection_through_null)
542 << UO->getSubExpr()->getSourceRange());
543 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
544 S.PDiag(diag::note_indirection_through_null));
545 }
546 }
547 }
548
DiagnoseDirectIsaAccess(Sema & S,const ObjCIvarRefExpr * OIRE,SourceLocation AssignLoc,const Expr * RHS)549 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
550 SourceLocation AssignLoc,
551 const Expr* RHS) {
552 const ObjCIvarDecl *IV = OIRE->getDecl();
553 if (!IV)
554 return;
555
556 DeclarationName MemberName = IV->getDeclName();
557 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
558 if (!Member || !Member->isStr("isa"))
559 return;
560
561 const Expr *Base = OIRE->getBase();
562 QualType BaseType = Base->getType();
563 if (OIRE->isArrow())
564 BaseType = BaseType->getPointeeType();
565 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
566 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
567 ObjCInterfaceDecl *ClassDeclared = nullptr;
568 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
569 if (!ClassDeclared->getSuperClass()
570 && (*ClassDeclared->ivar_begin()) == IV) {
571 if (RHS) {
572 NamedDecl *ObjectSetClass =
573 S.LookupSingleName(S.TUScope,
574 &S.Context.Idents.get("object_setClass"),
575 SourceLocation(), S.LookupOrdinaryName);
576 if (ObjectSetClass) {
577 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
578 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
579 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
580 "object_setClass(")
581 << FixItHint::CreateReplacement(
582 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
583 << FixItHint::CreateInsertion(RHSLocEnd, ")");
584 }
585 else
586 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
587 } else {
588 NamedDecl *ObjectGetClass =
589 S.LookupSingleName(S.TUScope,
590 &S.Context.Idents.get("object_getClass"),
591 SourceLocation(), S.LookupOrdinaryName);
592 if (ObjectGetClass)
593 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
594 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
595 "object_getClass(")
596 << FixItHint::CreateReplacement(
597 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
598 else
599 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
600 }
601 S.Diag(IV->getLocation(), diag::note_ivar_decl);
602 }
603 }
604 }
605
DefaultLvalueConversion(Expr * E)606 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
607 // Handle any placeholder expressions which made it here.
608 if (E->getType()->isPlaceholderType()) {
609 ExprResult result = CheckPlaceholderExpr(E);
610 if (result.isInvalid()) return ExprError();
611 E = result.get();
612 }
613
614 // C++ [conv.lval]p1:
615 // A glvalue of a non-function, non-array type T can be
616 // converted to a prvalue.
617 if (!E->isGLValue()) return E;
618
619 QualType T = E->getType();
620 assert(!T.isNull() && "r-value conversion on typeless expression?");
621
622 // lvalue-to-rvalue conversion cannot be applied to function or array types.
623 if (T->isFunctionType() || T->isArrayType())
624 return E;
625
626 // We don't want to throw lvalue-to-rvalue casts on top of
627 // expressions of certain types in C++.
628 if (getLangOpts().CPlusPlus &&
629 (E->getType() == Context.OverloadTy ||
630 T->isDependentType() ||
631 T->isRecordType()))
632 return E;
633
634 // The C standard is actually really unclear on this point, and
635 // DR106 tells us what the result should be but not why. It's
636 // generally best to say that void types just doesn't undergo
637 // lvalue-to-rvalue at all. Note that expressions of unqualified
638 // 'void' type are never l-values, but qualified void can be.
639 if (T->isVoidType())
640 return E;
641
642 // OpenCL usually rejects direct accesses to values of 'half' type.
643 if (getLangOpts().OpenCL &&
644 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
645 T->isHalfType()) {
646 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
647 << 0 << T;
648 return ExprError();
649 }
650
651 CheckForNullPointerDereference(*this, E);
652 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
653 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
654 &Context.Idents.get("object_getClass"),
655 SourceLocation(), LookupOrdinaryName);
656 if (ObjectGetClass)
657 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
658 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
659 << FixItHint::CreateReplacement(
660 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
661 else
662 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
663 }
664 else if (const ObjCIvarRefExpr *OIRE =
665 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
666 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
667
668 // C++ [conv.lval]p1:
669 // [...] If T is a non-class type, the type of the prvalue is the
670 // cv-unqualified version of T. Otherwise, the type of the
671 // rvalue is T.
672 //
673 // C99 6.3.2.1p2:
674 // If the lvalue has qualified type, the value has the unqualified
675 // version of the type of the lvalue; otherwise, the value has the
676 // type of the lvalue.
677 if (T.hasQualifiers())
678 T = T.getUnqualifiedType();
679
680 // Under the MS ABI, lock down the inheritance model now.
681 if (T->isMemberPointerType() &&
682 Context.getTargetInfo().getCXXABI().isMicrosoft())
683 (void)isCompleteType(E->getExprLoc(), T);
684
685 ExprResult Res = CheckLValueToRValueConversionOperand(E);
686 if (Res.isInvalid())
687 return Res;
688 E = Res.get();
689
690 // Loading a __weak object implicitly retains the value, so we need a cleanup to
691 // balance that.
692 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
693 Cleanup.setExprNeedsCleanups(true);
694
695 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
696 Cleanup.setExprNeedsCleanups(true);
697
698 // C++ [conv.lval]p3:
699 // If T is cv std::nullptr_t, the result is a null pointer constant.
700 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
701 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue,
702 CurFPFeatureOverrides());
703
704 // C11 6.3.2.1p2:
705 // ... if the lvalue has atomic type, the value has the non-atomic version
706 // of the type of the lvalue ...
707 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
708 T = Atomic->getValueType().getUnqualifiedType();
709 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
710 nullptr, VK_RValue, FPOptionsOverride());
711 }
712
713 return Res;
714 }
715
DefaultFunctionArrayLvalueConversion(Expr * E,bool Diagnose)716 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
717 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
718 if (Res.isInvalid())
719 return ExprError();
720 Res = DefaultLvalueConversion(Res.get());
721 if (Res.isInvalid())
722 return ExprError();
723 return Res;
724 }
725
726 /// CallExprUnaryConversions - a special case of an unary conversion
727 /// performed on a function designator of a call expression.
CallExprUnaryConversions(Expr * E)728 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
729 QualType Ty = E->getType();
730 ExprResult Res = E;
731 // Only do implicit cast for a function type, but not for a pointer
732 // to function type.
733 if (Ty->isFunctionType()) {
734 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
735 CK_FunctionToPointerDecay);
736 if (Res.isInvalid())
737 return ExprError();
738 }
739 Res = DefaultLvalueConversion(Res.get());
740 if (Res.isInvalid())
741 return ExprError();
742 return Res.get();
743 }
744
745 /// UsualUnaryConversions - Performs various conversions that are common to most
746 /// operators (C99 6.3). The conversions of array and function types are
747 /// sometimes suppressed. For example, the array->pointer conversion doesn't
748 /// apply if the array is an argument to the sizeof or address (&) operators.
749 /// In these instances, this routine should *not* be called.
UsualUnaryConversions(Expr * E)750 ExprResult Sema::UsualUnaryConversions(Expr *E) {
751 // First, convert to an r-value.
752 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
753 if (Res.isInvalid())
754 return ExprError();
755 E = Res.get();
756
757 QualType Ty = E->getType();
758 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
759
760 // Half FP have to be promoted to float unless it is natively supported
761 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
762 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
763
764 // Try to perform integral promotions if the object has a theoretically
765 // promotable type.
766 if (Ty->isIntegralOrUnscopedEnumerationType()) {
767 // C99 6.3.1.1p2:
768 //
769 // The following may be used in an expression wherever an int or
770 // unsigned int may be used:
771 // - an object or expression with an integer type whose integer
772 // conversion rank is less than or equal to the rank of int
773 // and unsigned int.
774 // - A bit-field of type _Bool, int, signed int, or unsigned int.
775 //
776 // If an int can represent all values of the original type, the
777 // value is converted to an int; otherwise, it is converted to an
778 // unsigned int. These are called the integer promotions. All
779 // other types are unchanged by the integer promotions.
780
781 QualType PTy = Context.isPromotableBitField(E);
782 if (!PTy.isNull()) {
783 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
784 return E;
785 }
786 if (Ty->isPromotableIntegerType()) {
787 QualType PT = Context.getPromotedIntegerType(Ty);
788 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
789 return E;
790 }
791 }
792 return E;
793 }
794
795 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
796 /// do not have a prototype. Arguments that have type float or __fp16
797 /// are promoted to double. All other argument types are converted by
798 /// UsualUnaryConversions().
DefaultArgumentPromotion(Expr * E)799 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
800 QualType Ty = E->getType();
801 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
802
803 ExprResult Res = UsualUnaryConversions(E);
804 if (Res.isInvalid())
805 return ExprError();
806 E = Res.get();
807
808 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
809 // promote to double.
810 // Note that default argument promotion applies only to float (and
811 // half/fp16); it does not apply to _Float16.
812 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
813 if (BTy && (BTy->getKind() == BuiltinType::Half ||
814 BTy->getKind() == BuiltinType::Float)) {
815 if (getLangOpts().OpenCL &&
816 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
817 if (BTy->getKind() == BuiltinType::Half) {
818 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
819 }
820 } else {
821 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
822 }
823 }
824 if (BTy &&
825 getLangOpts().getExtendIntArgs() ==
826 LangOptions::ExtendArgsKind::ExtendTo64 &&
827 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
828 Context.getTypeSizeInChars(BTy) <
829 Context.getTypeSizeInChars(Context.LongLongTy)) {
830 E = (Ty->isUnsignedIntegerType())
831 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
832 .get()
833 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
834 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
835 "Unexpected typesize for LongLongTy");
836 }
837
838 // C++ performs lvalue-to-rvalue conversion as a default argument
839 // promotion, even on class types, but note:
840 // C++11 [conv.lval]p2:
841 // When an lvalue-to-rvalue conversion occurs in an unevaluated
842 // operand or a subexpression thereof the value contained in the
843 // referenced object is not accessed. Otherwise, if the glvalue
844 // has a class type, the conversion copy-initializes a temporary
845 // of type T from the glvalue and the result of the conversion
846 // is a prvalue for the temporary.
847 // FIXME: add some way to gate this entire thing for correctness in
848 // potentially potentially evaluated contexts.
849 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
850 ExprResult Temp = PerformCopyInitialization(
851 InitializedEntity::InitializeTemporary(E->getType()),
852 E->getExprLoc(), E);
853 if (Temp.isInvalid())
854 return ExprError();
855 E = Temp.get();
856 }
857
858 return E;
859 }
860
861 /// Determine the degree of POD-ness for an expression.
862 /// Incomplete types are considered POD, since this check can be performed
863 /// when we're in an unevaluated context.
isValidVarArgType(const QualType & Ty)864 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
865 if (Ty->isIncompleteType()) {
866 // C++11 [expr.call]p7:
867 // After these conversions, if the argument does not have arithmetic,
868 // enumeration, pointer, pointer to member, or class type, the program
869 // is ill-formed.
870 //
871 // Since we've already performed array-to-pointer and function-to-pointer
872 // decay, the only such type in C++ is cv void. This also handles
873 // initializer lists as variadic arguments.
874 if (Ty->isVoidType())
875 return VAK_Invalid;
876
877 if (Ty->isObjCObjectType())
878 return VAK_Invalid;
879 return VAK_Valid;
880 }
881
882 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
883 return VAK_Invalid;
884
885 if (Ty.isCXX98PODType(Context))
886 return VAK_Valid;
887
888 // C++11 [expr.call]p7:
889 // Passing a potentially-evaluated argument of class type (Clause 9)
890 // having a non-trivial copy constructor, a non-trivial move constructor,
891 // or a non-trivial destructor, with no corresponding parameter,
892 // is conditionally-supported with implementation-defined semantics.
893 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
894 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
895 if (!Record->hasNonTrivialCopyConstructor() &&
896 !Record->hasNonTrivialMoveConstructor() &&
897 !Record->hasNonTrivialDestructor())
898 return VAK_ValidInCXX11;
899
900 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
901 return VAK_Valid;
902
903 if (Ty->isObjCObjectType())
904 return VAK_Invalid;
905
906 if (getLangOpts().MSVCCompat)
907 return VAK_MSVCUndefined;
908
909 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
910 // permitted to reject them. We should consider doing so.
911 return VAK_Undefined;
912 }
913
checkVariadicArgument(const Expr * E,VariadicCallType CT)914 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
915 // Don't allow one to pass an Objective-C interface to a vararg.
916 const QualType &Ty = E->getType();
917 VarArgKind VAK = isValidVarArgType(Ty);
918
919 // Complain about passing non-POD types through varargs.
920 switch (VAK) {
921 case VAK_ValidInCXX11:
922 DiagRuntimeBehavior(
923 E->getBeginLoc(), nullptr,
924 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
925 LLVM_FALLTHROUGH;
926 case VAK_Valid:
927 if (Ty->isRecordType()) {
928 // This is unlikely to be what the user intended. If the class has a
929 // 'c_str' member function, the user probably meant to call that.
930 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
931 PDiag(diag::warn_pass_class_arg_to_vararg)
932 << Ty << CT << hasCStrMethod(E) << ".c_str()");
933 }
934 break;
935
936 case VAK_Undefined:
937 case VAK_MSVCUndefined:
938 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
939 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
940 << getLangOpts().CPlusPlus11 << Ty << CT);
941 break;
942
943 case VAK_Invalid:
944 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
945 Diag(E->getBeginLoc(),
946 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
947 << Ty << CT;
948 else if (Ty->isObjCObjectType())
949 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
950 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
951 << Ty << CT);
952 else
953 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
954 << isa<InitListExpr>(E) << Ty << CT;
955 break;
956 }
957 }
958
959 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
960 /// will create a trap if the resulting type is not a POD type.
DefaultVariadicArgumentPromotion(Expr * E,VariadicCallType CT,FunctionDecl * FDecl)961 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
962 FunctionDecl *FDecl) {
963 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
964 // Strip the unbridged-cast placeholder expression off, if applicable.
965 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
966 (CT == VariadicMethod ||
967 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
968 E = stripARCUnbridgedCast(E);
969
970 // Otherwise, do normal placeholder checking.
971 } else {
972 ExprResult ExprRes = CheckPlaceholderExpr(E);
973 if (ExprRes.isInvalid())
974 return ExprError();
975 E = ExprRes.get();
976 }
977 }
978
979 ExprResult ExprRes = DefaultArgumentPromotion(E);
980 if (ExprRes.isInvalid())
981 return ExprError();
982
983 // Copy blocks to the heap.
984 if (ExprRes.get()->getType()->isBlockPointerType())
985 maybeExtendBlockObject(ExprRes);
986
987 E = ExprRes.get();
988
989 // Diagnostics regarding non-POD argument types are
990 // emitted along with format string checking in Sema::CheckFunctionCall().
991 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
992 // Turn this into a trap.
993 CXXScopeSpec SS;
994 SourceLocation TemplateKWLoc;
995 UnqualifiedId Name;
996 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
997 E->getBeginLoc());
998 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
999 /*HasTrailingLParen=*/true,
1000 /*IsAddressOfOperand=*/false);
1001 if (TrapFn.isInvalid())
1002 return ExprError();
1003
1004 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1005 None, E->getEndLoc());
1006 if (Call.isInvalid())
1007 return ExprError();
1008
1009 ExprResult Comma =
1010 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1011 if (Comma.isInvalid())
1012 return ExprError();
1013 return Comma.get();
1014 }
1015
1016 if (!getLangOpts().CPlusPlus &&
1017 RequireCompleteType(E->getExprLoc(), E->getType(),
1018 diag::err_call_incomplete_argument))
1019 return ExprError();
1020
1021 return E;
1022 }
1023
1024 /// Converts an integer to complex float type. Helper function of
1025 /// UsualArithmeticConversions()
1026 ///
1027 /// \return false if the integer expression is an integer type and is
1028 /// successfully converted to the complex type.
handleIntegerToComplexFloatConversion(Sema & S,ExprResult & IntExpr,ExprResult & ComplexExpr,QualType IntTy,QualType ComplexTy,bool SkipCast)1029 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1030 ExprResult &ComplexExpr,
1031 QualType IntTy,
1032 QualType ComplexTy,
1033 bool SkipCast) {
1034 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1035 if (SkipCast) return false;
1036 if (IntTy->isIntegerType()) {
1037 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1038 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1039 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1040 CK_FloatingRealToComplex);
1041 } else {
1042 assert(IntTy->isComplexIntegerType());
1043 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1044 CK_IntegralComplexToFloatingComplex);
1045 }
1046 return false;
1047 }
1048
1049 /// Handle arithmetic conversion with complex types. Helper function of
1050 /// UsualArithmeticConversions()
handleComplexFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1051 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1052 ExprResult &RHS, QualType LHSType,
1053 QualType RHSType,
1054 bool IsCompAssign) {
1055 // if we have an integer operand, the result is the complex type.
1056 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1057 /*skipCast*/false))
1058 return LHSType;
1059 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1060 /*skipCast*/IsCompAssign))
1061 return RHSType;
1062
1063 // This handles complex/complex, complex/float, or float/complex.
1064 // When both operands are complex, the shorter operand is converted to the
1065 // type of the longer, and that is the type of the result. This corresponds
1066 // to what is done when combining two real floating-point operands.
1067 // The fun begins when size promotion occur across type domains.
1068 // From H&S 6.3.4: When one operand is complex and the other is a real
1069 // floating-point type, the less precise type is converted, within it's
1070 // real or complex domain, to the precision of the other type. For example,
1071 // when combining a "long double" with a "double _Complex", the
1072 // "double _Complex" is promoted to "long double _Complex".
1073
1074 // Compute the rank of the two types, regardless of whether they are complex.
1075 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1076
1077 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1078 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1079 QualType LHSElementType =
1080 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1081 QualType RHSElementType =
1082 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1083
1084 QualType ResultType = S.Context.getComplexType(LHSElementType);
1085 if (Order < 0) {
1086 // Promote the precision of the LHS if not an assignment.
1087 ResultType = S.Context.getComplexType(RHSElementType);
1088 if (!IsCompAssign) {
1089 if (LHSComplexType)
1090 LHS =
1091 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1092 else
1093 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1094 }
1095 } else if (Order > 0) {
1096 // Promote the precision of the RHS.
1097 if (RHSComplexType)
1098 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1099 else
1100 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1101 }
1102 return ResultType;
1103 }
1104
1105 /// Handle arithmetic conversion from integer to float. Helper function
1106 /// of UsualArithmeticConversions()
handleIntToFloatConversion(Sema & S,ExprResult & FloatExpr,ExprResult & IntExpr,QualType FloatTy,QualType IntTy,bool ConvertFloat,bool ConvertInt)1107 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1108 ExprResult &IntExpr,
1109 QualType FloatTy, QualType IntTy,
1110 bool ConvertFloat, bool ConvertInt) {
1111 if (IntTy->isIntegerType()) {
1112 if (ConvertInt)
1113 // Convert intExpr to the lhs floating point type.
1114 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1115 CK_IntegralToFloating);
1116 return FloatTy;
1117 }
1118
1119 // Convert both sides to the appropriate complex float.
1120 assert(IntTy->isComplexIntegerType());
1121 QualType result = S.Context.getComplexType(FloatTy);
1122
1123 // _Complex int -> _Complex float
1124 if (ConvertInt)
1125 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1126 CK_IntegralComplexToFloatingComplex);
1127
1128 // float -> _Complex float
1129 if (ConvertFloat)
1130 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1131 CK_FloatingRealToComplex);
1132
1133 return result;
1134 }
1135
1136 /// Handle arithmethic conversion with floating point types. Helper
1137 /// function of UsualArithmeticConversions()
handleFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1138 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1139 ExprResult &RHS, QualType LHSType,
1140 QualType RHSType, bool IsCompAssign) {
1141 bool LHSFloat = LHSType->isRealFloatingType();
1142 bool RHSFloat = RHSType->isRealFloatingType();
1143
1144 // N1169 4.1.4: If one of the operands has a floating type and the other
1145 // operand has a fixed-point type, the fixed-point operand
1146 // is converted to the floating type [...]
1147 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1148 if (LHSFloat)
1149 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1150 else if (!IsCompAssign)
1151 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1152 return LHSFloat ? LHSType : RHSType;
1153 }
1154
1155 // If we have two real floating types, convert the smaller operand
1156 // to the bigger result.
1157 if (LHSFloat && RHSFloat) {
1158 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1159 if (order > 0) {
1160 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1161 return LHSType;
1162 }
1163
1164 assert(order < 0 && "illegal float comparison");
1165 if (!IsCompAssign)
1166 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1167 return RHSType;
1168 }
1169
1170 if (LHSFloat) {
1171 // Half FP has to be promoted to float unless it is natively supported
1172 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1173 LHSType = S.Context.FloatTy;
1174
1175 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1176 /*ConvertFloat=*/!IsCompAssign,
1177 /*ConvertInt=*/ true);
1178 }
1179 assert(RHSFloat);
1180 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1181 /*ConvertFloat=*/ true,
1182 /*ConvertInt=*/!IsCompAssign);
1183 }
1184
1185 /// Diagnose attempts to convert between __float128 and long double if
1186 /// there is no support for such conversion. Helper function of
1187 /// UsualArithmeticConversions().
unsupportedTypeConversion(const Sema & S,QualType LHSType,QualType RHSType)1188 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1189 QualType RHSType) {
1190 /* No issue converting if at least one of the types is not a floating point
1191 type or the two types have the same rank.
1192 */
1193 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1194 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1195 return false;
1196
1197 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1198 "The remaining types must be floating point types.");
1199
1200 auto *LHSComplex = LHSType->getAs<ComplexType>();
1201 auto *RHSComplex = RHSType->getAs<ComplexType>();
1202
1203 QualType LHSElemType = LHSComplex ?
1204 LHSComplex->getElementType() : LHSType;
1205 QualType RHSElemType = RHSComplex ?
1206 RHSComplex->getElementType() : RHSType;
1207
1208 // No issue if the two types have the same representation
1209 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1210 &S.Context.getFloatTypeSemantics(RHSElemType))
1211 return false;
1212
1213 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1214 RHSElemType == S.Context.LongDoubleTy);
1215 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1216 RHSElemType == S.Context.Float128Ty);
1217
1218 // We've handled the situation where __float128 and long double have the same
1219 // representation. We allow all conversions for all possible long double types
1220 // except PPC's double double.
1221 return Float128AndLongDouble &&
1222 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1223 &llvm::APFloat::PPCDoubleDouble());
1224 }
1225
1226 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1227
1228 namespace {
1229 /// These helper callbacks are placed in an anonymous namespace to
1230 /// permit their use as function template parameters.
doIntegralCast(Sema & S,Expr * op,QualType toType)1231 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1232 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1233 }
1234
doComplexIntegralCast(Sema & S,Expr * op,QualType toType)1235 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1236 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1237 CK_IntegralComplexCast);
1238 }
1239 }
1240
1241 /// Handle integer arithmetic conversions. Helper function of
1242 /// UsualArithmeticConversions()
1243 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
handleIntegerConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1244 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1245 ExprResult &RHS, QualType LHSType,
1246 QualType RHSType, bool IsCompAssign) {
1247 // The rules for this case are in C99 6.3.1.8
1248 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1249 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1250 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1251 if (LHSSigned == RHSSigned) {
1252 // Same signedness; use the higher-ranked type
1253 if (order >= 0) {
1254 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1255 return LHSType;
1256 } else if (!IsCompAssign)
1257 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1258 return RHSType;
1259 } else if (order != (LHSSigned ? 1 : -1)) {
1260 // The unsigned type has greater than or equal rank to the
1261 // signed type, so use the unsigned type
1262 if (RHSSigned) {
1263 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1264 return LHSType;
1265 } else if (!IsCompAssign)
1266 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1267 return RHSType;
1268 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1269 // The two types are different widths; if we are here, that
1270 // means the signed type is larger than the unsigned type, so
1271 // use the signed type.
1272 if (LHSSigned) {
1273 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1274 return LHSType;
1275 } else if (!IsCompAssign)
1276 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1277 return RHSType;
1278 } else {
1279 // The signed type is higher-ranked than the unsigned type,
1280 // but isn't actually any bigger (like unsigned int and long
1281 // on most 32-bit systems). Use the unsigned type corresponding
1282 // to the signed type.
1283 QualType result =
1284 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1285 RHS = (*doRHSCast)(S, RHS.get(), result);
1286 if (!IsCompAssign)
1287 LHS = (*doLHSCast)(S, LHS.get(), result);
1288 return result;
1289 }
1290 }
1291
1292 /// Handle conversions with GCC complex int extension. Helper function
1293 /// of UsualArithmeticConversions()
handleComplexIntConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1294 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1295 ExprResult &RHS, QualType LHSType,
1296 QualType RHSType,
1297 bool IsCompAssign) {
1298 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1299 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1300
1301 if (LHSComplexInt && RHSComplexInt) {
1302 QualType LHSEltType = LHSComplexInt->getElementType();
1303 QualType RHSEltType = RHSComplexInt->getElementType();
1304 QualType ScalarType =
1305 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1306 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1307
1308 return S.Context.getComplexType(ScalarType);
1309 }
1310
1311 if (LHSComplexInt) {
1312 QualType LHSEltType = LHSComplexInt->getElementType();
1313 QualType ScalarType =
1314 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1315 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1316 QualType ComplexType = S.Context.getComplexType(ScalarType);
1317 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1318 CK_IntegralRealToComplex);
1319
1320 return ComplexType;
1321 }
1322
1323 assert(RHSComplexInt);
1324
1325 QualType RHSEltType = RHSComplexInt->getElementType();
1326 QualType ScalarType =
1327 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1328 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1329 QualType ComplexType = S.Context.getComplexType(ScalarType);
1330
1331 if (!IsCompAssign)
1332 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1333 CK_IntegralRealToComplex);
1334 return ComplexType;
1335 }
1336
1337 /// Return the rank of a given fixed point or integer type. The value itself
1338 /// doesn't matter, but the values must be increasing with proper increasing
1339 /// rank as described in N1169 4.1.1.
GetFixedPointRank(QualType Ty)1340 static unsigned GetFixedPointRank(QualType Ty) {
1341 const auto *BTy = Ty->getAs<BuiltinType>();
1342 assert(BTy && "Expected a builtin type.");
1343
1344 switch (BTy->getKind()) {
1345 case BuiltinType::ShortFract:
1346 case BuiltinType::UShortFract:
1347 case BuiltinType::SatShortFract:
1348 case BuiltinType::SatUShortFract:
1349 return 1;
1350 case BuiltinType::Fract:
1351 case BuiltinType::UFract:
1352 case BuiltinType::SatFract:
1353 case BuiltinType::SatUFract:
1354 return 2;
1355 case BuiltinType::LongFract:
1356 case BuiltinType::ULongFract:
1357 case BuiltinType::SatLongFract:
1358 case BuiltinType::SatULongFract:
1359 return 3;
1360 case BuiltinType::ShortAccum:
1361 case BuiltinType::UShortAccum:
1362 case BuiltinType::SatShortAccum:
1363 case BuiltinType::SatUShortAccum:
1364 return 4;
1365 case BuiltinType::Accum:
1366 case BuiltinType::UAccum:
1367 case BuiltinType::SatAccum:
1368 case BuiltinType::SatUAccum:
1369 return 5;
1370 case BuiltinType::LongAccum:
1371 case BuiltinType::ULongAccum:
1372 case BuiltinType::SatLongAccum:
1373 case BuiltinType::SatULongAccum:
1374 return 6;
1375 default:
1376 if (BTy->isInteger())
1377 return 0;
1378 llvm_unreachable("Unexpected fixed point or integer type");
1379 }
1380 }
1381
1382 /// handleFixedPointConversion - Fixed point operations between fixed
1383 /// point types and integers or other fixed point types do not fall under
1384 /// usual arithmetic conversion since these conversions could result in loss
1385 /// of precsision (N1169 4.1.4). These operations should be calculated with
1386 /// the full precision of their result type (N1169 4.1.6.2.1).
handleFixedPointConversion(Sema & S,QualType LHSTy,QualType RHSTy)1387 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1388 QualType RHSTy) {
1389 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1390 "Expected at least one of the operands to be a fixed point type");
1391 assert((LHSTy->isFixedPointOrIntegerType() ||
1392 RHSTy->isFixedPointOrIntegerType()) &&
1393 "Special fixed point arithmetic operation conversions are only "
1394 "applied to ints or other fixed point types");
1395
1396 // If one operand has signed fixed-point type and the other operand has
1397 // unsigned fixed-point type, then the unsigned fixed-point operand is
1398 // converted to its corresponding signed fixed-point type and the resulting
1399 // type is the type of the converted operand.
1400 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1401 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1402 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1403 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1404
1405 // The result type is the type with the highest rank, whereby a fixed-point
1406 // conversion rank is always greater than an integer conversion rank; if the
1407 // type of either of the operands is a saturating fixedpoint type, the result
1408 // type shall be the saturating fixed-point type corresponding to the type
1409 // with the highest rank; the resulting value is converted (taking into
1410 // account rounding and overflow) to the precision of the resulting type.
1411 // Same ranks between signed and unsigned types are resolved earlier, so both
1412 // types are either signed or both unsigned at this point.
1413 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1414 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1415
1416 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1417
1418 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1419 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1420
1421 return ResultTy;
1422 }
1423
1424 /// Check that the usual arithmetic conversions can be performed on this pair of
1425 /// expressions that might be of enumeration type.
checkEnumArithmeticConversions(Sema & S,Expr * LHS,Expr * RHS,SourceLocation Loc,Sema::ArithConvKind ACK)1426 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1427 SourceLocation Loc,
1428 Sema::ArithConvKind ACK) {
1429 // C++2a [expr.arith.conv]p1:
1430 // If one operand is of enumeration type and the other operand is of a
1431 // different enumeration type or a floating-point type, this behavior is
1432 // deprecated ([depr.arith.conv.enum]).
1433 //
1434 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1435 // Eventually we will presumably reject these cases (in C++23 onwards?).
1436 QualType L = LHS->getType(), R = RHS->getType();
1437 bool LEnum = L->isUnscopedEnumerationType(),
1438 REnum = R->isUnscopedEnumerationType();
1439 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1440 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1441 (REnum && L->isFloatingType())) {
1442 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1443 ? diag::warn_arith_conv_enum_float_cxx20
1444 : diag::warn_arith_conv_enum_float)
1445 << LHS->getSourceRange() << RHS->getSourceRange()
1446 << (int)ACK << LEnum << L << R;
1447 } else if (!IsCompAssign && LEnum && REnum &&
1448 !S.Context.hasSameUnqualifiedType(L, R)) {
1449 unsigned DiagID;
1450 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1451 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1452 // If either enumeration type is unnamed, it's less likely that the
1453 // user cares about this, but this situation is still deprecated in
1454 // C++2a. Use a different warning group.
1455 DiagID = S.getLangOpts().CPlusPlus20
1456 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1457 : diag::warn_arith_conv_mixed_anon_enum_types;
1458 } else if (ACK == Sema::ACK_Conditional) {
1459 // Conditional expressions are separated out because they have
1460 // historically had a different warning flag.
1461 DiagID = S.getLangOpts().CPlusPlus20
1462 ? diag::warn_conditional_mixed_enum_types_cxx20
1463 : diag::warn_conditional_mixed_enum_types;
1464 } else if (ACK == Sema::ACK_Comparison) {
1465 // Comparison expressions are separated out because they have
1466 // historically had a different warning flag.
1467 DiagID = S.getLangOpts().CPlusPlus20
1468 ? diag::warn_comparison_mixed_enum_types_cxx20
1469 : diag::warn_comparison_mixed_enum_types;
1470 } else {
1471 DiagID = S.getLangOpts().CPlusPlus20
1472 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1473 : diag::warn_arith_conv_mixed_enum_types;
1474 }
1475 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1476 << (int)ACK << L << R;
1477 }
1478 }
1479
1480 /// UsualArithmeticConversions - Performs various conversions that are common to
1481 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1482 /// routine returns the first non-arithmetic type found. The client is
1483 /// responsible for emitting appropriate error diagnostics.
UsualArithmeticConversions(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,ArithConvKind ACK)1484 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1485 SourceLocation Loc,
1486 ArithConvKind ACK) {
1487 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1488
1489 if (ACK != ACK_CompAssign) {
1490 LHS = UsualUnaryConversions(LHS.get());
1491 if (LHS.isInvalid())
1492 return QualType();
1493 }
1494
1495 RHS = UsualUnaryConversions(RHS.get());
1496 if (RHS.isInvalid())
1497 return QualType();
1498
1499 // For conversion purposes, we ignore any qualifiers.
1500 // For example, "const float" and "float" are equivalent.
1501 QualType LHSType =
1502 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1503 QualType RHSType =
1504 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1505
1506 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1507 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1508 LHSType = AtomicLHS->getValueType();
1509
1510 // If both types are identical, no conversion is needed.
1511 if (LHSType == RHSType)
1512 return LHSType;
1513
1514 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1515 // The caller can deal with this (e.g. pointer + int).
1516 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1517 return QualType();
1518
1519 // Apply unary and bitfield promotions to the LHS's type.
1520 QualType LHSUnpromotedType = LHSType;
1521 if (LHSType->isPromotableIntegerType())
1522 LHSType = Context.getPromotedIntegerType(LHSType);
1523 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1524 if (!LHSBitfieldPromoteTy.isNull())
1525 LHSType = LHSBitfieldPromoteTy;
1526 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1527 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1528
1529 // If both types are identical, no conversion is needed.
1530 if (LHSType == RHSType)
1531 return LHSType;
1532
1533 // ExtInt types aren't subject to conversions between them or normal integers,
1534 // so this fails.
1535 if(LHSType->isExtIntType() || RHSType->isExtIntType())
1536 return QualType();
1537
1538 // At this point, we have two different arithmetic types.
1539
1540 // Diagnose attempts to convert between __float128 and long double where
1541 // such conversions currently can't be handled.
1542 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1543 return QualType();
1544
1545 // Handle complex types first (C99 6.3.1.8p1).
1546 if (LHSType->isComplexType() || RHSType->isComplexType())
1547 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1548 ACK == ACK_CompAssign);
1549
1550 // Now handle "real" floating types (i.e. float, double, long double).
1551 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1552 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1553 ACK == ACK_CompAssign);
1554
1555 // Handle GCC complex int extension.
1556 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1557 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1558 ACK == ACK_CompAssign);
1559
1560 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1561 return handleFixedPointConversion(*this, LHSType, RHSType);
1562
1563 // Finally, we have two differing integer types.
1564 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1565 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1566 }
1567
1568 //===----------------------------------------------------------------------===//
1569 // Semantic Analysis for various Expression Types
1570 //===----------------------------------------------------------------------===//
1571
1572
1573 ExprResult
ActOnGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<ParsedType> ArgTypes,ArrayRef<Expr * > ArgExprs)1574 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1575 SourceLocation DefaultLoc,
1576 SourceLocation RParenLoc,
1577 Expr *ControllingExpr,
1578 ArrayRef<ParsedType> ArgTypes,
1579 ArrayRef<Expr *> ArgExprs) {
1580 unsigned NumAssocs = ArgTypes.size();
1581 assert(NumAssocs == ArgExprs.size());
1582
1583 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1584 for (unsigned i = 0; i < NumAssocs; ++i) {
1585 if (ArgTypes[i])
1586 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1587 else
1588 Types[i] = nullptr;
1589 }
1590
1591 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1592 ControllingExpr,
1593 llvm::makeArrayRef(Types, NumAssocs),
1594 ArgExprs);
1595 delete [] Types;
1596 return ER;
1597 }
1598
1599 ExprResult
CreateGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > Types,ArrayRef<Expr * > Exprs)1600 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1601 SourceLocation DefaultLoc,
1602 SourceLocation RParenLoc,
1603 Expr *ControllingExpr,
1604 ArrayRef<TypeSourceInfo *> Types,
1605 ArrayRef<Expr *> Exprs) {
1606 unsigned NumAssocs = Types.size();
1607 assert(NumAssocs == Exprs.size());
1608
1609 // Decay and strip qualifiers for the controlling expression type, and handle
1610 // placeholder type replacement. See committee discussion from WG14 DR423.
1611 {
1612 EnterExpressionEvaluationContext Unevaluated(
1613 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1614 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1615 if (R.isInvalid())
1616 return ExprError();
1617 ControllingExpr = R.get();
1618 }
1619
1620 // The controlling expression is an unevaluated operand, so side effects are
1621 // likely unintended.
1622 if (!inTemplateInstantiation() &&
1623 ControllingExpr->HasSideEffects(Context, false))
1624 Diag(ControllingExpr->getExprLoc(),
1625 diag::warn_side_effects_unevaluated_context);
1626
1627 bool TypeErrorFound = false,
1628 IsResultDependent = ControllingExpr->isTypeDependent(),
1629 ContainsUnexpandedParameterPack
1630 = ControllingExpr->containsUnexpandedParameterPack();
1631
1632 for (unsigned i = 0; i < NumAssocs; ++i) {
1633 if (Exprs[i]->containsUnexpandedParameterPack())
1634 ContainsUnexpandedParameterPack = true;
1635
1636 if (Types[i]) {
1637 if (Types[i]->getType()->containsUnexpandedParameterPack())
1638 ContainsUnexpandedParameterPack = true;
1639
1640 if (Types[i]->getType()->isDependentType()) {
1641 IsResultDependent = true;
1642 } else {
1643 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1644 // complete object type other than a variably modified type."
1645 unsigned D = 0;
1646 if (Types[i]->getType()->isIncompleteType())
1647 D = diag::err_assoc_type_incomplete;
1648 else if (!Types[i]->getType()->isObjectType())
1649 D = diag::err_assoc_type_nonobject;
1650 else if (Types[i]->getType()->isVariablyModifiedType())
1651 D = diag::err_assoc_type_variably_modified;
1652
1653 if (D != 0) {
1654 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1655 << Types[i]->getTypeLoc().getSourceRange()
1656 << Types[i]->getType();
1657 TypeErrorFound = true;
1658 }
1659
1660 // C11 6.5.1.1p2 "No two generic associations in the same generic
1661 // selection shall specify compatible types."
1662 for (unsigned j = i+1; j < NumAssocs; ++j)
1663 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1664 Context.typesAreCompatible(Types[i]->getType(),
1665 Types[j]->getType())) {
1666 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1667 diag::err_assoc_compatible_types)
1668 << Types[j]->getTypeLoc().getSourceRange()
1669 << Types[j]->getType()
1670 << Types[i]->getType();
1671 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1672 diag::note_compat_assoc)
1673 << Types[i]->getTypeLoc().getSourceRange()
1674 << Types[i]->getType();
1675 TypeErrorFound = true;
1676 }
1677 }
1678 }
1679 }
1680 if (TypeErrorFound)
1681 return ExprError();
1682
1683 // If we determined that the generic selection is result-dependent, don't
1684 // try to compute the result expression.
1685 if (IsResultDependent)
1686 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1687 Exprs, DefaultLoc, RParenLoc,
1688 ContainsUnexpandedParameterPack);
1689
1690 SmallVector<unsigned, 1> CompatIndices;
1691 unsigned DefaultIndex = -1U;
1692 for (unsigned i = 0; i < NumAssocs; ++i) {
1693 if (!Types[i])
1694 DefaultIndex = i;
1695 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1696 Types[i]->getType()))
1697 CompatIndices.push_back(i);
1698 }
1699
1700 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1701 // type compatible with at most one of the types named in its generic
1702 // association list."
1703 if (CompatIndices.size() > 1) {
1704 // We strip parens here because the controlling expression is typically
1705 // parenthesized in macro definitions.
1706 ControllingExpr = ControllingExpr->IgnoreParens();
1707 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1708 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1709 << (unsigned)CompatIndices.size();
1710 for (unsigned I : CompatIndices) {
1711 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1712 diag::note_compat_assoc)
1713 << Types[I]->getTypeLoc().getSourceRange()
1714 << Types[I]->getType();
1715 }
1716 return ExprError();
1717 }
1718
1719 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1720 // its controlling expression shall have type compatible with exactly one of
1721 // the types named in its generic association list."
1722 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1723 // We strip parens here because the controlling expression is typically
1724 // parenthesized in macro definitions.
1725 ControllingExpr = ControllingExpr->IgnoreParens();
1726 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1727 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1728 return ExprError();
1729 }
1730
1731 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1732 // type name that is compatible with the type of the controlling expression,
1733 // then the result expression of the generic selection is the expression
1734 // in that generic association. Otherwise, the result expression of the
1735 // generic selection is the expression in the default generic association."
1736 unsigned ResultIndex =
1737 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1738
1739 return GenericSelectionExpr::Create(
1740 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1741 ContainsUnexpandedParameterPack, ResultIndex);
1742 }
1743
1744 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1745 /// location of the token and the offset of the ud-suffix within it.
getUDSuffixLoc(Sema & S,SourceLocation TokLoc,unsigned Offset)1746 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1747 unsigned Offset) {
1748 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1749 S.getLangOpts());
1750 }
1751
1752 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1753 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
BuildCookedLiteralOperatorCall(Sema & S,Scope * Scope,IdentifierInfo * UDSuffix,SourceLocation UDSuffixLoc,ArrayRef<Expr * > Args,SourceLocation LitEndLoc)1754 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1755 IdentifierInfo *UDSuffix,
1756 SourceLocation UDSuffixLoc,
1757 ArrayRef<Expr*> Args,
1758 SourceLocation LitEndLoc) {
1759 assert(Args.size() <= 2 && "too many arguments for literal operator");
1760
1761 QualType ArgTy[2];
1762 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1763 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1764 if (ArgTy[ArgIdx]->isArrayType())
1765 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1766 }
1767
1768 DeclarationName OpName =
1769 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1770 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1771 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1772
1773 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1774 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1775 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1776 /*AllowStringTemplatePack*/ false,
1777 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1778 return ExprError();
1779
1780 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1781 }
1782
1783 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1784 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1785 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1786 /// multiple tokens. However, the common case is that StringToks points to one
1787 /// string.
1788 ///
1789 ExprResult
ActOnStringLiteral(ArrayRef<Token> StringToks,Scope * UDLScope)1790 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1791 assert(!StringToks.empty() && "Must have at least one string!");
1792
1793 StringLiteralParser Literal(StringToks, PP);
1794 if (Literal.hadError)
1795 return ExprError();
1796
1797 SmallVector<SourceLocation, 4> StringTokLocs;
1798 for (const Token &Tok : StringToks)
1799 StringTokLocs.push_back(Tok.getLocation());
1800
1801 QualType CharTy = Context.CharTy;
1802 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1803 if (Literal.isWide()) {
1804 CharTy = Context.getWideCharType();
1805 Kind = StringLiteral::Wide;
1806 } else if (Literal.isUTF8()) {
1807 if (getLangOpts().Char8)
1808 CharTy = Context.Char8Ty;
1809 Kind = StringLiteral::UTF8;
1810 } else if (Literal.isUTF16()) {
1811 CharTy = Context.Char16Ty;
1812 Kind = StringLiteral::UTF16;
1813 } else if (Literal.isUTF32()) {
1814 CharTy = Context.Char32Ty;
1815 Kind = StringLiteral::UTF32;
1816 } else if (Literal.isPascal()) {
1817 CharTy = Context.UnsignedCharTy;
1818 }
1819
1820 // Warn on initializing an array of char from a u8 string literal; this
1821 // becomes ill-formed in C++2a.
1822 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1823 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1824 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1825
1826 // Create removals for all 'u8' prefixes in the string literal(s). This
1827 // ensures C++2a compatibility (but may change the program behavior when
1828 // built by non-Clang compilers for which the execution character set is
1829 // not always UTF-8).
1830 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1831 SourceLocation RemovalDiagLoc;
1832 for (const Token &Tok : StringToks) {
1833 if (Tok.getKind() == tok::utf8_string_literal) {
1834 if (RemovalDiagLoc.isInvalid())
1835 RemovalDiagLoc = Tok.getLocation();
1836 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1837 Tok.getLocation(),
1838 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1839 getSourceManager(), getLangOpts())));
1840 }
1841 }
1842 Diag(RemovalDiagLoc, RemovalDiag);
1843 }
1844
1845 QualType StrTy =
1846 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1847
1848 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1849 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1850 Kind, Literal.Pascal, StrTy,
1851 &StringTokLocs[0],
1852 StringTokLocs.size());
1853 if (Literal.getUDSuffix().empty())
1854 return Lit;
1855
1856 // We're building a user-defined literal.
1857 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1858 SourceLocation UDSuffixLoc =
1859 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1860 Literal.getUDSuffixOffset());
1861
1862 // Make sure we're allowed user-defined literals here.
1863 if (!UDLScope)
1864 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1865
1866 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1867 // operator "" X (str, len)
1868 QualType SizeType = Context.getSizeType();
1869
1870 DeclarationName OpName =
1871 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1872 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1873 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1874
1875 QualType ArgTy[] = {
1876 Context.getArrayDecayedType(StrTy), SizeType
1877 };
1878
1879 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1880 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1881 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1882 /*AllowStringTemplatePack*/ true,
1883 /*DiagnoseMissing*/ true, Lit)) {
1884
1885 case LOLR_Cooked: {
1886 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1887 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1888 StringTokLocs[0]);
1889 Expr *Args[] = { Lit, LenArg };
1890
1891 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1892 }
1893
1894 case LOLR_Template: {
1895 TemplateArgumentListInfo ExplicitArgs;
1896 TemplateArgument Arg(Lit);
1897 TemplateArgumentLocInfo ArgInfo(Lit);
1898 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1899 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1900 &ExplicitArgs);
1901 }
1902
1903 case LOLR_StringTemplatePack: {
1904 TemplateArgumentListInfo ExplicitArgs;
1905
1906 unsigned CharBits = Context.getIntWidth(CharTy);
1907 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1908 llvm::APSInt Value(CharBits, CharIsUnsigned);
1909
1910 TemplateArgument TypeArg(CharTy);
1911 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1912 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1913
1914 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1915 Value = Lit->getCodeUnit(I);
1916 TemplateArgument Arg(Context, Value, CharTy);
1917 TemplateArgumentLocInfo ArgInfo;
1918 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1919 }
1920 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1921 &ExplicitArgs);
1922 }
1923 case LOLR_Raw:
1924 case LOLR_ErrorNoDiagnostic:
1925 llvm_unreachable("unexpected literal operator lookup result");
1926 case LOLR_Error:
1927 return ExprError();
1928 }
1929 llvm_unreachable("unexpected literal operator lookup result");
1930 }
1931
1932 DeclRefExpr *
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,SourceLocation Loc,const CXXScopeSpec * SS)1933 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1934 SourceLocation Loc,
1935 const CXXScopeSpec *SS) {
1936 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1937 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1938 }
1939
1940 DeclRefExpr *
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,const DeclarationNameInfo & NameInfo,const CXXScopeSpec * SS,NamedDecl * FoundD,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)1941 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1942 const DeclarationNameInfo &NameInfo,
1943 const CXXScopeSpec *SS, NamedDecl *FoundD,
1944 SourceLocation TemplateKWLoc,
1945 const TemplateArgumentListInfo *TemplateArgs) {
1946 NestedNameSpecifierLoc NNS =
1947 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1948 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1949 TemplateArgs);
1950 }
1951
1952 // CUDA/HIP: Check whether a captured reference variable is referencing a
1953 // host variable in a device or host device lambda.
isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema & S,VarDecl * VD)1954 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1955 VarDecl *VD) {
1956 if (!S.getLangOpts().CUDA || !VD->hasInit())
1957 return false;
1958 assert(VD->getType()->isReferenceType());
1959
1960 // Check whether the reference variable is referencing a host variable.
1961 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1962 if (!DRE)
1963 return false;
1964 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
1965 if (!Referee || !Referee->hasGlobalStorage() ||
1966 Referee->hasAttr<CUDADeviceAttr>())
1967 return false;
1968
1969 // Check whether the current function is a device or host device lambda.
1970 // Check whether the reference variable is a capture by getDeclContext()
1971 // since refersToEnclosingVariableOrCapture() is not ready at this point.
1972 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
1973 if (MD && MD->getParent()->isLambda() &&
1974 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
1975 VD->getDeclContext() != MD)
1976 return true;
1977
1978 return false;
1979 }
1980
getNonOdrUseReasonInCurrentContext(ValueDecl * D)1981 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1982 // A declaration named in an unevaluated operand never constitutes an odr-use.
1983 if (isUnevaluatedContext())
1984 return NOUR_Unevaluated;
1985
1986 // C++2a [basic.def.odr]p4:
1987 // A variable x whose name appears as a potentially-evaluated expression e
1988 // is odr-used by e unless [...] x is a reference that is usable in
1989 // constant expressions.
1990 // CUDA/HIP:
1991 // If a reference variable referencing a host variable is captured in a
1992 // device or host device lambda, the value of the referee must be copied
1993 // to the capture and the reference variable must be treated as odr-use
1994 // since the value of the referee is not known at compile time and must
1995 // be loaded from the captured.
1996 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1997 if (VD->getType()->isReferenceType() &&
1998 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
1999 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2000 VD->isUsableInConstantExpressions(Context))
2001 return NOUR_Constant;
2002 }
2003
2004 // All remaining non-variable cases constitute an odr-use. For variables, we
2005 // need to wait and see how the expression is used.
2006 return NOUR_None;
2007 }
2008
2009 /// BuildDeclRefExpr - Build an expression that references a
2010 /// declaration that does not require a closure capture.
2011 DeclRefExpr *
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,const DeclarationNameInfo & NameInfo,NestedNameSpecifierLoc NNS,NamedDecl * FoundD,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)2012 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2013 const DeclarationNameInfo &NameInfo,
2014 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2015 SourceLocation TemplateKWLoc,
2016 const TemplateArgumentListInfo *TemplateArgs) {
2017 bool RefersToCapturedVariable =
2018 isa<VarDecl>(D) &&
2019 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2020
2021 DeclRefExpr *E = DeclRefExpr::Create(
2022 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2023 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2024 MarkDeclRefReferenced(E);
2025
2026 // C++ [except.spec]p17:
2027 // An exception-specification is considered to be needed when:
2028 // - in an expression, the function is the unique lookup result or
2029 // the selected member of a set of overloaded functions.
2030 //
2031 // We delay doing this until after we've built the function reference and
2032 // marked it as used so that:
2033 // a) if the function is defaulted, we get errors from defining it before /
2034 // instead of errors from computing its exception specification, and
2035 // b) if the function is a defaulted comparison, we can use the body we
2036 // build when defining it as input to the exception specification
2037 // computation rather than computing a new body.
2038 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2039 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2040 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2041 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2042 }
2043 }
2044
2045 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2046 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2047 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2048 getCurFunction()->recordUseOfWeak(E);
2049
2050 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2051 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2052 FD = IFD->getAnonField();
2053 if (FD) {
2054 UnusedPrivateFields.remove(FD);
2055 // Just in case we're building an illegal pointer-to-member.
2056 if (FD->isBitField())
2057 E->setObjectKind(OK_BitField);
2058 }
2059
2060 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2061 // designates a bit-field.
2062 if (auto *BD = dyn_cast<BindingDecl>(D))
2063 if (auto *BE = BD->getBinding())
2064 E->setObjectKind(BE->getObjectKind());
2065
2066 return E;
2067 }
2068
2069 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2070 /// possibly a list of template arguments.
2071 ///
2072 /// If this produces template arguments, it is permitted to call
2073 /// DecomposeTemplateName.
2074 ///
2075 /// This actually loses a lot of source location information for
2076 /// non-standard name kinds; we should consider preserving that in
2077 /// some way.
2078 void
DecomposeUnqualifiedId(const UnqualifiedId & Id,TemplateArgumentListInfo & Buffer,DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * & TemplateArgs)2079 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2080 TemplateArgumentListInfo &Buffer,
2081 DeclarationNameInfo &NameInfo,
2082 const TemplateArgumentListInfo *&TemplateArgs) {
2083 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2084 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2085 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2086
2087 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2088 Id.TemplateId->NumArgs);
2089 translateTemplateArguments(TemplateArgsPtr, Buffer);
2090
2091 TemplateName TName = Id.TemplateId->Template.get();
2092 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2093 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2094 TemplateArgs = &Buffer;
2095 } else {
2096 NameInfo = GetNameFromUnqualifiedId(Id);
2097 TemplateArgs = nullptr;
2098 }
2099 }
2100
emitEmptyLookupTypoDiagnostic(const TypoCorrection & TC,Sema & SemaRef,const CXXScopeSpec & SS,DeclarationName Typo,SourceLocation TypoLoc,ArrayRef<Expr * > Args,unsigned DiagnosticID,unsigned DiagnosticSuggestID)2101 static void emitEmptyLookupTypoDiagnostic(
2102 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2103 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2104 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2105 DeclContext *Ctx =
2106 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2107 if (!TC) {
2108 // Emit a special diagnostic for failed member lookups.
2109 // FIXME: computing the declaration context might fail here (?)
2110 if (Ctx)
2111 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2112 << SS.getRange();
2113 else
2114 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2115 return;
2116 }
2117
2118 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2119 bool DroppedSpecifier =
2120 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2121 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2122 ? diag::note_implicit_param_decl
2123 : diag::note_previous_decl;
2124 if (!Ctx)
2125 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2126 SemaRef.PDiag(NoteID));
2127 else
2128 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2129 << Typo << Ctx << DroppedSpecifier
2130 << SS.getRange(),
2131 SemaRef.PDiag(NoteID));
2132 }
2133
2134 /// Diagnose a lookup that found results in an enclosing class during error
2135 /// recovery. This usually indicates that the results were found in a dependent
2136 /// base class that could not be searched as part of a template definition.
2137 /// Always issues a diagnostic (though this may be only a warning in MS
2138 /// compatibility mode).
2139 ///
2140 /// Return \c true if the error is unrecoverable, or \c false if the caller
2141 /// should attempt to recover using these lookup results.
DiagnoseDependentMemberLookup(LookupResult & R)2142 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2143 // During a default argument instantiation the CurContext points
2144 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2145 // function parameter list, hence add an explicit check.
2146 bool isDefaultArgument =
2147 !CodeSynthesisContexts.empty() &&
2148 CodeSynthesisContexts.back().Kind ==
2149 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2150 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2151 bool isInstance = CurMethod && CurMethod->isInstance() &&
2152 R.getNamingClass() == CurMethod->getParent() &&
2153 !isDefaultArgument;
2154
2155 // There are two ways we can find a class-scope declaration during template
2156 // instantiation that we did not find in the template definition: if it is a
2157 // member of a dependent base class, or if it is declared after the point of
2158 // use in the same class. Distinguish these by comparing the class in which
2159 // the member was found to the naming class of the lookup.
2160 unsigned DiagID = diag::err_found_in_dependent_base;
2161 unsigned NoteID = diag::note_member_declared_at;
2162 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2163 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2164 : diag::err_found_later_in_class;
2165 } else if (getLangOpts().MSVCCompat) {
2166 DiagID = diag::ext_found_in_dependent_base;
2167 NoteID = diag::note_dependent_member_use;
2168 }
2169
2170 if (isInstance) {
2171 // Give a code modification hint to insert 'this->'.
2172 Diag(R.getNameLoc(), DiagID)
2173 << R.getLookupName()
2174 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2175 CheckCXXThisCapture(R.getNameLoc());
2176 } else {
2177 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2178 // they're not shadowed).
2179 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2180 }
2181
2182 for (NamedDecl *D : R)
2183 Diag(D->getLocation(), NoteID);
2184
2185 // Return true if we are inside a default argument instantiation
2186 // and the found name refers to an instance member function, otherwise
2187 // the caller will try to create an implicit member call and this is wrong
2188 // for default arguments.
2189 //
2190 // FIXME: Is this special case necessary? We could allow the caller to
2191 // diagnose this.
2192 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2193 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2194 return true;
2195 }
2196
2197 // Tell the callee to try to recover.
2198 return false;
2199 }
2200
2201 /// Diagnose an empty lookup.
2202 ///
2203 /// \return false if new lookup candidates were found
DiagnoseEmptyLookup(Scope * S,CXXScopeSpec & SS,LookupResult & R,CorrectionCandidateCallback & CCC,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,TypoExpr ** Out)2204 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2205 CorrectionCandidateCallback &CCC,
2206 TemplateArgumentListInfo *ExplicitTemplateArgs,
2207 ArrayRef<Expr *> Args, TypoExpr **Out) {
2208 DeclarationName Name = R.getLookupName();
2209
2210 unsigned diagnostic = diag::err_undeclared_var_use;
2211 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2212 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2213 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2214 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2215 diagnostic = diag::err_undeclared_use;
2216 diagnostic_suggest = diag::err_undeclared_use_suggest;
2217 }
2218
2219 // If the original lookup was an unqualified lookup, fake an
2220 // unqualified lookup. This is useful when (for example) the
2221 // original lookup would not have found something because it was a
2222 // dependent name.
2223 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2224 while (DC) {
2225 if (isa<CXXRecordDecl>(DC)) {
2226 LookupQualifiedName(R, DC);
2227
2228 if (!R.empty()) {
2229 // Don't give errors about ambiguities in this lookup.
2230 R.suppressDiagnostics();
2231
2232 // If there's a best viable function among the results, only mention
2233 // that one in the notes.
2234 OverloadCandidateSet Candidates(R.getNameLoc(),
2235 OverloadCandidateSet::CSK_Normal);
2236 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2237 OverloadCandidateSet::iterator Best;
2238 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2239 OR_Success) {
2240 R.clear();
2241 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2242 R.resolveKind();
2243 }
2244
2245 return DiagnoseDependentMemberLookup(R);
2246 }
2247
2248 R.clear();
2249 }
2250
2251 DC = DC->getLookupParent();
2252 }
2253
2254 // We didn't find anything, so try to correct for a typo.
2255 TypoCorrection Corrected;
2256 if (S && Out) {
2257 SourceLocation TypoLoc = R.getNameLoc();
2258 assert(!ExplicitTemplateArgs &&
2259 "Diagnosing an empty lookup with explicit template args!");
2260 *Out = CorrectTypoDelayed(
2261 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2262 [=](const TypoCorrection &TC) {
2263 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2264 diagnostic, diagnostic_suggest);
2265 },
2266 nullptr, CTK_ErrorRecovery);
2267 if (*Out)
2268 return true;
2269 } else if (S &&
2270 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2271 S, &SS, CCC, CTK_ErrorRecovery))) {
2272 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2273 bool DroppedSpecifier =
2274 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2275 R.setLookupName(Corrected.getCorrection());
2276
2277 bool AcceptableWithRecovery = false;
2278 bool AcceptableWithoutRecovery = false;
2279 NamedDecl *ND = Corrected.getFoundDecl();
2280 if (ND) {
2281 if (Corrected.isOverloaded()) {
2282 OverloadCandidateSet OCS(R.getNameLoc(),
2283 OverloadCandidateSet::CSK_Normal);
2284 OverloadCandidateSet::iterator Best;
2285 for (NamedDecl *CD : Corrected) {
2286 if (FunctionTemplateDecl *FTD =
2287 dyn_cast<FunctionTemplateDecl>(CD))
2288 AddTemplateOverloadCandidate(
2289 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2290 Args, OCS);
2291 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2292 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2293 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2294 Args, OCS);
2295 }
2296 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2297 case OR_Success:
2298 ND = Best->FoundDecl;
2299 Corrected.setCorrectionDecl(ND);
2300 break;
2301 default:
2302 // FIXME: Arbitrarily pick the first declaration for the note.
2303 Corrected.setCorrectionDecl(ND);
2304 break;
2305 }
2306 }
2307 R.addDecl(ND);
2308 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2309 CXXRecordDecl *Record = nullptr;
2310 if (Corrected.getCorrectionSpecifier()) {
2311 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2312 Record = Ty->getAsCXXRecordDecl();
2313 }
2314 if (!Record)
2315 Record = cast<CXXRecordDecl>(
2316 ND->getDeclContext()->getRedeclContext());
2317 R.setNamingClass(Record);
2318 }
2319
2320 auto *UnderlyingND = ND->getUnderlyingDecl();
2321 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2322 isa<FunctionTemplateDecl>(UnderlyingND);
2323 // FIXME: If we ended up with a typo for a type name or
2324 // Objective-C class name, we're in trouble because the parser
2325 // is in the wrong place to recover. Suggest the typo
2326 // correction, but don't make it a fix-it since we're not going
2327 // to recover well anyway.
2328 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2329 getAsTypeTemplateDecl(UnderlyingND) ||
2330 isa<ObjCInterfaceDecl>(UnderlyingND);
2331 } else {
2332 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2333 // because we aren't able to recover.
2334 AcceptableWithoutRecovery = true;
2335 }
2336
2337 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2338 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2339 ? diag::note_implicit_param_decl
2340 : diag::note_previous_decl;
2341 if (SS.isEmpty())
2342 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2343 PDiag(NoteID), AcceptableWithRecovery);
2344 else
2345 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2346 << Name << computeDeclContext(SS, false)
2347 << DroppedSpecifier << SS.getRange(),
2348 PDiag(NoteID), AcceptableWithRecovery);
2349
2350 // Tell the callee whether to try to recover.
2351 return !AcceptableWithRecovery;
2352 }
2353 }
2354 R.clear();
2355
2356 // Emit a special diagnostic for failed member lookups.
2357 // FIXME: computing the declaration context might fail here (?)
2358 if (!SS.isEmpty()) {
2359 Diag(R.getNameLoc(), diag::err_no_member)
2360 << Name << computeDeclContext(SS, false)
2361 << SS.getRange();
2362 return true;
2363 }
2364
2365 // Give up, we can't recover.
2366 Diag(R.getNameLoc(), diagnostic) << Name;
2367 return true;
2368 }
2369
2370 /// In Microsoft mode, if we are inside a template class whose parent class has
2371 /// dependent base classes, and we can't resolve an unqualified identifier, then
2372 /// assume the identifier is a member of a dependent base class. We can only
2373 /// recover successfully in static methods, instance methods, and other contexts
2374 /// where 'this' is available. This doesn't precisely match MSVC's
2375 /// instantiation model, but it's close enough.
2376 static Expr *
recoverFromMSUnqualifiedLookup(Sema & S,ASTContext & Context,DeclarationNameInfo & NameInfo,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)2377 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2378 DeclarationNameInfo &NameInfo,
2379 SourceLocation TemplateKWLoc,
2380 const TemplateArgumentListInfo *TemplateArgs) {
2381 // Only try to recover from lookup into dependent bases in static methods or
2382 // contexts where 'this' is available.
2383 QualType ThisType = S.getCurrentThisType();
2384 const CXXRecordDecl *RD = nullptr;
2385 if (!ThisType.isNull())
2386 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2387 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2388 RD = MD->getParent();
2389 if (!RD || !RD->hasAnyDependentBases())
2390 return nullptr;
2391
2392 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2393 // is available, suggest inserting 'this->' as a fixit.
2394 SourceLocation Loc = NameInfo.getLoc();
2395 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2396 DB << NameInfo.getName() << RD;
2397
2398 if (!ThisType.isNull()) {
2399 DB << FixItHint::CreateInsertion(Loc, "this->");
2400 return CXXDependentScopeMemberExpr::Create(
2401 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2402 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2403 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2404 }
2405
2406 // Synthesize a fake NNS that points to the derived class. This will
2407 // perform name lookup during template instantiation.
2408 CXXScopeSpec SS;
2409 auto *NNS =
2410 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2411 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2412 return DependentScopeDeclRefExpr::Create(
2413 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2414 TemplateArgs);
2415 }
2416
2417 ExprResult
ActOnIdExpression(Scope * S,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & Id,bool HasTrailingLParen,bool IsAddressOfOperand,CorrectionCandidateCallback * CCC,bool IsInlineAsmIdentifier,Token * KeywordReplacement)2418 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2419 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2420 bool HasTrailingLParen, bool IsAddressOfOperand,
2421 CorrectionCandidateCallback *CCC,
2422 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2423 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2424 "cannot be direct & operand and have a trailing lparen");
2425 if (SS.isInvalid())
2426 return ExprError();
2427
2428 TemplateArgumentListInfo TemplateArgsBuffer;
2429
2430 // Decompose the UnqualifiedId into the following data.
2431 DeclarationNameInfo NameInfo;
2432 const TemplateArgumentListInfo *TemplateArgs;
2433 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2434
2435 DeclarationName Name = NameInfo.getName();
2436 IdentifierInfo *II = Name.getAsIdentifierInfo();
2437 SourceLocation NameLoc = NameInfo.getLoc();
2438
2439 if (II && II->isEditorPlaceholder()) {
2440 // FIXME: When typed placeholders are supported we can create a typed
2441 // placeholder expression node.
2442 return ExprError();
2443 }
2444
2445 // C++ [temp.dep.expr]p3:
2446 // An id-expression is type-dependent if it contains:
2447 // -- an identifier that was declared with a dependent type,
2448 // (note: handled after lookup)
2449 // -- a template-id that is dependent,
2450 // (note: handled in BuildTemplateIdExpr)
2451 // -- a conversion-function-id that specifies a dependent type,
2452 // -- a nested-name-specifier that contains a class-name that
2453 // names a dependent type.
2454 // Determine whether this is a member of an unknown specialization;
2455 // we need to handle these differently.
2456 bool DependentID = false;
2457 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2458 Name.getCXXNameType()->isDependentType()) {
2459 DependentID = true;
2460 } else if (SS.isSet()) {
2461 if (DeclContext *DC = computeDeclContext(SS, false)) {
2462 if (RequireCompleteDeclContext(SS, DC))
2463 return ExprError();
2464 } else {
2465 DependentID = true;
2466 }
2467 }
2468
2469 if (DependentID)
2470 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2471 IsAddressOfOperand, TemplateArgs);
2472
2473 // Perform the required lookup.
2474 LookupResult R(*this, NameInfo,
2475 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2476 ? LookupObjCImplicitSelfParam
2477 : LookupOrdinaryName);
2478 if (TemplateKWLoc.isValid() || TemplateArgs) {
2479 // Lookup the template name again to correctly establish the context in
2480 // which it was found. This is really unfortunate as we already did the
2481 // lookup to determine that it was a template name in the first place. If
2482 // this becomes a performance hit, we can work harder to preserve those
2483 // results until we get here but it's likely not worth it.
2484 bool MemberOfUnknownSpecialization;
2485 AssumedTemplateKind AssumedTemplate;
2486 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2487 MemberOfUnknownSpecialization, TemplateKWLoc,
2488 &AssumedTemplate))
2489 return ExprError();
2490
2491 if (MemberOfUnknownSpecialization ||
2492 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2493 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2494 IsAddressOfOperand, TemplateArgs);
2495 } else {
2496 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2497 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2498
2499 // If the result might be in a dependent base class, this is a dependent
2500 // id-expression.
2501 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2502 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2503 IsAddressOfOperand, TemplateArgs);
2504
2505 // If this reference is in an Objective-C method, then we need to do
2506 // some special Objective-C lookup, too.
2507 if (IvarLookupFollowUp) {
2508 ExprResult E(LookupInObjCMethod(R, S, II, true));
2509 if (E.isInvalid())
2510 return ExprError();
2511
2512 if (Expr *Ex = E.getAs<Expr>())
2513 return Ex;
2514 }
2515 }
2516
2517 if (R.isAmbiguous())
2518 return ExprError();
2519
2520 // This could be an implicitly declared function reference (legal in C90,
2521 // extension in C99, forbidden in C++).
2522 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2523 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2524 if (D) R.addDecl(D);
2525 }
2526
2527 // Determine whether this name might be a candidate for
2528 // argument-dependent lookup.
2529 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2530
2531 if (R.empty() && !ADL) {
2532 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2533 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2534 TemplateKWLoc, TemplateArgs))
2535 return E;
2536 }
2537
2538 // Don't diagnose an empty lookup for inline assembly.
2539 if (IsInlineAsmIdentifier)
2540 return ExprError();
2541
2542 // If this name wasn't predeclared and if this is not a function
2543 // call, diagnose the problem.
2544 TypoExpr *TE = nullptr;
2545 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2546 : nullptr);
2547 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2548 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2549 "Typo correction callback misconfigured");
2550 if (CCC) {
2551 // Make sure the callback knows what the typo being diagnosed is.
2552 CCC->setTypoName(II);
2553 if (SS.isValid())
2554 CCC->setTypoNNS(SS.getScopeRep());
2555 }
2556 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2557 // a template name, but we happen to have always already looked up the name
2558 // before we get here if it must be a template name.
2559 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2560 None, &TE)) {
2561 if (TE && KeywordReplacement) {
2562 auto &State = getTypoExprState(TE);
2563 auto BestTC = State.Consumer->getNextCorrection();
2564 if (BestTC.isKeyword()) {
2565 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2566 if (State.DiagHandler)
2567 State.DiagHandler(BestTC);
2568 KeywordReplacement->startToken();
2569 KeywordReplacement->setKind(II->getTokenID());
2570 KeywordReplacement->setIdentifierInfo(II);
2571 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2572 // Clean up the state associated with the TypoExpr, since it has
2573 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2574 clearDelayedTypo(TE);
2575 // Signal that a correction to a keyword was performed by returning a
2576 // valid-but-null ExprResult.
2577 return (Expr*)nullptr;
2578 }
2579 State.Consumer->resetCorrectionStream();
2580 }
2581 return TE ? TE : ExprError();
2582 }
2583
2584 assert(!R.empty() &&
2585 "DiagnoseEmptyLookup returned false but added no results");
2586
2587 // If we found an Objective-C instance variable, let
2588 // LookupInObjCMethod build the appropriate expression to
2589 // reference the ivar.
2590 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2591 R.clear();
2592 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2593 // In a hopelessly buggy code, Objective-C instance variable
2594 // lookup fails and no expression will be built to reference it.
2595 if (!E.isInvalid() && !E.get())
2596 return ExprError();
2597 return E;
2598 }
2599 }
2600
2601 // This is guaranteed from this point on.
2602 assert(!R.empty() || ADL);
2603
2604 // Check whether this might be a C++ implicit instance member access.
2605 // C++ [class.mfct.non-static]p3:
2606 // When an id-expression that is not part of a class member access
2607 // syntax and not used to form a pointer to member is used in the
2608 // body of a non-static member function of class X, if name lookup
2609 // resolves the name in the id-expression to a non-static non-type
2610 // member of some class C, the id-expression is transformed into a
2611 // class member access expression using (*this) as the
2612 // postfix-expression to the left of the . operator.
2613 //
2614 // But we don't actually need to do this for '&' operands if R
2615 // resolved to a function or overloaded function set, because the
2616 // expression is ill-formed if it actually works out to be a
2617 // non-static member function:
2618 //
2619 // C++ [expr.ref]p4:
2620 // Otherwise, if E1.E2 refers to a non-static member function. . .
2621 // [t]he expression can be used only as the left-hand operand of a
2622 // member function call.
2623 //
2624 // There are other safeguards against such uses, but it's important
2625 // to get this right here so that we don't end up making a
2626 // spuriously dependent expression if we're inside a dependent
2627 // instance method.
2628 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2629 bool MightBeImplicitMember;
2630 if (!IsAddressOfOperand)
2631 MightBeImplicitMember = true;
2632 else if (!SS.isEmpty())
2633 MightBeImplicitMember = false;
2634 else if (R.isOverloadedResult())
2635 MightBeImplicitMember = false;
2636 else if (R.isUnresolvableResult())
2637 MightBeImplicitMember = true;
2638 else
2639 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2640 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2641 isa<MSPropertyDecl>(R.getFoundDecl());
2642
2643 if (MightBeImplicitMember)
2644 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2645 R, TemplateArgs, S);
2646 }
2647
2648 if (TemplateArgs || TemplateKWLoc.isValid()) {
2649
2650 // In C++1y, if this is a variable template id, then check it
2651 // in BuildTemplateIdExpr().
2652 // The single lookup result must be a variable template declaration.
2653 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2654 Id.TemplateId->Kind == TNK_Var_template) {
2655 assert(R.getAsSingle<VarTemplateDecl>() &&
2656 "There should only be one declaration found.");
2657 }
2658
2659 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2660 }
2661
2662 return BuildDeclarationNameExpr(SS, R, ADL);
2663 }
2664
2665 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2666 /// declaration name, generally during template instantiation.
2667 /// There's a large number of things which don't need to be done along
2668 /// this path.
BuildQualifiedDeclarationNameExpr(CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,bool IsAddressOfOperand,const Scope * S,TypeSourceInfo ** RecoveryTSI)2669 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2670 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2671 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2672 DeclContext *DC = computeDeclContext(SS, false);
2673 if (!DC)
2674 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2675 NameInfo, /*TemplateArgs=*/nullptr);
2676
2677 if (RequireCompleteDeclContext(SS, DC))
2678 return ExprError();
2679
2680 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2681 LookupQualifiedName(R, DC);
2682
2683 if (R.isAmbiguous())
2684 return ExprError();
2685
2686 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2687 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2688 NameInfo, /*TemplateArgs=*/nullptr);
2689
2690 if (R.empty()) {
2691 // Don't diagnose problems with invalid record decl, the secondary no_member
2692 // diagnostic during template instantiation is likely bogus, e.g. if a class
2693 // is invalid because it's derived from an invalid base class, then missing
2694 // members were likely supposed to be inherited.
2695 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2696 if (CD->isInvalidDecl())
2697 return ExprError();
2698 Diag(NameInfo.getLoc(), diag::err_no_member)
2699 << NameInfo.getName() << DC << SS.getRange();
2700 return ExprError();
2701 }
2702
2703 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2704 // Diagnose a missing typename if this resolved unambiguously to a type in
2705 // a dependent context. If we can recover with a type, downgrade this to
2706 // a warning in Microsoft compatibility mode.
2707 unsigned DiagID = diag::err_typename_missing;
2708 if (RecoveryTSI && getLangOpts().MSVCCompat)
2709 DiagID = diag::ext_typename_missing;
2710 SourceLocation Loc = SS.getBeginLoc();
2711 auto D = Diag(Loc, DiagID);
2712 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2713 << SourceRange(Loc, NameInfo.getEndLoc());
2714
2715 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2716 // context.
2717 if (!RecoveryTSI)
2718 return ExprError();
2719
2720 // Only issue the fixit if we're prepared to recover.
2721 D << FixItHint::CreateInsertion(Loc, "typename ");
2722
2723 // Recover by pretending this was an elaborated type.
2724 QualType Ty = Context.getTypeDeclType(TD);
2725 TypeLocBuilder TLB;
2726 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2727
2728 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2729 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2730 QTL.setElaboratedKeywordLoc(SourceLocation());
2731 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2732
2733 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2734
2735 return ExprEmpty();
2736 }
2737
2738 // Defend against this resolving to an implicit member access. We usually
2739 // won't get here if this might be a legitimate a class member (we end up in
2740 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2741 // a pointer-to-member or in an unevaluated context in C++11.
2742 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2743 return BuildPossibleImplicitMemberExpr(SS,
2744 /*TemplateKWLoc=*/SourceLocation(),
2745 R, /*TemplateArgs=*/nullptr, S);
2746
2747 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2748 }
2749
2750 /// The parser has read a name in, and Sema has detected that we're currently
2751 /// inside an ObjC method. Perform some additional checks and determine if we
2752 /// should form a reference to an ivar.
2753 ///
2754 /// Ideally, most of this would be done by lookup, but there's
2755 /// actually quite a lot of extra work involved.
LookupIvarInObjCMethod(LookupResult & Lookup,Scope * S,IdentifierInfo * II)2756 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2757 IdentifierInfo *II) {
2758 SourceLocation Loc = Lookup.getNameLoc();
2759 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2760
2761 // Check for error condition which is already reported.
2762 if (!CurMethod)
2763 return DeclResult(true);
2764
2765 // There are two cases to handle here. 1) scoped lookup could have failed,
2766 // in which case we should look for an ivar. 2) scoped lookup could have
2767 // found a decl, but that decl is outside the current instance method (i.e.
2768 // a global variable). In these two cases, we do a lookup for an ivar with
2769 // this name, if the lookup sucedes, we replace it our current decl.
2770
2771 // If we're in a class method, we don't normally want to look for
2772 // ivars. But if we don't find anything else, and there's an
2773 // ivar, that's an error.
2774 bool IsClassMethod = CurMethod->isClassMethod();
2775
2776 bool LookForIvars;
2777 if (Lookup.empty())
2778 LookForIvars = true;
2779 else if (IsClassMethod)
2780 LookForIvars = false;
2781 else
2782 LookForIvars = (Lookup.isSingleResult() &&
2783 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2784 ObjCInterfaceDecl *IFace = nullptr;
2785 if (LookForIvars) {
2786 IFace = CurMethod->getClassInterface();
2787 ObjCInterfaceDecl *ClassDeclared;
2788 ObjCIvarDecl *IV = nullptr;
2789 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2790 // Diagnose using an ivar in a class method.
2791 if (IsClassMethod) {
2792 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2793 return DeclResult(true);
2794 }
2795
2796 // Diagnose the use of an ivar outside of the declaring class.
2797 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2798 !declaresSameEntity(ClassDeclared, IFace) &&
2799 !getLangOpts().DebuggerSupport)
2800 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2801
2802 // Success.
2803 return IV;
2804 }
2805 } else if (CurMethod->isInstanceMethod()) {
2806 // We should warn if a local variable hides an ivar.
2807 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2808 ObjCInterfaceDecl *ClassDeclared;
2809 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2810 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2811 declaresSameEntity(IFace, ClassDeclared))
2812 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2813 }
2814 }
2815 } else if (Lookup.isSingleResult() &&
2816 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2817 // If accessing a stand-alone ivar in a class method, this is an error.
2818 if (const ObjCIvarDecl *IV =
2819 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2820 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2821 return DeclResult(true);
2822 }
2823 }
2824
2825 // Didn't encounter an error, didn't find an ivar.
2826 return DeclResult(false);
2827 }
2828
BuildIvarRefExpr(Scope * S,SourceLocation Loc,ObjCIvarDecl * IV)2829 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2830 ObjCIvarDecl *IV) {
2831 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2832 assert(CurMethod && CurMethod->isInstanceMethod() &&
2833 "should not reference ivar from this context");
2834
2835 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2836 assert(IFace && "should not reference ivar from this context");
2837
2838 // If we're referencing an invalid decl, just return this as a silent
2839 // error node. The error diagnostic was already emitted on the decl.
2840 if (IV->isInvalidDecl())
2841 return ExprError();
2842
2843 // Check if referencing a field with __attribute__((deprecated)).
2844 if (DiagnoseUseOfDecl(IV, Loc))
2845 return ExprError();
2846
2847 // FIXME: This should use a new expr for a direct reference, don't
2848 // turn this into Self->ivar, just return a BareIVarExpr or something.
2849 IdentifierInfo &II = Context.Idents.get("self");
2850 UnqualifiedId SelfName;
2851 SelfName.setImplicitSelfParam(&II);
2852 CXXScopeSpec SelfScopeSpec;
2853 SourceLocation TemplateKWLoc;
2854 ExprResult SelfExpr =
2855 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2856 /*HasTrailingLParen=*/false,
2857 /*IsAddressOfOperand=*/false);
2858 if (SelfExpr.isInvalid())
2859 return ExprError();
2860
2861 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2862 if (SelfExpr.isInvalid())
2863 return ExprError();
2864
2865 MarkAnyDeclReferenced(Loc, IV, true);
2866
2867 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2868 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2869 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2870 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2871
2872 ObjCIvarRefExpr *Result = new (Context)
2873 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2874 IV->getLocation(), SelfExpr.get(), true, true);
2875
2876 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2877 if (!isUnevaluatedContext() &&
2878 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2879 getCurFunction()->recordUseOfWeak(Result);
2880 }
2881 if (getLangOpts().ObjCAutoRefCount)
2882 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2883 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2884
2885 return Result;
2886 }
2887
2888 /// The parser has read a name in, and Sema has detected that we're currently
2889 /// inside an ObjC method. Perform some additional checks and determine if we
2890 /// should form a reference to an ivar. If so, build an expression referencing
2891 /// that ivar.
2892 ExprResult
LookupInObjCMethod(LookupResult & Lookup,Scope * S,IdentifierInfo * II,bool AllowBuiltinCreation)2893 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2894 IdentifierInfo *II, bool AllowBuiltinCreation) {
2895 // FIXME: Integrate this lookup step into LookupParsedName.
2896 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2897 if (Ivar.isInvalid())
2898 return ExprError();
2899 if (Ivar.isUsable())
2900 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2901 cast<ObjCIvarDecl>(Ivar.get()));
2902
2903 if (Lookup.empty() && II && AllowBuiltinCreation)
2904 LookupBuiltin(Lookup);
2905
2906 // Sentinel value saying that we didn't do anything special.
2907 return ExprResult(false);
2908 }
2909
2910 /// Cast a base object to a member's actual type.
2911 ///
2912 /// There are two relevant checks:
2913 ///
2914 /// C++ [class.access.base]p7:
2915 ///
2916 /// If a class member access operator [...] is used to access a non-static
2917 /// data member or non-static member function, the reference is ill-formed if
2918 /// the left operand [...] cannot be implicitly converted to a pointer to the
2919 /// naming class of the right operand.
2920 ///
2921 /// C++ [expr.ref]p7:
2922 ///
2923 /// If E2 is a non-static data member or a non-static member function, the
2924 /// program is ill-formed if the class of which E2 is directly a member is an
2925 /// ambiguous base (11.8) of the naming class (11.9.3) of E2.
2926 ///
2927 /// Note that the latter check does not consider access; the access of the
2928 /// "real" base class is checked as appropriate when checking the access of the
2929 /// member name.
2930 ExprResult
PerformObjectMemberConversion(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,NamedDecl * Member)2931 Sema::PerformObjectMemberConversion(Expr *From,
2932 NestedNameSpecifier *Qualifier,
2933 NamedDecl *FoundDecl,
2934 NamedDecl *Member) {
2935 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2936 if (!RD)
2937 return From;
2938
2939 QualType DestRecordType;
2940 QualType DestType;
2941 QualType FromRecordType;
2942 QualType FromType = From->getType();
2943 bool PointerConversions = false;
2944 if (isa<FieldDecl>(Member)) {
2945 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2946 auto FromPtrType = FromType->getAs<PointerType>();
2947 DestRecordType = Context.getAddrSpaceQualType(
2948 DestRecordType, FromPtrType
2949 ? FromType->getPointeeType().getAddressSpace()
2950 : FromType.getAddressSpace());
2951
2952 if (FromPtrType) {
2953 DestType = Context.getPointerType(DestRecordType);
2954 FromRecordType = FromPtrType->getPointeeType();
2955 PointerConversions = true;
2956 } else {
2957 DestType = DestRecordType;
2958 FromRecordType = FromType;
2959 }
2960 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2961 if (Method->isStatic())
2962 return From;
2963
2964 DestType = Method->getThisType();
2965 DestRecordType = DestType->getPointeeType();
2966
2967 if (FromType->getAs<PointerType>()) {
2968 FromRecordType = FromType->getPointeeType();
2969 PointerConversions = true;
2970 } else {
2971 FromRecordType = FromType;
2972 DestType = DestRecordType;
2973 }
2974
2975 LangAS FromAS = FromRecordType.getAddressSpace();
2976 LangAS DestAS = DestRecordType.getAddressSpace();
2977 if (FromAS != DestAS) {
2978 QualType FromRecordTypeWithoutAS =
2979 Context.removeAddrSpaceQualType(FromRecordType);
2980 QualType FromTypeWithDestAS =
2981 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2982 if (PointerConversions)
2983 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2984 From = ImpCastExprToType(From, FromTypeWithDestAS,
2985 CK_AddressSpaceConversion, From->getValueKind())
2986 .get();
2987 }
2988 } else {
2989 // No conversion necessary.
2990 return From;
2991 }
2992
2993 if (DestType->isDependentType() || FromType->isDependentType())
2994 return From;
2995
2996 // If the unqualified types are the same, no conversion is necessary.
2997 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2998 return From;
2999
3000 SourceRange FromRange = From->getSourceRange();
3001 SourceLocation FromLoc = FromRange.getBegin();
3002
3003 ExprValueKind VK = From->getValueKind();
3004
3005 // C++ [class.member.lookup]p8:
3006 // [...] Ambiguities can often be resolved by qualifying a name with its
3007 // class name.
3008 //
3009 // If the member was a qualified name and the qualified referred to a
3010 // specific base subobject type, we'll cast to that intermediate type
3011 // first and then to the object in which the member is declared. That allows
3012 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3013 //
3014 // class Base { public: int x; };
3015 // class Derived1 : public Base { };
3016 // class Derived2 : public Base { };
3017 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3018 //
3019 // void VeryDerived::f() {
3020 // x = 17; // error: ambiguous base subobjects
3021 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3022 // }
3023 if (Qualifier && Qualifier->getAsType()) {
3024 QualType QType = QualType(Qualifier->getAsType(), 0);
3025 assert(QType->isRecordType() && "lookup done with non-record type");
3026
3027 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
3028
3029 // In C++98, the qualifier type doesn't actually have to be a base
3030 // type of the object type, in which case we just ignore it.
3031 // Otherwise build the appropriate casts.
3032 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3033 CXXCastPath BasePath;
3034 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3035 FromLoc, FromRange, &BasePath))
3036 return ExprError();
3037
3038 if (PointerConversions)
3039 QType = Context.getPointerType(QType);
3040 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3041 VK, &BasePath).get();
3042
3043 FromType = QType;
3044 FromRecordType = QRecordType;
3045
3046 // If the qualifier type was the same as the destination type,
3047 // we're done.
3048 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3049 return From;
3050 }
3051 }
3052
3053 CXXCastPath BasePath;
3054 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3055 FromLoc, FromRange, &BasePath,
3056 /*IgnoreAccess=*/true))
3057 return ExprError();
3058
3059 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3060 VK, &BasePath);
3061 }
3062
UseArgumentDependentLookup(const CXXScopeSpec & SS,const LookupResult & R,bool HasTrailingLParen)3063 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3064 const LookupResult &R,
3065 bool HasTrailingLParen) {
3066 // Only when used directly as the postfix-expression of a call.
3067 if (!HasTrailingLParen)
3068 return false;
3069
3070 // Never if a scope specifier was provided.
3071 if (SS.isSet())
3072 return false;
3073
3074 // Only in C++ or ObjC++.
3075 if (!getLangOpts().CPlusPlus)
3076 return false;
3077
3078 // Turn off ADL when we find certain kinds of declarations during
3079 // normal lookup:
3080 for (NamedDecl *D : R) {
3081 // C++0x [basic.lookup.argdep]p3:
3082 // -- a declaration of a class member
3083 // Since using decls preserve this property, we check this on the
3084 // original decl.
3085 if (D->isCXXClassMember())
3086 return false;
3087
3088 // C++0x [basic.lookup.argdep]p3:
3089 // -- a block-scope function declaration that is not a
3090 // using-declaration
3091 // NOTE: we also trigger this for function templates (in fact, we
3092 // don't check the decl type at all, since all other decl types
3093 // turn off ADL anyway).
3094 if (isa<UsingShadowDecl>(D))
3095 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3096 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3097 return false;
3098
3099 // C++0x [basic.lookup.argdep]p3:
3100 // -- a declaration that is neither a function or a function
3101 // template
3102 // And also for builtin functions.
3103 if (isa<FunctionDecl>(D)) {
3104 FunctionDecl *FDecl = cast<FunctionDecl>(D);
3105
3106 // But also builtin functions.
3107 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3108 return false;
3109 } else if (!isa<FunctionTemplateDecl>(D))
3110 return false;
3111 }
3112
3113 return true;
3114 }
3115
3116
3117 /// Diagnoses obvious problems with the use of the given declaration
3118 /// as an expression. This is only actually called for lookups that
3119 /// were not overloaded, and it doesn't promise that the declaration
3120 /// will in fact be used.
CheckDeclInExpr(Sema & S,SourceLocation Loc,NamedDecl * D)3121 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3122 if (D->isInvalidDecl())
3123 return true;
3124
3125 if (isa<TypedefNameDecl>(D)) {
3126 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3127 return true;
3128 }
3129
3130 if (isa<ObjCInterfaceDecl>(D)) {
3131 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3132 return true;
3133 }
3134
3135 if (isa<NamespaceDecl>(D)) {
3136 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3137 return true;
3138 }
3139
3140 return false;
3141 }
3142
3143 // Certain multiversion types should be treated as overloaded even when there is
3144 // only one result.
ShouldLookupResultBeMultiVersionOverload(const LookupResult & R)3145 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3146 assert(R.isSingleResult() && "Expected only a single result");
3147 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3148 return FD &&
3149 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3150 }
3151
BuildDeclarationNameExpr(const CXXScopeSpec & SS,LookupResult & R,bool NeedsADL,bool AcceptInvalidDecl)3152 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3153 LookupResult &R, bool NeedsADL,
3154 bool AcceptInvalidDecl) {
3155 // If this is a single, fully-resolved result and we don't need ADL,
3156 // just build an ordinary singleton decl ref.
3157 if (!NeedsADL && R.isSingleResult() &&
3158 !R.getAsSingle<FunctionTemplateDecl>() &&
3159 !ShouldLookupResultBeMultiVersionOverload(R))
3160 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3161 R.getRepresentativeDecl(), nullptr,
3162 AcceptInvalidDecl);
3163
3164 // We only need to check the declaration if there's exactly one
3165 // result, because in the overloaded case the results can only be
3166 // functions and function templates.
3167 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3168 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3169 return ExprError();
3170
3171 // Otherwise, just build an unresolved lookup expression. Suppress
3172 // any lookup-related diagnostics; we'll hash these out later, when
3173 // we've picked a target.
3174 R.suppressDiagnostics();
3175
3176 UnresolvedLookupExpr *ULE
3177 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3178 SS.getWithLocInContext(Context),
3179 R.getLookupNameInfo(),
3180 NeedsADL, R.isOverloadedResult(),
3181 R.begin(), R.end());
3182
3183 return ULE;
3184 }
3185
3186 static void
3187 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3188 ValueDecl *var, DeclContext *DC);
3189
3190 /// Complete semantic analysis for a reference to the given declaration.
BuildDeclarationNameExpr(const CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,NamedDecl * D,NamedDecl * FoundD,const TemplateArgumentListInfo * TemplateArgs,bool AcceptInvalidDecl)3191 ExprResult Sema::BuildDeclarationNameExpr(
3192 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3193 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3194 bool AcceptInvalidDecl) {
3195 assert(D && "Cannot refer to a NULL declaration");
3196 assert(!isa<FunctionTemplateDecl>(D) &&
3197 "Cannot refer unambiguously to a function template");
3198
3199 SourceLocation Loc = NameInfo.getLoc();
3200 if (CheckDeclInExpr(*this, Loc, D))
3201 return ExprError();
3202
3203 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3204 // Specifically diagnose references to class templates that are missing
3205 // a template argument list.
3206 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3207 return ExprError();
3208 }
3209
3210 // Make sure that we're referring to a value.
3211 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3212 if (!VD) {
3213 Diag(Loc, diag::err_ref_non_value)
3214 << D << SS.getRange();
3215 Diag(D->getLocation(), diag::note_declared_at);
3216 return ExprError();
3217 }
3218
3219 // Check whether this declaration can be used. Note that we suppress
3220 // this check when we're going to perform argument-dependent lookup
3221 // on this function name, because this might not be the function
3222 // that overload resolution actually selects.
3223 if (DiagnoseUseOfDecl(VD, Loc))
3224 return ExprError();
3225
3226 // Only create DeclRefExpr's for valid Decl's.
3227 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3228 return ExprError();
3229
3230 // Handle members of anonymous structs and unions. If we got here,
3231 // and the reference is to a class member indirect field, then this
3232 // must be the subject of a pointer-to-member expression.
3233 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3234 if (!indirectField->isCXXClassMember())
3235 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3236 indirectField);
3237
3238 {
3239 QualType type = VD->getType();
3240 if (type.isNull())
3241 return ExprError();
3242 ExprValueKind valueKind = VK_RValue;
3243
3244 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3245 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3246 // is expanded by some outer '...' in the context of the use.
3247 type = type.getNonPackExpansionType();
3248
3249 switch (D->getKind()) {
3250 // Ignore all the non-ValueDecl kinds.
3251 #define ABSTRACT_DECL(kind)
3252 #define VALUE(type, base)
3253 #define DECL(type, base) \
3254 case Decl::type:
3255 #include "clang/AST/DeclNodes.inc"
3256 llvm_unreachable("invalid value decl kind");
3257
3258 // These shouldn't make it here.
3259 case Decl::ObjCAtDefsField:
3260 llvm_unreachable("forming non-member reference to ivar?");
3261
3262 // Enum constants are always r-values and never references.
3263 // Unresolved using declarations are dependent.
3264 case Decl::EnumConstant:
3265 case Decl::UnresolvedUsingValue:
3266 case Decl::OMPDeclareReduction:
3267 case Decl::OMPDeclareMapper:
3268 valueKind = VK_RValue;
3269 break;
3270
3271 // Fields and indirect fields that got here must be for
3272 // pointer-to-member expressions; we just call them l-values for
3273 // internal consistency, because this subexpression doesn't really
3274 // exist in the high-level semantics.
3275 case Decl::Field:
3276 case Decl::IndirectField:
3277 case Decl::ObjCIvar:
3278 assert(getLangOpts().CPlusPlus &&
3279 "building reference to field in C?");
3280
3281 // These can't have reference type in well-formed programs, but
3282 // for internal consistency we do this anyway.
3283 type = type.getNonReferenceType();
3284 valueKind = VK_LValue;
3285 break;
3286
3287 // Non-type template parameters are either l-values or r-values
3288 // depending on the type.
3289 case Decl::NonTypeTemplateParm: {
3290 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3291 type = reftype->getPointeeType();
3292 valueKind = VK_LValue; // even if the parameter is an r-value reference
3293 break;
3294 }
3295
3296 // [expr.prim.id.unqual]p2:
3297 // If the entity is a template parameter object for a template
3298 // parameter of type T, the type of the expression is const T.
3299 // [...] The expression is an lvalue if the entity is a [...] template
3300 // parameter object.
3301 if (type->isRecordType()) {
3302 type = type.getUnqualifiedType().withConst();
3303 valueKind = VK_LValue;
3304 break;
3305 }
3306
3307 // For non-references, we need to strip qualifiers just in case
3308 // the template parameter was declared as 'const int' or whatever.
3309 valueKind = VK_RValue;
3310 type = type.getUnqualifiedType();
3311 break;
3312 }
3313
3314 case Decl::Var:
3315 case Decl::VarTemplateSpecialization:
3316 case Decl::VarTemplatePartialSpecialization:
3317 case Decl::Decomposition:
3318 case Decl::OMPCapturedExpr:
3319 // In C, "extern void blah;" is valid and is an r-value.
3320 if (!getLangOpts().CPlusPlus &&
3321 !type.hasQualifiers() &&
3322 type->isVoidType()) {
3323 valueKind = VK_RValue;
3324 break;
3325 }
3326 LLVM_FALLTHROUGH;
3327
3328 case Decl::ImplicitParam:
3329 case Decl::ParmVar: {
3330 // These are always l-values.
3331 valueKind = VK_LValue;
3332 type = type.getNonReferenceType();
3333
3334 // FIXME: Does the addition of const really only apply in
3335 // potentially-evaluated contexts? Since the variable isn't actually
3336 // captured in an unevaluated context, it seems that the answer is no.
3337 if (!isUnevaluatedContext()) {
3338 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3339 if (!CapturedType.isNull())
3340 type = CapturedType;
3341 }
3342
3343 break;
3344 }
3345
3346 case Decl::Binding: {
3347 // These are always lvalues.
3348 valueKind = VK_LValue;
3349 type = type.getNonReferenceType();
3350 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3351 // decides how that's supposed to work.
3352 auto *BD = cast<BindingDecl>(VD);
3353 if (BD->getDeclContext() != CurContext) {
3354 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3355 if (DD && DD->hasLocalStorage())
3356 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3357 }
3358 break;
3359 }
3360
3361 case Decl::Function: {
3362 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3363 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3364 type = Context.BuiltinFnTy;
3365 valueKind = VK_RValue;
3366 break;
3367 }
3368 }
3369
3370 const FunctionType *fty = type->castAs<FunctionType>();
3371
3372 // If we're referring to a function with an __unknown_anytype
3373 // result type, make the entire expression __unknown_anytype.
3374 if (fty->getReturnType() == Context.UnknownAnyTy) {
3375 type = Context.UnknownAnyTy;
3376 valueKind = VK_RValue;
3377 break;
3378 }
3379
3380 // Functions are l-values in C++.
3381 if (getLangOpts().CPlusPlus) {
3382 valueKind = VK_LValue;
3383 break;
3384 }
3385
3386 // C99 DR 316 says that, if a function type comes from a
3387 // function definition (without a prototype), that type is only
3388 // used for checking compatibility. Therefore, when referencing
3389 // the function, we pretend that we don't have the full function
3390 // type.
3391 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3392 isa<FunctionProtoType>(fty))
3393 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3394 fty->getExtInfo());
3395
3396 // Functions are r-values in C.
3397 valueKind = VK_RValue;
3398 break;
3399 }
3400
3401 case Decl::CXXDeductionGuide:
3402 llvm_unreachable("building reference to deduction guide");
3403
3404 case Decl::MSProperty:
3405 case Decl::MSGuid:
3406 case Decl::TemplateParamObject:
3407 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3408 // capture in OpenMP, or duplicated between host and device?
3409 valueKind = VK_LValue;
3410 break;
3411
3412 case Decl::CXXMethod:
3413 // If we're referring to a method with an __unknown_anytype
3414 // result type, make the entire expression __unknown_anytype.
3415 // This should only be possible with a type written directly.
3416 if (const FunctionProtoType *proto
3417 = dyn_cast<FunctionProtoType>(VD->getType()))
3418 if (proto->getReturnType() == Context.UnknownAnyTy) {
3419 type = Context.UnknownAnyTy;
3420 valueKind = VK_RValue;
3421 break;
3422 }
3423
3424 // C++ methods are l-values if static, r-values if non-static.
3425 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3426 valueKind = VK_LValue;
3427 break;
3428 }
3429 LLVM_FALLTHROUGH;
3430
3431 case Decl::CXXConversion:
3432 case Decl::CXXDestructor:
3433 case Decl::CXXConstructor:
3434 valueKind = VK_RValue;
3435 break;
3436 }
3437
3438 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3439 /*FIXME: TemplateKWLoc*/ SourceLocation(),
3440 TemplateArgs);
3441 }
3442 }
3443
ConvertUTF8ToWideString(unsigned CharByteWidth,StringRef Source,SmallString<32> & Target)3444 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3445 SmallString<32> &Target) {
3446 Target.resize(CharByteWidth * (Source.size() + 1));
3447 char *ResultPtr = &Target[0];
3448 const llvm::UTF8 *ErrorPtr;
3449 bool success =
3450 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3451 (void)success;
3452 assert(success);
3453 Target.resize(ResultPtr - &Target[0]);
3454 }
3455
BuildPredefinedExpr(SourceLocation Loc,PredefinedExpr::IdentKind IK)3456 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3457 PredefinedExpr::IdentKind IK) {
3458 // Pick the current block, lambda, captured statement or function.
3459 Decl *currentDecl = nullptr;
3460 if (const BlockScopeInfo *BSI = getCurBlock())
3461 currentDecl = BSI->TheDecl;
3462 else if (const LambdaScopeInfo *LSI = getCurLambda())
3463 currentDecl = LSI->CallOperator;
3464 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3465 currentDecl = CSI->TheCapturedDecl;
3466 else
3467 currentDecl = getCurFunctionOrMethodDecl();
3468
3469 if (!currentDecl) {
3470 Diag(Loc, diag::ext_predef_outside_function);
3471 currentDecl = Context.getTranslationUnitDecl();
3472 }
3473
3474 QualType ResTy;
3475 StringLiteral *SL = nullptr;
3476 if (cast<DeclContext>(currentDecl)->isDependentContext())
3477 ResTy = Context.DependentTy;
3478 else {
3479 // Pre-defined identifiers are of type char[x], where x is the length of
3480 // the string.
3481 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3482 unsigned Length = Str.length();
3483
3484 llvm::APInt LengthI(32, Length + 1);
3485 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3486 ResTy =
3487 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3488 SmallString<32> RawChars;
3489 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3490 Str, RawChars);
3491 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3492 ArrayType::Normal,
3493 /*IndexTypeQuals*/ 0);
3494 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3495 /*Pascal*/ false, ResTy, Loc);
3496 } else {
3497 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3498 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3499 ArrayType::Normal,
3500 /*IndexTypeQuals*/ 0);
3501 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3502 /*Pascal*/ false, ResTy, Loc);
3503 }
3504 }
3505
3506 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3507 }
3508
ActOnPredefinedExpr(SourceLocation Loc,tok::TokenKind Kind)3509 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3510 PredefinedExpr::IdentKind IK;
3511
3512 switch (Kind) {
3513 default: llvm_unreachable("Unknown simple primary expr!");
3514 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3515 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3516 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3517 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3518 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3519 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3520 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3521 }
3522
3523 return BuildPredefinedExpr(Loc, IK);
3524 }
3525
ActOnCharacterConstant(const Token & Tok,Scope * UDLScope)3526 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3527 SmallString<16> CharBuffer;
3528 bool Invalid = false;
3529 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3530 if (Invalid)
3531 return ExprError();
3532
3533 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3534 PP, Tok.getKind());
3535 if (Literal.hadError())
3536 return ExprError();
3537
3538 QualType Ty;
3539 if (Literal.isWide())
3540 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3541 else if (Literal.isUTF8() && getLangOpts().Char8)
3542 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3543 else if (Literal.isUTF16())
3544 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3545 else if (Literal.isUTF32())
3546 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3547 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3548 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3549 else
3550 Ty = Context.CharTy; // 'x' -> char in C++
3551
3552 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3553 if (Literal.isWide())
3554 Kind = CharacterLiteral::Wide;
3555 else if (Literal.isUTF16())
3556 Kind = CharacterLiteral::UTF16;
3557 else if (Literal.isUTF32())
3558 Kind = CharacterLiteral::UTF32;
3559 else if (Literal.isUTF8())
3560 Kind = CharacterLiteral::UTF8;
3561
3562 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3563 Tok.getLocation());
3564
3565 if (Literal.getUDSuffix().empty())
3566 return Lit;
3567
3568 // We're building a user-defined literal.
3569 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3570 SourceLocation UDSuffixLoc =
3571 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3572
3573 // Make sure we're allowed user-defined literals here.
3574 if (!UDLScope)
3575 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3576
3577 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3578 // operator "" X (ch)
3579 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3580 Lit, Tok.getLocation());
3581 }
3582
ActOnIntegerConstant(SourceLocation Loc,uint64_t Val)3583 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3584 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3585 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3586 Context.IntTy, Loc);
3587 }
3588
BuildFloatingLiteral(Sema & S,NumericLiteralParser & Literal,QualType Ty,SourceLocation Loc)3589 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3590 QualType Ty, SourceLocation Loc) {
3591 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3592
3593 using llvm::APFloat;
3594 APFloat Val(Format);
3595
3596 APFloat::opStatus result = Literal.GetFloatValue(Val);
3597
3598 // Overflow is always an error, but underflow is only an error if
3599 // we underflowed to zero (APFloat reports denormals as underflow).
3600 if ((result & APFloat::opOverflow) ||
3601 ((result & APFloat::opUnderflow) && Val.isZero())) {
3602 unsigned diagnostic;
3603 SmallString<20> buffer;
3604 if (result & APFloat::opOverflow) {
3605 diagnostic = diag::warn_float_overflow;
3606 APFloat::getLargest(Format).toString(buffer);
3607 } else {
3608 diagnostic = diag::warn_float_underflow;
3609 APFloat::getSmallest(Format).toString(buffer);
3610 }
3611
3612 S.Diag(Loc, diagnostic)
3613 << Ty
3614 << StringRef(buffer.data(), buffer.size());
3615 }
3616
3617 bool isExact = (result == APFloat::opOK);
3618 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3619 }
3620
CheckLoopHintExpr(Expr * E,SourceLocation Loc)3621 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3622 assert(E && "Invalid expression");
3623
3624 if (E->isValueDependent())
3625 return false;
3626
3627 QualType QT = E->getType();
3628 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3629 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3630 return true;
3631 }
3632
3633 llvm::APSInt ValueAPS;
3634 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3635
3636 if (R.isInvalid())
3637 return true;
3638
3639 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3640 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3641 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3642 << ValueAPS.toString(10) << ValueIsPositive;
3643 return true;
3644 }
3645
3646 return false;
3647 }
3648
ActOnNumericConstant(const Token & Tok,Scope * UDLScope)3649 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3650 // Fast path for a single digit (which is quite common). A single digit
3651 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3652 if (Tok.getLength() == 1) {
3653 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3654 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3655 }
3656
3657 SmallString<128> SpellingBuffer;
3658 // NumericLiteralParser wants to overread by one character. Add padding to
3659 // the buffer in case the token is copied to the buffer. If getSpelling()
3660 // returns a StringRef to the memory buffer, it should have a null char at
3661 // the EOF, so it is also safe.
3662 SpellingBuffer.resize(Tok.getLength() + 1);
3663
3664 // Get the spelling of the token, which eliminates trigraphs, etc.
3665 bool Invalid = false;
3666 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3667 if (Invalid)
3668 return ExprError();
3669
3670 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3671 PP.getSourceManager(), PP.getLangOpts(),
3672 PP.getTargetInfo(), PP.getDiagnostics());
3673 if (Literal.hadError)
3674 return ExprError();
3675
3676 if (Literal.hasUDSuffix()) {
3677 // We're building a user-defined literal.
3678 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3679 SourceLocation UDSuffixLoc =
3680 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3681
3682 // Make sure we're allowed user-defined literals here.
3683 if (!UDLScope)
3684 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3685
3686 QualType CookedTy;
3687 if (Literal.isFloatingLiteral()) {
3688 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3689 // long double, the literal is treated as a call of the form
3690 // operator "" X (f L)
3691 CookedTy = Context.LongDoubleTy;
3692 } else {
3693 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3694 // unsigned long long, the literal is treated as a call of the form
3695 // operator "" X (n ULL)
3696 CookedTy = Context.UnsignedLongLongTy;
3697 }
3698
3699 DeclarationName OpName =
3700 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3701 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3702 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3703
3704 SourceLocation TokLoc = Tok.getLocation();
3705
3706 // Perform literal operator lookup to determine if we're building a raw
3707 // literal or a cooked one.
3708 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3709 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3710 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3711 /*AllowStringTemplatePack*/ false,
3712 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3713 case LOLR_ErrorNoDiagnostic:
3714 // Lookup failure for imaginary constants isn't fatal, there's still the
3715 // GNU extension producing _Complex types.
3716 break;
3717 case LOLR_Error:
3718 return ExprError();
3719 case LOLR_Cooked: {
3720 Expr *Lit;
3721 if (Literal.isFloatingLiteral()) {
3722 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3723 } else {
3724 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3725 if (Literal.GetIntegerValue(ResultVal))
3726 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3727 << /* Unsigned */ 1;
3728 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3729 Tok.getLocation());
3730 }
3731 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3732 }
3733
3734 case LOLR_Raw: {
3735 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3736 // literal is treated as a call of the form
3737 // operator "" X ("n")
3738 unsigned Length = Literal.getUDSuffixOffset();
3739 QualType StrTy = Context.getConstantArrayType(
3740 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3741 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3742 Expr *Lit = StringLiteral::Create(
3743 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3744 /*Pascal*/false, StrTy, &TokLoc, 1);
3745 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3746 }
3747
3748 case LOLR_Template: {
3749 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3750 // template), L is treated as a call fo the form
3751 // operator "" X <'c1', 'c2', ... 'ck'>()
3752 // where n is the source character sequence c1 c2 ... ck.
3753 TemplateArgumentListInfo ExplicitArgs;
3754 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3755 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3756 llvm::APSInt Value(CharBits, CharIsUnsigned);
3757 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3758 Value = TokSpelling[I];
3759 TemplateArgument Arg(Context, Value, Context.CharTy);
3760 TemplateArgumentLocInfo ArgInfo;
3761 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3762 }
3763 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3764 &ExplicitArgs);
3765 }
3766 case LOLR_StringTemplatePack:
3767 llvm_unreachable("unexpected literal operator lookup result");
3768 }
3769 }
3770
3771 Expr *Res;
3772
3773 if (Literal.isFixedPointLiteral()) {
3774 QualType Ty;
3775
3776 if (Literal.isAccum) {
3777 if (Literal.isHalf) {
3778 Ty = Context.ShortAccumTy;
3779 } else if (Literal.isLong) {
3780 Ty = Context.LongAccumTy;
3781 } else {
3782 Ty = Context.AccumTy;
3783 }
3784 } else if (Literal.isFract) {
3785 if (Literal.isHalf) {
3786 Ty = Context.ShortFractTy;
3787 } else if (Literal.isLong) {
3788 Ty = Context.LongFractTy;
3789 } else {
3790 Ty = Context.FractTy;
3791 }
3792 }
3793
3794 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3795
3796 bool isSigned = !Literal.isUnsigned;
3797 unsigned scale = Context.getFixedPointScale(Ty);
3798 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3799
3800 llvm::APInt Val(bit_width, 0, isSigned);
3801 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3802 bool ValIsZero = Val.isNullValue() && !Overflowed;
3803
3804 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3805 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3806 // Clause 6.4.4 - The value of a constant shall be in the range of
3807 // representable values for its type, with exception for constants of a
3808 // fract type with a value of exactly 1; such a constant shall denote
3809 // the maximal value for the type.
3810 --Val;
3811 else if (Val.ugt(MaxVal) || Overflowed)
3812 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3813
3814 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3815 Tok.getLocation(), scale);
3816 } else if (Literal.isFloatingLiteral()) {
3817 QualType Ty;
3818 if (Literal.isHalf){
3819 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3820 Ty = Context.HalfTy;
3821 else {
3822 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3823 return ExprError();
3824 }
3825 } else if (Literal.isFloat)
3826 Ty = Context.FloatTy;
3827 else if (Literal.isLong)
3828 Ty = Context.LongDoubleTy;
3829 else if (Literal.isFloat16)
3830 Ty = Context.Float16Ty;
3831 else if (Literal.isFloat128)
3832 Ty = Context.Float128Ty;
3833 else
3834 Ty = Context.DoubleTy;
3835
3836 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3837
3838 if (Ty == Context.DoubleTy) {
3839 if (getLangOpts().SinglePrecisionConstants) {
3840 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3841 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3842 }
3843 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3844 "cl_khr_fp64", getLangOpts())) {
3845 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3846 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3847 << (getLangOpts().OpenCLVersion >= 300);
3848 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3849 }
3850 }
3851 } else if (!Literal.isIntegerLiteral()) {
3852 return ExprError();
3853 } else {
3854 QualType Ty;
3855
3856 // 'long long' is a C99 or C++11 feature.
3857 if (!getLangOpts().C99 && Literal.isLongLong) {
3858 if (getLangOpts().CPlusPlus)
3859 Diag(Tok.getLocation(),
3860 getLangOpts().CPlusPlus11 ?
3861 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3862 else
3863 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3864 }
3865
3866 // 'z/uz' literals are a C++2b feature.
3867 if (Literal.isSizeT)
3868 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3869 ? getLangOpts().CPlusPlus2b
3870 ? diag::warn_cxx20_compat_size_t_suffix
3871 : diag::ext_cxx2b_size_t_suffix
3872 : diag::err_cxx2b_size_t_suffix);
3873
3874 // Get the value in the widest-possible width.
3875 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3876 llvm::APInt ResultVal(MaxWidth, 0);
3877
3878 if (Literal.GetIntegerValue(ResultVal)) {
3879 // If this value didn't fit into uintmax_t, error and force to ull.
3880 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3881 << /* Unsigned */ 1;
3882 Ty = Context.UnsignedLongLongTy;
3883 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3884 "long long is not intmax_t?");
3885 } else {
3886 // If this value fits into a ULL, try to figure out what else it fits into
3887 // according to the rules of C99 6.4.4.1p5.
3888
3889 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3890 // be an unsigned int.
3891 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3892
3893 // Check from smallest to largest, picking the smallest type we can.
3894 unsigned Width = 0;
3895
3896 // Microsoft specific integer suffixes are explicitly sized.
3897 if (Literal.MicrosoftInteger) {
3898 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3899 Width = 8;
3900 Ty = Context.CharTy;
3901 } else {
3902 Width = Literal.MicrosoftInteger;
3903 Ty = Context.getIntTypeForBitwidth(Width,
3904 /*Signed=*/!Literal.isUnsigned);
3905 }
3906 }
3907
3908 // Check C++2b size_t literals.
3909 if (Literal.isSizeT) {
3910 assert(!Literal.MicrosoftInteger &&
3911 "size_t literals can't be Microsoft literals");
3912 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3913 Context.getTargetInfo().getSizeType());
3914
3915 // Does it fit in size_t?
3916 if (ResultVal.isIntN(SizeTSize)) {
3917 // Does it fit in ssize_t?
3918 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3919 Ty = Context.getSignedSizeType();
3920 else if (AllowUnsigned)
3921 Ty = Context.getSizeType();
3922 Width = SizeTSize;
3923 }
3924 }
3925
3926 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3927 !Literal.isSizeT) {
3928 // Are int/unsigned possibilities?
3929 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3930
3931 // Does it fit in a unsigned int?
3932 if (ResultVal.isIntN(IntSize)) {
3933 // Does it fit in a signed int?
3934 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3935 Ty = Context.IntTy;
3936 else if (AllowUnsigned)
3937 Ty = Context.UnsignedIntTy;
3938 Width = IntSize;
3939 }
3940 }
3941
3942 // Are long/unsigned long possibilities?
3943 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
3944 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3945
3946 // Does it fit in a unsigned long?
3947 if (ResultVal.isIntN(LongSize)) {
3948 // Does it fit in a signed long?
3949 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3950 Ty = Context.LongTy;
3951 else if (AllowUnsigned)
3952 Ty = Context.UnsignedLongTy;
3953 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3954 // is compatible.
3955 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3956 const unsigned LongLongSize =
3957 Context.getTargetInfo().getLongLongWidth();
3958 Diag(Tok.getLocation(),
3959 getLangOpts().CPlusPlus
3960 ? Literal.isLong
3961 ? diag::warn_old_implicitly_unsigned_long_cxx
3962 : /*C++98 UB*/ diag::
3963 ext_old_implicitly_unsigned_long_cxx
3964 : diag::warn_old_implicitly_unsigned_long)
3965 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3966 : /*will be ill-formed*/ 1);
3967 Ty = Context.UnsignedLongTy;
3968 }
3969 Width = LongSize;
3970 }
3971 }
3972
3973 // Check long long if needed.
3974 if (Ty.isNull() && !Literal.isSizeT) {
3975 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3976
3977 // Does it fit in a unsigned long long?
3978 if (ResultVal.isIntN(LongLongSize)) {
3979 // Does it fit in a signed long long?
3980 // To be compatible with MSVC, hex integer literals ending with the
3981 // LL or i64 suffix are always signed in Microsoft mode.
3982 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3983 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3984 Ty = Context.LongLongTy;
3985 else if (AllowUnsigned)
3986 Ty = Context.UnsignedLongLongTy;
3987 Width = LongLongSize;
3988 }
3989 }
3990
3991 // If we still couldn't decide a type, we either have 'size_t' literal
3992 // that is out of range, or a decimal literal that does not fit in a
3993 // signed long long and has no U suffix.
3994 if (Ty.isNull()) {
3995 if (Literal.isSizeT)
3996 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
3997 << Literal.isUnsigned;
3998 else
3999 Diag(Tok.getLocation(),
4000 diag::ext_integer_literal_too_large_for_signed);
4001 Ty = Context.UnsignedLongLongTy;
4002 Width = Context.getTargetInfo().getLongLongWidth();
4003 }
4004
4005 if (ResultVal.getBitWidth() != Width)
4006 ResultVal = ResultVal.trunc(Width);
4007 }
4008 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4009 }
4010
4011 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4012 if (Literal.isImaginary) {
4013 Res = new (Context) ImaginaryLiteral(Res,
4014 Context.getComplexType(Res->getType()));
4015
4016 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4017 }
4018 return Res;
4019 }
4020
ActOnParenExpr(SourceLocation L,SourceLocation R,Expr * E)4021 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
4022 assert(E && "ActOnParenExpr() missing expr");
4023 return new (Context) ParenExpr(L, R, E);
4024 }
4025
CheckVecStepTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange)4026 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
4027 SourceLocation Loc,
4028 SourceRange ArgRange) {
4029 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4030 // scalar or vector data type argument..."
4031 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4032 // type (C99 6.2.5p18) or void.
4033 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4034 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4035 << T << ArgRange;
4036 return true;
4037 }
4038
4039 assert((T->isVoidType() || !T->isIncompleteType()) &&
4040 "Scalar types should always be complete");
4041 return false;
4042 }
4043
CheckExtensionTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)4044 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4045 SourceLocation Loc,
4046 SourceRange ArgRange,
4047 UnaryExprOrTypeTrait TraitKind) {
4048 // Invalid types must be hard errors for SFINAE in C++.
4049 if (S.LangOpts.CPlusPlus)
4050 return true;
4051
4052 // C99 6.5.3.4p1:
4053 if (T->isFunctionType() &&
4054 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4055 TraitKind == UETT_PreferredAlignOf)) {
4056 // sizeof(function)/alignof(function) is allowed as an extension.
4057 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4058 << getTraitSpelling(TraitKind) << ArgRange;
4059 return false;
4060 }
4061
4062 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4063 // this is an error (OpenCL v1.1 s6.3.k)
4064 if (T->isVoidType()) {
4065 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4066 : diag::ext_sizeof_alignof_void_type;
4067 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4068 return false;
4069 }
4070
4071 return true;
4072 }
4073
CheckObjCTraitOperandConstraints(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)4074 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4075 SourceLocation Loc,
4076 SourceRange ArgRange,
4077 UnaryExprOrTypeTrait TraitKind) {
4078 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4079 // runtime doesn't allow it.
4080 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4081 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4082 << T << (TraitKind == UETT_SizeOf)
4083 << ArgRange;
4084 return true;
4085 }
4086
4087 return false;
4088 }
4089
4090 /// Check whether E is a pointer from a decayed array type (the decayed
4091 /// pointer type is equal to T) and emit a warning if it is.
warnOnSizeofOnArrayDecay(Sema & S,SourceLocation Loc,QualType T,Expr * E)4092 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4093 Expr *E) {
4094 // Don't warn if the operation changed the type.
4095 if (T != E->getType())
4096 return;
4097
4098 // Now look for array decays.
4099 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4100 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4101 return;
4102
4103 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4104 << ICE->getType()
4105 << ICE->getSubExpr()->getType();
4106 }
4107
4108 /// Check the constraints on expression operands to unary type expression
4109 /// and type traits.
4110 ///
4111 /// Completes any types necessary and validates the constraints on the operand
4112 /// expression. The logic mostly mirrors the type-based overload, but may modify
4113 /// the expression as it completes the type for that expression through template
4114 /// instantiation, etc.
CheckUnaryExprOrTypeTraitOperand(Expr * E,UnaryExprOrTypeTrait ExprKind)4115 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4116 UnaryExprOrTypeTrait ExprKind) {
4117 QualType ExprTy = E->getType();
4118 assert(!ExprTy->isReferenceType());
4119
4120 bool IsUnevaluatedOperand =
4121 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4122 ExprKind == UETT_PreferredAlignOf || ExprKind == UETT_VecStep);
4123 if (IsUnevaluatedOperand) {
4124 ExprResult Result = CheckUnevaluatedOperand(E);
4125 if (Result.isInvalid())
4126 return true;
4127 E = Result.get();
4128 }
4129
4130 // The operand for sizeof and alignof is in an unevaluated expression context,
4131 // so side effects could result in unintended consequences.
4132 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4133 // used to build SFINAE gadgets.
4134 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4135 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4136 !E->isInstantiationDependent() &&
4137 E->HasSideEffects(Context, false))
4138 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4139
4140 if (ExprKind == UETT_VecStep)
4141 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4142 E->getSourceRange());
4143
4144 // Explicitly list some types as extensions.
4145 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4146 E->getSourceRange(), ExprKind))
4147 return false;
4148
4149 // 'alignof' applied to an expression only requires the base element type of
4150 // the expression to be complete. 'sizeof' requires the expression's type to
4151 // be complete (and will attempt to complete it if it's an array of unknown
4152 // bound).
4153 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4154 if (RequireCompleteSizedType(
4155 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4156 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4157 getTraitSpelling(ExprKind), E->getSourceRange()))
4158 return true;
4159 } else {
4160 if (RequireCompleteSizedExprType(
4161 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4162 getTraitSpelling(ExprKind), E->getSourceRange()))
4163 return true;
4164 }
4165
4166 // Completing the expression's type may have changed it.
4167 ExprTy = E->getType();
4168 assert(!ExprTy->isReferenceType());
4169
4170 if (ExprTy->isFunctionType()) {
4171 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4172 << getTraitSpelling(ExprKind) << E->getSourceRange();
4173 return true;
4174 }
4175
4176 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4177 E->getSourceRange(), ExprKind))
4178 return true;
4179
4180 if (ExprKind == UETT_SizeOf) {
4181 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4182 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4183 QualType OType = PVD->getOriginalType();
4184 QualType Type = PVD->getType();
4185 if (Type->isPointerType() && OType->isArrayType()) {
4186 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4187 << Type << OType;
4188 Diag(PVD->getLocation(), diag::note_declared_at);
4189 }
4190 }
4191 }
4192
4193 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4194 // decays into a pointer and returns an unintended result. This is most
4195 // likely a typo for "sizeof(array) op x".
4196 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4197 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4198 BO->getLHS());
4199 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4200 BO->getRHS());
4201 }
4202 }
4203
4204 return false;
4205 }
4206
4207 /// Check the constraints on operands to unary expression and type
4208 /// traits.
4209 ///
4210 /// This will complete any types necessary, and validate the various constraints
4211 /// on those operands.
4212 ///
4213 /// The UsualUnaryConversions() function is *not* called by this routine.
4214 /// C99 6.3.2.1p[2-4] all state:
4215 /// Except when it is the operand of the sizeof operator ...
4216 ///
4217 /// C++ [expr.sizeof]p4
4218 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4219 /// standard conversions are not applied to the operand of sizeof.
4220 ///
4221 /// This policy is followed for all of the unary trait expressions.
CheckUnaryExprOrTypeTraitOperand(QualType ExprType,SourceLocation OpLoc,SourceRange ExprRange,UnaryExprOrTypeTrait ExprKind)4222 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4223 SourceLocation OpLoc,
4224 SourceRange ExprRange,
4225 UnaryExprOrTypeTrait ExprKind) {
4226 if (ExprType->isDependentType())
4227 return false;
4228
4229 // C++ [expr.sizeof]p2:
4230 // When applied to a reference or a reference type, the result
4231 // is the size of the referenced type.
4232 // C++11 [expr.alignof]p3:
4233 // When alignof is applied to a reference type, the result
4234 // shall be the alignment of the referenced type.
4235 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4236 ExprType = Ref->getPointeeType();
4237
4238 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4239 // When alignof or _Alignof is applied to an array type, the result
4240 // is the alignment of the element type.
4241 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4242 ExprKind == UETT_OpenMPRequiredSimdAlign)
4243 ExprType = Context.getBaseElementType(ExprType);
4244
4245 if (ExprKind == UETT_VecStep)
4246 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4247
4248 // Explicitly list some types as extensions.
4249 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4250 ExprKind))
4251 return false;
4252
4253 if (RequireCompleteSizedType(
4254 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4255 getTraitSpelling(ExprKind), ExprRange))
4256 return true;
4257
4258 if (ExprType->isFunctionType()) {
4259 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4260 << getTraitSpelling(ExprKind) << ExprRange;
4261 return true;
4262 }
4263
4264 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4265 ExprKind))
4266 return true;
4267
4268 return false;
4269 }
4270
CheckAlignOfExpr(Sema & S,Expr * E,UnaryExprOrTypeTrait ExprKind)4271 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4272 // Cannot know anything else if the expression is dependent.
4273 if (E->isTypeDependent())
4274 return false;
4275
4276 if (E->getObjectKind() == OK_BitField) {
4277 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4278 << 1 << E->getSourceRange();
4279 return true;
4280 }
4281
4282 ValueDecl *D = nullptr;
4283 Expr *Inner = E->IgnoreParens();
4284 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4285 D = DRE->getDecl();
4286 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4287 D = ME->getMemberDecl();
4288 }
4289
4290 // If it's a field, require the containing struct to have a
4291 // complete definition so that we can compute the layout.
4292 //
4293 // This can happen in C++11 onwards, either by naming the member
4294 // in a way that is not transformed into a member access expression
4295 // (in an unevaluated operand, for instance), or by naming the member
4296 // in a trailing-return-type.
4297 //
4298 // For the record, since __alignof__ on expressions is a GCC
4299 // extension, GCC seems to permit this but always gives the
4300 // nonsensical answer 0.
4301 //
4302 // We don't really need the layout here --- we could instead just
4303 // directly check for all the appropriate alignment-lowing
4304 // attributes --- but that would require duplicating a lot of
4305 // logic that just isn't worth duplicating for such a marginal
4306 // use-case.
4307 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4308 // Fast path this check, since we at least know the record has a
4309 // definition if we can find a member of it.
4310 if (!FD->getParent()->isCompleteDefinition()) {
4311 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4312 << E->getSourceRange();
4313 return true;
4314 }
4315
4316 // Otherwise, if it's a field, and the field doesn't have
4317 // reference type, then it must have a complete type (or be a
4318 // flexible array member, which we explicitly want to
4319 // white-list anyway), which makes the following checks trivial.
4320 if (!FD->getType()->isReferenceType())
4321 return false;
4322 }
4323
4324 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4325 }
4326
CheckVecStepExpr(Expr * E)4327 bool Sema::CheckVecStepExpr(Expr *E) {
4328 E = E->IgnoreParens();
4329
4330 // Cannot know anything else if the expression is dependent.
4331 if (E->isTypeDependent())
4332 return false;
4333
4334 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4335 }
4336
captureVariablyModifiedType(ASTContext & Context,QualType T,CapturingScopeInfo * CSI)4337 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4338 CapturingScopeInfo *CSI) {
4339 assert(T->isVariablyModifiedType());
4340 assert(CSI != nullptr);
4341
4342 // We're going to walk down into the type and look for VLA expressions.
4343 do {
4344 const Type *Ty = T.getTypePtr();
4345 switch (Ty->getTypeClass()) {
4346 #define TYPE(Class, Base)
4347 #define ABSTRACT_TYPE(Class, Base)
4348 #define NON_CANONICAL_TYPE(Class, Base)
4349 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4350 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4351 #include "clang/AST/TypeNodes.inc"
4352 T = QualType();
4353 break;
4354 // These types are never variably-modified.
4355 case Type::Builtin:
4356 case Type::Complex:
4357 case Type::Vector:
4358 case Type::ExtVector:
4359 case Type::ConstantMatrix:
4360 case Type::Record:
4361 case Type::Enum:
4362 case Type::Elaborated:
4363 case Type::TemplateSpecialization:
4364 case Type::ObjCObject:
4365 case Type::ObjCInterface:
4366 case Type::ObjCObjectPointer:
4367 case Type::ObjCTypeParam:
4368 case Type::Pipe:
4369 case Type::ExtInt:
4370 llvm_unreachable("type class is never variably-modified!");
4371 case Type::Adjusted:
4372 T = cast<AdjustedType>(Ty)->getOriginalType();
4373 break;
4374 case Type::Decayed:
4375 T = cast<DecayedType>(Ty)->getPointeeType();
4376 break;
4377 case Type::Pointer:
4378 T = cast<PointerType>(Ty)->getPointeeType();
4379 break;
4380 case Type::BlockPointer:
4381 T = cast<BlockPointerType>(Ty)->getPointeeType();
4382 break;
4383 case Type::LValueReference:
4384 case Type::RValueReference:
4385 T = cast<ReferenceType>(Ty)->getPointeeType();
4386 break;
4387 case Type::MemberPointer:
4388 T = cast<MemberPointerType>(Ty)->getPointeeType();
4389 break;
4390 case Type::ConstantArray:
4391 case Type::IncompleteArray:
4392 // Losing element qualification here is fine.
4393 T = cast<ArrayType>(Ty)->getElementType();
4394 break;
4395 case Type::VariableArray: {
4396 // Losing element qualification here is fine.
4397 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4398
4399 // Unknown size indication requires no size computation.
4400 // Otherwise, evaluate and record it.
4401 auto Size = VAT->getSizeExpr();
4402 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4403 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4404 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4405
4406 T = VAT->getElementType();
4407 break;
4408 }
4409 case Type::FunctionProto:
4410 case Type::FunctionNoProto:
4411 T = cast<FunctionType>(Ty)->getReturnType();
4412 break;
4413 case Type::Paren:
4414 case Type::TypeOf:
4415 case Type::UnaryTransform:
4416 case Type::Attributed:
4417 case Type::SubstTemplateTypeParm:
4418 case Type::MacroQualified:
4419 // Keep walking after single level desugaring.
4420 T = T.getSingleStepDesugaredType(Context);
4421 break;
4422 case Type::Typedef:
4423 T = cast<TypedefType>(Ty)->desugar();
4424 break;
4425 case Type::Decltype:
4426 T = cast<DecltypeType>(Ty)->desugar();
4427 break;
4428 case Type::Auto:
4429 case Type::DeducedTemplateSpecialization:
4430 T = cast<DeducedType>(Ty)->getDeducedType();
4431 break;
4432 case Type::TypeOfExpr:
4433 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4434 break;
4435 case Type::Atomic:
4436 T = cast<AtomicType>(Ty)->getValueType();
4437 break;
4438 }
4439 } while (!T.isNull() && T->isVariablyModifiedType());
4440 }
4441
4442 /// Build a sizeof or alignof expression given a type operand.
4443 ExprResult
CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo * TInfo,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,SourceRange R)4444 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4445 SourceLocation OpLoc,
4446 UnaryExprOrTypeTrait ExprKind,
4447 SourceRange R) {
4448 if (!TInfo)
4449 return ExprError();
4450
4451 QualType T = TInfo->getType();
4452
4453 if (!T->isDependentType() &&
4454 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4455 return ExprError();
4456
4457 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4458 if (auto *TT = T->getAs<TypedefType>()) {
4459 for (auto I = FunctionScopes.rbegin(),
4460 E = std::prev(FunctionScopes.rend());
4461 I != E; ++I) {
4462 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4463 if (CSI == nullptr)
4464 break;
4465 DeclContext *DC = nullptr;
4466 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4467 DC = LSI->CallOperator;
4468 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4469 DC = CRSI->TheCapturedDecl;
4470 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4471 DC = BSI->TheDecl;
4472 if (DC) {
4473 if (DC->containsDecl(TT->getDecl()))
4474 break;
4475 captureVariablyModifiedType(Context, T, CSI);
4476 }
4477 }
4478 }
4479 }
4480
4481 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4482 return new (Context) UnaryExprOrTypeTraitExpr(
4483 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4484 }
4485
4486 /// Build a sizeof or alignof expression given an expression
4487 /// operand.
4488 ExprResult
CreateUnaryExprOrTypeTraitExpr(Expr * E,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind)4489 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4490 UnaryExprOrTypeTrait ExprKind) {
4491 ExprResult PE = CheckPlaceholderExpr(E);
4492 if (PE.isInvalid())
4493 return ExprError();
4494
4495 E = PE.get();
4496
4497 // Verify that the operand is valid.
4498 bool isInvalid = false;
4499 if (E->isTypeDependent()) {
4500 // Delay type-checking for type-dependent expressions.
4501 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4502 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4503 } else if (ExprKind == UETT_VecStep) {
4504 isInvalid = CheckVecStepExpr(E);
4505 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4506 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4507 isInvalid = true;
4508 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4509 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4510 isInvalid = true;
4511 } else {
4512 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4513 }
4514
4515 if (isInvalid)
4516 return ExprError();
4517
4518 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4519 PE = TransformToPotentiallyEvaluated(E);
4520 if (PE.isInvalid()) return ExprError();
4521 E = PE.get();
4522 }
4523
4524 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4525 return new (Context) UnaryExprOrTypeTraitExpr(
4526 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4527 }
4528
4529 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4530 /// expr and the same for @c alignof and @c __alignof
4531 /// Note that the ArgRange is invalid if isType is false.
4532 ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,bool IsType,void * TyOrEx,SourceRange ArgRange)4533 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4534 UnaryExprOrTypeTrait ExprKind, bool IsType,
4535 void *TyOrEx, SourceRange ArgRange) {
4536 // If error parsing type, ignore.
4537 if (!TyOrEx) return ExprError();
4538
4539 if (IsType) {
4540 TypeSourceInfo *TInfo;
4541 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4542 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4543 }
4544
4545 Expr *ArgEx = (Expr *)TyOrEx;
4546 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4547 return Result;
4548 }
4549
CheckRealImagOperand(Sema & S,ExprResult & V,SourceLocation Loc,bool IsReal)4550 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4551 bool IsReal) {
4552 if (V.get()->isTypeDependent())
4553 return S.Context.DependentTy;
4554
4555 // _Real and _Imag are only l-values for normal l-values.
4556 if (V.get()->getObjectKind() != OK_Ordinary) {
4557 V = S.DefaultLvalueConversion(V.get());
4558 if (V.isInvalid())
4559 return QualType();
4560 }
4561
4562 // These operators return the element type of a complex type.
4563 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4564 return CT->getElementType();
4565
4566 // Otherwise they pass through real integer and floating point types here.
4567 if (V.get()->getType()->isArithmeticType())
4568 return V.get()->getType();
4569
4570 // Test for placeholders.
4571 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4572 if (PR.isInvalid()) return QualType();
4573 if (PR.get() != V.get()) {
4574 V = PR;
4575 return CheckRealImagOperand(S, V, Loc, IsReal);
4576 }
4577
4578 // Reject anything else.
4579 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4580 << (IsReal ? "__real" : "__imag");
4581 return QualType();
4582 }
4583
4584
4585
4586 ExprResult
ActOnPostfixUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Kind,Expr * Input)4587 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4588 tok::TokenKind Kind, Expr *Input) {
4589 UnaryOperatorKind Opc;
4590 switch (Kind) {
4591 default: llvm_unreachable("Unknown unary op!");
4592 case tok::plusplus: Opc = UO_PostInc; break;
4593 case tok::minusminus: Opc = UO_PostDec; break;
4594 }
4595
4596 // Since this might is a postfix expression, get rid of ParenListExprs.
4597 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4598 if (Result.isInvalid()) return ExprError();
4599 Input = Result.get();
4600
4601 return BuildUnaryOp(S, OpLoc, Opc, Input);
4602 }
4603
4604 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4605 ///
4606 /// \return true on error
checkArithmeticOnObjCPointer(Sema & S,SourceLocation opLoc,Expr * op)4607 static bool checkArithmeticOnObjCPointer(Sema &S,
4608 SourceLocation opLoc,
4609 Expr *op) {
4610 assert(op->getType()->isObjCObjectPointerType());
4611 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4612 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4613 return false;
4614
4615 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4616 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4617 << op->getSourceRange();
4618 return true;
4619 }
4620
isMSPropertySubscriptExpr(Sema & S,Expr * Base)4621 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4622 auto *BaseNoParens = Base->IgnoreParens();
4623 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4624 return MSProp->getPropertyDecl()->getType()->isArrayType();
4625 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4626 }
4627
4628 ExprResult
ActOnArraySubscriptExpr(Scope * S,Expr * base,SourceLocation lbLoc,Expr * idx,SourceLocation rbLoc)4629 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4630 Expr *idx, SourceLocation rbLoc) {
4631 if (base && !base->getType().isNull() &&
4632 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4633 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4634 SourceLocation(), /*Length*/ nullptr,
4635 /*Stride=*/nullptr, rbLoc);
4636
4637 // Since this might be a postfix expression, get rid of ParenListExprs.
4638 if (isa<ParenListExpr>(base)) {
4639 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4640 if (result.isInvalid()) return ExprError();
4641 base = result.get();
4642 }
4643
4644 // Check if base and idx form a MatrixSubscriptExpr.
4645 //
4646 // Helper to check for comma expressions, which are not allowed as indices for
4647 // matrix subscript expressions.
4648 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4649 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4650 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4651 << SourceRange(base->getBeginLoc(), rbLoc);
4652 return true;
4653 }
4654 return false;
4655 };
4656 // The matrix subscript operator ([][])is considered a single operator.
4657 // Separating the index expressions by parenthesis is not allowed.
4658 if (base->getType()->isSpecificPlaceholderType(
4659 BuiltinType::IncompleteMatrixIdx) &&
4660 !isa<MatrixSubscriptExpr>(base)) {
4661 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4662 << SourceRange(base->getBeginLoc(), rbLoc);
4663 return ExprError();
4664 }
4665 // If the base is a MatrixSubscriptExpr, try to create a new
4666 // MatrixSubscriptExpr.
4667 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4668 if (matSubscriptE) {
4669 if (CheckAndReportCommaError(idx))
4670 return ExprError();
4671
4672 assert(matSubscriptE->isIncomplete() &&
4673 "base has to be an incomplete matrix subscript");
4674 return CreateBuiltinMatrixSubscriptExpr(
4675 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4676 }
4677
4678 // Handle any non-overload placeholder types in the base and index
4679 // expressions. We can't handle overloads here because the other
4680 // operand might be an overloadable type, in which case the overload
4681 // resolution for the operator overload should get the first crack
4682 // at the overload.
4683 bool IsMSPropertySubscript = false;
4684 if (base->getType()->isNonOverloadPlaceholderType()) {
4685 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4686 if (!IsMSPropertySubscript) {
4687 ExprResult result = CheckPlaceholderExpr(base);
4688 if (result.isInvalid())
4689 return ExprError();
4690 base = result.get();
4691 }
4692 }
4693
4694 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4695 if (base->getType()->isMatrixType()) {
4696 if (CheckAndReportCommaError(idx))
4697 return ExprError();
4698
4699 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4700 }
4701
4702 // A comma-expression as the index is deprecated in C++2a onwards.
4703 if (getLangOpts().CPlusPlus20 &&
4704 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4705 (isa<CXXOperatorCallExpr>(idx) &&
4706 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4707 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4708 << SourceRange(base->getBeginLoc(), rbLoc);
4709 }
4710
4711 if (idx->getType()->isNonOverloadPlaceholderType()) {
4712 ExprResult result = CheckPlaceholderExpr(idx);
4713 if (result.isInvalid()) return ExprError();
4714 idx = result.get();
4715 }
4716
4717 // Build an unanalyzed expression if either operand is type-dependent.
4718 if (getLangOpts().CPlusPlus &&
4719 (base->isTypeDependent() || idx->isTypeDependent())) {
4720 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4721 VK_LValue, OK_Ordinary, rbLoc);
4722 }
4723
4724 // MSDN, property (C++)
4725 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4726 // This attribute can also be used in the declaration of an empty array in a
4727 // class or structure definition. For example:
4728 // __declspec(property(get=GetX, put=PutX)) int x[];
4729 // The above statement indicates that x[] can be used with one or more array
4730 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4731 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4732 if (IsMSPropertySubscript) {
4733 // Build MS property subscript expression if base is MS property reference
4734 // or MS property subscript.
4735 return new (Context) MSPropertySubscriptExpr(
4736 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4737 }
4738
4739 // Use C++ overloaded-operator rules if either operand has record
4740 // type. The spec says to do this if either type is *overloadable*,
4741 // but enum types can't declare subscript operators or conversion
4742 // operators, so there's nothing interesting for overload resolution
4743 // to do if there aren't any record types involved.
4744 //
4745 // ObjC pointers have their own subscripting logic that is not tied
4746 // to overload resolution and so should not take this path.
4747 if (getLangOpts().CPlusPlus &&
4748 (base->getType()->isRecordType() ||
4749 (!base->getType()->isObjCObjectPointerType() &&
4750 idx->getType()->isRecordType()))) {
4751 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4752 }
4753
4754 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4755
4756 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4757 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4758
4759 return Res;
4760 }
4761
tryConvertExprToType(Expr * E,QualType Ty)4762 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4763 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4764 InitializationKind Kind =
4765 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4766 InitializationSequence InitSeq(*this, Entity, Kind, E);
4767 return InitSeq.Perform(*this, Entity, Kind, E);
4768 }
4769
CreateBuiltinMatrixSubscriptExpr(Expr * Base,Expr * RowIdx,Expr * ColumnIdx,SourceLocation RBLoc)4770 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4771 Expr *ColumnIdx,
4772 SourceLocation RBLoc) {
4773 ExprResult BaseR = CheckPlaceholderExpr(Base);
4774 if (BaseR.isInvalid())
4775 return BaseR;
4776 Base = BaseR.get();
4777
4778 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4779 if (RowR.isInvalid())
4780 return RowR;
4781 RowIdx = RowR.get();
4782
4783 if (!ColumnIdx)
4784 return new (Context) MatrixSubscriptExpr(
4785 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4786
4787 // Build an unanalyzed expression if any of the operands is type-dependent.
4788 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4789 ColumnIdx->isTypeDependent())
4790 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4791 Context.DependentTy, RBLoc);
4792
4793 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4794 if (ColumnR.isInvalid())
4795 return ColumnR;
4796 ColumnIdx = ColumnR.get();
4797
4798 // Check that IndexExpr is an integer expression. If it is a constant
4799 // expression, check that it is less than Dim (= the number of elements in the
4800 // corresponding dimension).
4801 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4802 bool IsColumnIdx) -> Expr * {
4803 if (!IndexExpr->getType()->isIntegerType() &&
4804 !IndexExpr->isTypeDependent()) {
4805 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4806 << IsColumnIdx;
4807 return nullptr;
4808 }
4809
4810 if (Optional<llvm::APSInt> Idx =
4811 IndexExpr->getIntegerConstantExpr(Context)) {
4812 if ((*Idx < 0 || *Idx >= Dim)) {
4813 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4814 << IsColumnIdx << Dim;
4815 return nullptr;
4816 }
4817 }
4818
4819 ExprResult ConvExpr =
4820 tryConvertExprToType(IndexExpr, Context.getSizeType());
4821 assert(!ConvExpr.isInvalid() &&
4822 "should be able to convert any integer type to size type");
4823 return ConvExpr.get();
4824 };
4825
4826 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4827 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4828 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4829 if (!RowIdx || !ColumnIdx)
4830 return ExprError();
4831
4832 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4833 MTy->getElementType(), RBLoc);
4834 }
4835
CheckAddressOfNoDeref(const Expr * E)4836 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4837 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4838 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4839
4840 // For expressions like `&(*s).b`, the base is recorded and what should be
4841 // checked.
4842 const MemberExpr *Member = nullptr;
4843 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4844 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4845
4846 LastRecord.PossibleDerefs.erase(StrippedExpr);
4847 }
4848
CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr * E)4849 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4850 if (isUnevaluatedContext())
4851 return;
4852
4853 QualType ResultTy = E->getType();
4854 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4855
4856 // Bail if the element is an array since it is not memory access.
4857 if (isa<ArrayType>(ResultTy))
4858 return;
4859
4860 if (ResultTy->hasAttr(attr::NoDeref)) {
4861 LastRecord.PossibleDerefs.insert(E);
4862 return;
4863 }
4864
4865 // Check if the base type is a pointer to a member access of a struct
4866 // marked with noderef.
4867 const Expr *Base = E->getBase();
4868 QualType BaseTy = Base->getType();
4869 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4870 // Not a pointer access
4871 return;
4872
4873 const MemberExpr *Member = nullptr;
4874 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4875 Member->isArrow())
4876 Base = Member->getBase();
4877
4878 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4879 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4880 LastRecord.PossibleDerefs.insert(E);
4881 }
4882 }
4883
ActOnOMPArraySectionExpr(Expr * Base,SourceLocation LBLoc,Expr * LowerBound,SourceLocation ColonLocFirst,SourceLocation ColonLocSecond,Expr * Length,Expr * Stride,SourceLocation RBLoc)4884 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4885 Expr *LowerBound,
4886 SourceLocation ColonLocFirst,
4887 SourceLocation ColonLocSecond,
4888 Expr *Length, Expr *Stride,
4889 SourceLocation RBLoc) {
4890 if (Base->getType()->isPlaceholderType() &&
4891 !Base->getType()->isSpecificPlaceholderType(
4892 BuiltinType::OMPArraySection)) {
4893 ExprResult Result = CheckPlaceholderExpr(Base);
4894 if (Result.isInvalid())
4895 return ExprError();
4896 Base = Result.get();
4897 }
4898 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4899 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4900 if (Result.isInvalid())
4901 return ExprError();
4902 Result = DefaultLvalueConversion(Result.get());
4903 if (Result.isInvalid())
4904 return ExprError();
4905 LowerBound = Result.get();
4906 }
4907 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4908 ExprResult Result = CheckPlaceholderExpr(Length);
4909 if (Result.isInvalid())
4910 return ExprError();
4911 Result = DefaultLvalueConversion(Result.get());
4912 if (Result.isInvalid())
4913 return ExprError();
4914 Length = Result.get();
4915 }
4916 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4917 ExprResult Result = CheckPlaceholderExpr(Stride);
4918 if (Result.isInvalid())
4919 return ExprError();
4920 Result = DefaultLvalueConversion(Result.get());
4921 if (Result.isInvalid())
4922 return ExprError();
4923 Stride = Result.get();
4924 }
4925
4926 // Build an unanalyzed expression if either operand is type-dependent.
4927 if (Base->isTypeDependent() ||
4928 (LowerBound &&
4929 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4930 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4931 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4932 return new (Context) OMPArraySectionExpr(
4933 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4934 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4935 }
4936
4937 // Perform default conversions.
4938 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4939 QualType ResultTy;
4940 if (OriginalTy->isAnyPointerType()) {
4941 ResultTy = OriginalTy->getPointeeType();
4942 } else if (OriginalTy->isArrayType()) {
4943 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4944 } else {
4945 return ExprError(
4946 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4947 << Base->getSourceRange());
4948 }
4949 // C99 6.5.2.1p1
4950 if (LowerBound) {
4951 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4952 LowerBound);
4953 if (Res.isInvalid())
4954 return ExprError(Diag(LowerBound->getExprLoc(),
4955 diag::err_omp_typecheck_section_not_integer)
4956 << 0 << LowerBound->getSourceRange());
4957 LowerBound = Res.get();
4958
4959 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4960 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4961 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4962 << 0 << LowerBound->getSourceRange();
4963 }
4964 if (Length) {
4965 auto Res =
4966 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4967 if (Res.isInvalid())
4968 return ExprError(Diag(Length->getExprLoc(),
4969 diag::err_omp_typecheck_section_not_integer)
4970 << 1 << Length->getSourceRange());
4971 Length = Res.get();
4972
4973 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4974 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4975 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4976 << 1 << Length->getSourceRange();
4977 }
4978 if (Stride) {
4979 ExprResult Res =
4980 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4981 if (Res.isInvalid())
4982 return ExprError(Diag(Stride->getExprLoc(),
4983 diag::err_omp_typecheck_section_not_integer)
4984 << 1 << Stride->getSourceRange());
4985 Stride = Res.get();
4986
4987 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4988 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4989 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4990 << 1 << Stride->getSourceRange();
4991 }
4992
4993 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4994 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4995 // type. Note that functions are not objects, and that (in C99 parlance)
4996 // incomplete types are not object types.
4997 if (ResultTy->isFunctionType()) {
4998 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4999 << ResultTy << Base->getSourceRange();
5000 return ExprError();
5001 }
5002
5003 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
5004 diag::err_omp_section_incomplete_type, Base))
5005 return ExprError();
5006
5007 if (LowerBound && !OriginalTy->isAnyPointerType()) {
5008 Expr::EvalResult Result;
5009 if (LowerBound->EvaluateAsInt(Result, Context)) {
5010 // OpenMP 5.0, [2.1.5 Array Sections]
5011 // The array section must be a subset of the original array.
5012 llvm::APSInt LowerBoundValue = Result.Val.getInt();
5013 if (LowerBoundValue.isNegative()) {
5014 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
5015 << LowerBound->getSourceRange();
5016 return ExprError();
5017 }
5018 }
5019 }
5020
5021 if (Length) {
5022 Expr::EvalResult Result;
5023 if (Length->EvaluateAsInt(Result, Context)) {
5024 // OpenMP 5.0, [2.1.5 Array Sections]
5025 // The length must evaluate to non-negative integers.
5026 llvm::APSInt LengthValue = Result.Val.getInt();
5027 if (LengthValue.isNegative()) {
5028 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
5029 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
5030 << Length->getSourceRange();
5031 return ExprError();
5032 }
5033 }
5034 } else if (ColonLocFirst.isValid() &&
5035 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5036 !OriginalTy->isVariableArrayType()))) {
5037 // OpenMP 5.0, [2.1.5 Array Sections]
5038 // When the size of the array dimension is not known, the length must be
5039 // specified explicitly.
5040 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5041 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5042 return ExprError();
5043 }
5044
5045 if (Stride) {
5046 Expr::EvalResult Result;
5047 if (Stride->EvaluateAsInt(Result, Context)) {
5048 // OpenMP 5.0, [2.1.5 Array Sections]
5049 // The stride must evaluate to a positive integer.
5050 llvm::APSInt StrideValue = Result.Val.getInt();
5051 if (!StrideValue.isStrictlyPositive()) {
5052 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5053 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
5054 << Stride->getSourceRange();
5055 return ExprError();
5056 }
5057 }
5058 }
5059
5060 if (!Base->getType()->isSpecificPlaceholderType(
5061 BuiltinType::OMPArraySection)) {
5062 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5063 if (Result.isInvalid())
5064 return ExprError();
5065 Base = Result.get();
5066 }
5067 return new (Context) OMPArraySectionExpr(
5068 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5069 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5070 }
5071
ActOnOMPArrayShapingExpr(Expr * Base,SourceLocation LParenLoc,SourceLocation RParenLoc,ArrayRef<Expr * > Dims,ArrayRef<SourceRange> Brackets)5072 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5073 SourceLocation RParenLoc,
5074 ArrayRef<Expr *> Dims,
5075 ArrayRef<SourceRange> Brackets) {
5076 if (Base->getType()->isPlaceholderType()) {
5077 ExprResult Result = CheckPlaceholderExpr(Base);
5078 if (Result.isInvalid())
5079 return ExprError();
5080 Result = DefaultLvalueConversion(Result.get());
5081 if (Result.isInvalid())
5082 return ExprError();
5083 Base = Result.get();
5084 }
5085 QualType BaseTy = Base->getType();
5086 // Delay analysis of the types/expressions if instantiation/specialization is
5087 // required.
5088 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5089 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5090 LParenLoc, RParenLoc, Dims, Brackets);
5091 if (!BaseTy->isPointerType() ||
5092 (!Base->isTypeDependent() &&
5093 BaseTy->getPointeeType()->isIncompleteType()))
5094 return ExprError(Diag(Base->getExprLoc(),
5095 diag::err_omp_non_pointer_type_array_shaping_base)
5096 << Base->getSourceRange());
5097
5098 SmallVector<Expr *, 4> NewDims;
5099 bool ErrorFound = false;
5100 for (Expr *Dim : Dims) {
5101 if (Dim->getType()->isPlaceholderType()) {
5102 ExprResult Result = CheckPlaceholderExpr(Dim);
5103 if (Result.isInvalid()) {
5104 ErrorFound = true;
5105 continue;
5106 }
5107 Result = DefaultLvalueConversion(Result.get());
5108 if (Result.isInvalid()) {
5109 ErrorFound = true;
5110 continue;
5111 }
5112 Dim = Result.get();
5113 }
5114 if (!Dim->isTypeDependent()) {
5115 ExprResult Result =
5116 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5117 if (Result.isInvalid()) {
5118 ErrorFound = true;
5119 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5120 << Dim->getSourceRange();
5121 continue;
5122 }
5123 Dim = Result.get();
5124 Expr::EvalResult EvResult;
5125 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5126 // OpenMP 5.0, [2.1.4 Array Shaping]
5127 // Each si is an integral type expression that must evaluate to a
5128 // positive integer.
5129 llvm::APSInt Value = EvResult.Val.getInt();
5130 if (!Value.isStrictlyPositive()) {
5131 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5132 << Value.toString(/*Radix=*/10, /*Signed=*/true)
5133 << Dim->getSourceRange();
5134 ErrorFound = true;
5135 continue;
5136 }
5137 }
5138 }
5139 NewDims.push_back(Dim);
5140 }
5141 if (ErrorFound)
5142 return ExprError();
5143 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5144 LParenLoc, RParenLoc, NewDims, Brackets);
5145 }
5146
ActOnOMPIteratorExpr(Scope * S,SourceLocation IteratorKwLoc,SourceLocation LLoc,SourceLocation RLoc,ArrayRef<OMPIteratorData> Data)5147 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5148 SourceLocation LLoc, SourceLocation RLoc,
5149 ArrayRef<OMPIteratorData> Data) {
5150 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5151 bool IsCorrect = true;
5152 for (const OMPIteratorData &D : Data) {
5153 TypeSourceInfo *TInfo = nullptr;
5154 SourceLocation StartLoc;
5155 QualType DeclTy;
5156 if (!D.Type.getAsOpaquePtr()) {
5157 // OpenMP 5.0, 2.1.6 Iterators
5158 // In an iterator-specifier, if the iterator-type is not specified then
5159 // the type of that iterator is of int type.
5160 DeclTy = Context.IntTy;
5161 StartLoc = D.DeclIdentLoc;
5162 } else {
5163 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5164 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5165 }
5166
5167 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5168 DeclTy->containsUnexpandedParameterPack() ||
5169 DeclTy->isInstantiationDependentType();
5170 if (!IsDeclTyDependent) {
5171 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5172 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5173 // The iterator-type must be an integral or pointer type.
5174 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5175 << DeclTy;
5176 IsCorrect = false;
5177 continue;
5178 }
5179 if (DeclTy.isConstant(Context)) {
5180 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5181 // The iterator-type must not be const qualified.
5182 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5183 << DeclTy;
5184 IsCorrect = false;
5185 continue;
5186 }
5187 }
5188
5189 // Iterator declaration.
5190 assert(D.DeclIdent && "Identifier expected.");
5191 // Always try to create iterator declarator to avoid extra error messages
5192 // about unknown declarations use.
5193 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5194 D.DeclIdent, DeclTy, TInfo, SC_None);
5195 VD->setImplicit();
5196 if (S) {
5197 // Check for conflicting previous declaration.
5198 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5199 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5200 ForVisibleRedeclaration);
5201 Previous.suppressDiagnostics();
5202 LookupName(Previous, S);
5203
5204 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5205 /*AllowInlineNamespace=*/false);
5206 if (!Previous.empty()) {
5207 NamedDecl *Old = Previous.getRepresentativeDecl();
5208 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5209 Diag(Old->getLocation(), diag::note_previous_definition);
5210 } else {
5211 PushOnScopeChains(VD, S);
5212 }
5213 } else {
5214 CurContext->addDecl(VD);
5215 }
5216 Expr *Begin = D.Range.Begin;
5217 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5218 ExprResult BeginRes =
5219 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5220 Begin = BeginRes.get();
5221 }
5222 Expr *End = D.Range.End;
5223 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5224 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5225 End = EndRes.get();
5226 }
5227 Expr *Step = D.Range.Step;
5228 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5229 if (!Step->getType()->isIntegralType(Context)) {
5230 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5231 << Step << Step->getSourceRange();
5232 IsCorrect = false;
5233 continue;
5234 }
5235 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5236 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5237 // If the step expression of a range-specification equals zero, the
5238 // behavior is unspecified.
5239 if (Result && Result->isNullValue()) {
5240 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5241 << Step << Step->getSourceRange();
5242 IsCorrect = false;
5243 continue;
5244 }
5245 }
5246 if (!Begin || !End || !IsCorrect) {
5247 IsCorrect = false;
5248 continue;
5249 }
5250 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5251 IDElem.IteratorDecl = VD;
5252 IDElem.AssignmentLoc = D.AssignLoc;
5253 IDElem.Range.Begin = Begin;
5254 IDElem.Range.End = End;
5255 IDElem.Range.Step = Step;
5256 IDElem.ColonLoc = D.ColonLoc;
5257 IDElem.SecondColonLoc = D.SecColonLoc;
5258 }
5259 if (!IsCorrect) {
5260 // Invalidate all created iterator declarations if error is found.
5261 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5262 if (Decl *ID = D.IteratorDecl)
5263 ID->setInvalidDecl();
5264 }
5265 return ExprError();
5266 }
5267 SmallVector<OMPIteratorHelperData, 4> Helpers;
5268 if (!CurContext->isDependentContext()) {
5269 // Build number of ityeration for each iteration range.
5270 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5271 // ((Begini-Stepi-1-Endi) / -Stepi);
5272 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5273 // (Endi - Begini)
5274 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5275 D.Range.Begin);
5276 if(!Res.isUsable()) {
5277 IsCorrect = false;
5278 continue;
5279 }
5280 ExprResult St, St1;
5281 if (D.Range.Step) {
5282 St = D.Range.Step;
5283 // (Endi - Begini) + Stepi
5284 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5285 if (!Res.isUsable()) {
5286 IsCorrect = false;
5287 continue;
5288 }
5289 // (Endi - Begini) + Stepi - 1
5290 Res =
5291 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5292 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5293 if (!Res.isUsable()) {
5294 IsCorrect = false;
5295 continue;
5296 }
5297 // ((Endi - Begini) + Stepi - 1) / Stepi
5298 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5299 if (!Res.isUsable()) {
5300 IsCorrect = false;
5301 continue;
5302 }
5303 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5304 // (Begini - Endi)
5305 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5306 D.Range.Begin, D.Range.End);
5307 if (!Res1.isUsable()) {
5308 IsCorrect = false;
5309 continue;
5310 }
5311 // (Begini - Endi) - Stepi
5312 Res1 =
5313 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5314 if (!Res1.isUsable()) {
5315 IsCorrect = false;
5316 continue;
5317 }
5318 // (Begini - Endi) - Stepi - 1
5319 Res1 =
5320 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5321 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5322 if (!Res1.isUsable()) {
5323 IsCorrect = false;
5324 continue;
5325 }
5326 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5327 Res1 =
5328 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5329 if (!Res1.isUsable()) {
5330 IsCorrect = false;
5331 continue;
5332 }
5333 // Stepi > 0.
5334 ExprResult CmpRes =
5335 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5336 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5337 if (!CmpRes.isUsable()) {
5338 IsCorrect = false;
5339 continue;
5340 }
5341 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5342 Res.get(), Res1.get());
5343 if (!Res.isUsable()) {
5344 IsCorrect = false;
5345 continue;
5346 }
5347 }
5348 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5349 if (!Res.isUsable()) {
5350 IsCorrect = false;
5351 continue;
5352 }
5353
5354 // Build counter update.
5355 // Build counter.
5356 auto *CounterVD =
5357 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5358 D.IteratorDecl->getBeginLoc(), nullptr,
5359 Res.get()->getType(), nullptr, SC_None);
5360 CounterVD->setImplicit();
5361 ExprResult RefRes =
5362 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5363 D.IteratorDecl->getBeginLoc());
5364 // Build counter update.
5365 // I = Begini + counter * Stepi;
5366 ExprResult UpdateRes;
5367 if (D.Range.Step) {
5368 UpdateRes = CreateBuiltinBinOp(
5369 D.AssignmentLoc, BO_Mul,
5370 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5371 } else {
5372 UpdateRes = DefaultLvalueConversion(RefRes.get());
5373 }
5374 if (!UpdateRes.isUsable()) {
5375 IsCorrect = false;
5376 continue;
5377 }
5378 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5379 UpdateRes.get());
5380 if (!UpdateRes.isUsable()) {
5381 IsCorrect = false;
5382 continue;
5383 }
5384 ExprResult VDRes =
5385 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5386 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5387 D.IteratorDecl->getBeginLoc());
5388 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5389 UpdateRes.get());
5390 if (!UpdateRes.isUsable()) {
5391 IsCorrect = false;
5392 continue;
5393 }
5394 UpdateRes =
5395 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5396 if (!UpdateRes.isUsable()) {
5397 IsCorrect = false;
5398 continue;
5399 }
5400 ExprResult CounterUpdateRes =
5401 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5402 if (!CounterUpdateRes.isUsable()) {
5403 IsCorrect = false;
5404 continue;
5405 }
5406 CounterUpdateRes =
5407 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5408 if (!CounterUpdateRes.isUsable()) {
5409 IsCorrect = false;
5410 continue;
5411 }
5412 OMPIteratorHelperData &HD = Helpers.emplace_back();
5413 HD.CounterVD = CounterVD;
5414 HD.Upper = Res.get();
5415 HD.Update = UpdateRes.get();
5416 HD.CounterUpdate = CounterUpdateRes.get();
5417 }
5418 } else {
5419 Helpers.assign(ID.size(), {});
5420 }
5421 if (!IsCorrect) {
5422 // Invalidate all created iterator declarations if error is found.
5423 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5424 if (Decl *ID = D.IteratorDecl)
5425 ID->setInvalidDecl();
5426 }
5427 return ExprError();
5428 }
5429 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5430 LLoc, RLoc, ID, Helpers);
5431 }
5432
5433 ExprResult
CreateBuiltinArraySubscriptExpr(Expr * Base,SourceLocation LLoc,Expr * Idx,SourceLocation RLoc)5434 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5435 Expr *Idx, SourceLocation RLoc) {
5436 Expr *LHSExp = Base;
5437 Expr *RHSExp = Idx;
5438
5439 ExprValueKind VK = VK_LValue;
5440 ExprObjectKind OK = OK_Ordinary;
5441
5442 // Per C++ core issue 1213, the result is an xvalue if either operand is
5443 // a non-lvalue array, and an lvalue otherwise.
5444 if (getLangOpts().CPlusPlus11) {
5445 for (auto *Op : {LHSExp, RHSExp}) {
5446 Op = Op->IgnoreImplicit();
5447 if (Op->getType()->isArrayType() && !Op->isLValue())
5448 VK = VK_XValue;
5449 }
5450 }
5451
5452 // Perform default conversions.
5453 if (!LHSExp->getType()->getAs<VectorType>()) {
5454 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5455 if (Result.isInvalid())
5456 return ExprError();
5457 LHSExp = Result.get();
5458 }
5459 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5460 if (Result.isInvalid())
5461 return ExprError();
5462 RHSExp = Result.get();
5463
5464 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5465
5466 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5467 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5468 // in the subscript position. As a result, we need to derive the array base
5469 // and index from the expression types.
5470 Expr *BaseExpr, *IndexExpr;
5471 QualType ResultType;
5472 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5473 BaseExpr = LHSExp;
5474 IndexExpr = RHSExp;
5475 ResultType = Context.DependentTy;
5476 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5477 BaseExpr = LHSExp;
5478 IndexExpr = RHSExp;
5479 ResultType = PTy->getPointeeType();
5480 } else if (const ObjCObjectPointerType *PTy =
5481 LHSTy->getAs<ObjCObjectPointerType>()) {
5482 BaseExpr = LHSExp;
5483 IndexExpr = RHSExp;
5484
5485 // Use custom logic if this should be the pseudo-object subscript
5486 // expression.
5487 if (!LangOpts.isSubscriptPointerArithmetic())
5488 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5489 nullptr);
5490
5491 ResultType = PTy->getPointeeType();
5492 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5493 // Handle the uncommon case of "123[Ptr]".
5494 BaseExpr = RHSExp;
5495 IndexExpr = LHSExp;
5496 ResultType = PTy->getPointeeType();
5497 } else if (const ObjCObjectPointerType *PTy =
5498 RHSTy->getAs<ObjCObjectPointerType>()) {
5499 // Handle the uncommon case of "123[Ptr]".
5500 BaseExpr = RHSExp;
5501 IndexExpr = LHSExp;
5502 ResultType = PTy->getPointeeType();
5503 if (!LangOpts.isSubscriptPointerArithmetic()) {
5504 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5505 << ResultType << BaseExpr->getSourceRange();
5506 return ExprError();
5507 }
5508 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5509 BaseExpr = LHSExp; // vectors: V[123]
5510 IndexExpr = RHSExp;
5511 // We apply C++ DR1213 to vector subscripting too.
5512 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5513 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5514 if (Materialized.isInvalid())
5515 return ExprError();
5516 LHSExp = Materialized.get();
5517 }
5518 VK = LHSExp->getValueKind();
5519 if (VK != VK_RValue)
5520 OK = OK_VectorComponent;
5521
5522 ResultType = VTy->getElementType();
5523 QualType BaseType = BaseExpr->getType();
5524 Qualifiers BaseQuals = BaseType.getQualifiers();
5525 Qualifiers MemberQuals = ResultType.getQualifiers();
5526 Qualifiers Combined = BaseQuals + MemberQuals;
5527 if (Combined != MemberQuals)
5528 ResultType = Context.getQualifiedType(ResultType, Combined);
5529 } else if (LHSTy->isArrayType()) {
5530 // If we see an array that wasn't promoted by
5531 // DefaultFunctionArrayLvalueConversion, it must be an array that
5532 // wasn't promoted because of the C90 rule that doesn't
5533 // allow promoting non-lvalue arrays. Warn, then
5534 // force the promotion here.
5535 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5536 << LHSExp->getSourceRange();
5537 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5538 CK_ArrayToPointerDecay).get();
5539 LHSTy = LHSExp->getType();
5540
5541 BaseExpr = LHSExp;
5542 IndexExpr = RHSExp;
5543 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5544 } else if (RHSTy->isArrayType()) {
5545 // Same as previous, except for 123[f().a] case
5546 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5547 << RHSExp->getSourceRange();
5548 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5549 CK_ArrayToPointerDecay).get();
5550 RHSTy = RHSExp->getType();
5551
5552 BaseExpr = RHSExp;
5553 IndexExpr = LHSExp;
5554 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5555 } else {
5556 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5557 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5558 }
5559 // C99 6.5.2.1p1
5560 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5561 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5562 << IndexExpr->getSourceRange());
5563
5564 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5565 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5566 && !IndexExpr->isTypeDependent())
5567 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5568
5569 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5570 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5571 // type. Note that Functions are not objects, and that (in C99 parlance)
5572 // incomplete types are not object types.
5573 if (ResultType->isFunctionType()) {
5574 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5575 << ResultType << BaseExpr->getSourceRange();
5576 return ExprError();
5577 }
5578
5579 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5580 // GNU extension: subscripting on pointer to void
5581 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5582 << BaseExpr->getSourceRange();
5583
5584 // C forbids expressions of unqualified void type from being l-values.
5585 // See IsCForbiddenLValueType.
5586 if (!ResultType.hasQualifiers()) VK = VK_RValue;
5587 } else if (!ResultType->isDependentType() &&
5588 RequireCompleteSizedType(
5589 LLoc, ResultType,
5590 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5591 return ExprError();
5592
5593 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5594 !ResultType.isCForbiddenLValueType());
5595
5596 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5597 FunctionScopes.size() > 1) {
5598 if (auto *TT =
5599 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5600 for (auto I = FunctionScopes.rbegin(),
5601 E = std::prev(FunctionScopes.rend());
5602 I != E; ++I) {
5603 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5604 if (CSI == nullptr)
5605 break;
5606 DeclContext *DC = nullptr;
5607 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5608 DC = LSI->CallOperator;
5609 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5610 DC = CRSI->TheCapturedDecl;
5611 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5612 DC = BSI->TheDecl;
5613 if (DC) {
5614 if (DC->containsDecl(TT->getDecl()))
5615 break;
5616 captureVariablyModifiedType(
5617 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5618 }
5619 }
5620 }
5621 }
5622
5623 return new (Context)
5624 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5625 }
5626
CheckCXXDefaultArgExpr(SourceLocation CallLoc,FunctionDecl * FD,ParmVarDecl * Param)5627 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5628 ParmVarDecl *Param) {
5629 if (Param->hasUnparsedDefaultArg()) {
5630 // If we've already cleared out the location for the default argument,
5631 // that means we're parsing it right now.
5632 if (!UnparsedDefaultArgLocs.count(Param)) {
5633 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5634 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5635 Param->setInvalidDecl();
5636 return true;
5637 }
5638
5639 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5640 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5641 Diag(UnparsedDefaultArgLocs[Param],
5642 diag::note_default_argument_declared_here);
5643 return true;
5644 }
5645
5646 if (Param->hasUninstantiatedDefaultArg() &&
5647 InstantiateDefaultArgument(CallLoc, FD, Param))
5648 return true;
5649
5650 assert(Param->hasInit() && "default argument but no initializer?");
5651
5652 // If the default expression creates temporaries, we need to
5653 // push them to the current stack of expression temporaries so they'll
5654 // be properly destroyed.
5655 // FIXME: We should really be rebuilding the default argument with new
5656 // bound temporaries; see the comment in PR5810.
5657 // We don't need to do that with block decls, though, because
5658 // blocks in default argument expression can never capture anything.
5659 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5660 // Set the "needs cleanups" bit regardless of whether there are
5661 // any explicit objects.
5662 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5663
5664 // Append all the objects to the cleanup list. Right now, this
5665 // should always be a no-op, because blocks in default argument
5666 // expressions should never be able to capture anything.
5667 assert(!Init->getNumObjects() &&
5668 "default argument expression has capturing blocks?");
5669 }
5670
5671 // We already type-checked the argument, so we know it works.
5672 // Just mark all of the declarations in this potentially-evaluated expression
5673 // as being "referenced".
5674 EnterExpressionEvaluationContext EvalContext(
5675 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5676 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5677 /*SkipLocalVariables=*/true);
5678 return false;
5679 }
5680
BuildCXXDefaultArgExpr(SourceLocation CallLoc,FunctionDecl * FD,ParmVarDecl * Param)5681 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5682 FunctionDecl *FD, ParmVarDecl *Param) {
5683 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5684 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5685 return ExprError();
5686 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5687 }
5688
5689 Sema::VariadicCallType
getVariadicCallType(FunctionDecl * FDecl,const FunctionProtoType * Proto,Expr * Fn)5690 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5691 Expr *Fn) {
5692 if (Proto && Proto->isVariadic()) {
5693 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5694 return VariadicConstructor;
5695 else if (Fn && Fn->getType()->isBlockPointerType())
5696 return VariadicBlock;
5697 else if (FDecl) {
5698 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5699 if (Method->isInstance())
5700 return VariadicMethod;
5701 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5702 return VariadicMethod;
5703 return VariadicFunction;
5704 }
5705 return VariadicDoesNotApply;
5706 }
5707
5708 namespace {
5709 class FunctionCallCCC final : public FunctionCallFilterCCC {
5710 public:
FunctionCallCCC(Sema & SemaRef,const IdentifierInfo * FuncName,unsigned NumArgs,MemberExpr * ME)5711 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5712 unsigned NumArgs, MemberExpr *ME)
5713 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5714 FunctionName(FuncName) {}
5715
ValidateCandidate(const TypoCorrection & candidate)5716 bool ValidateCandidate(const TypoCorrection &candidate) override {
5717 if (!candidate.getCorrectionSpecifier() ||
5718 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5719 return false;
5720 }
5721
5722 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5723 }
5724
clone()5725 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5726 return std::make_unique<FunctionCallCCC>(*this);
5727 }
5728
5729 private:
5730 const IdentifierInfo *const FunctionName;
5731 };
5732 }
5733
TryTypoCorrectionForCall(Sema & S,Expr * Fn,FunctionDecl * FDecl,ArrayRef<Expr * > Args)5734 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5735 FunctionDecl *FDecl,
5736 ArrayRef<Expr *> Args) {
5737 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5738 DeclarationName FuncName = FDecl->getDeclName();
5739 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5740
5741 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5742 if (TypoCorrection Corrected = S.CorrectTypo(
5743 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5744 S.getScopeForContext(S.CurContext), nullptr, CCC,
5745 Sema::CTK_ErrorRecovery)) {
5746 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5747 if (Corrected.isOverloaded()) {
5748 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5749 OverloadCandidateSet::iterator Best;
5750 for (NamedDecl *CD : Corrected) {
5751 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5752 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5753 OCS);
5754 }
5755 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5756 case OR_Success:
5757 ND = Best->FoundDecl;
5758 Corrected.setCorrectionDecl(ND);
5759 break;
5760 default:
5761 break;
5762 }
5763 }
5764 ND = ND->getUnderlyingDecl();
5765 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5766 return Corrected;
5767 }
5768 }
5769 return TypoCorrection();
5770 }
5771
5772 /// ConvertArgumentsForCall - Converts the arguments specified in
5773 /// Args/NumArgs to the parameter types of the function FDecl with
5774 /// function prototype Proto. Call is the call expression itself, and
5775 /// Fn is the function expression. For a C++ member function, this
5776 /// routine does not attempt to convert the object argument. Returns
5777 /// true if the call is ill-formed.
5778 bool
ConvertArgumentsForCall(CallExpr * Call,Expr * Fn,FunctionDecl * FDecl,const FunctionProtoType * Proto,ArrayRef<Expr * > Args,SourceLocation RParenLoc,bool IsExecConfig)5779 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5780 FunctionDecl *FDecl,
5781 const FunctionProtoType *Proto,
5782 ArrayRef<Expr *> Args,
5783 SourceLocation RParenLoc,
5784 bool IsExecConfig) {
5785 // Bail out early if calling a builtin with custom typechecking.
5786 if (FDecl)
5787 if (unsigned ID = FDecl->getBuiltinID())
5788 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5789 return false;
5790
5791 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5792 // assignment, to the types of the corresponding parameter, ...
5793 unsigned NumParams = Proto->getNumParams();
5794 bool Invalid = false;
5795 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5796 unsigned FnKind = Fn->getType()->isBlockPointerType()
5797 ? 1 /* block */
5798 : (IsExecConfig ? 3 /* kernel function (exec config) */
5799 : 0 /* function */);
5800
5801 // If too few arguments are available (and we don't have default
5802 // arguments for the remaining parameters), don't make the call.
5803 if (Args.size() < NumParams) {
5804 if (Args.size() < MinArgs) {
5805 TypoCorrection TC;
5806 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5807 unsigned diag_id =
5808 MinArgs == NumParams && !Proto->isVariadic()
5809 ? diag::err_typecheck_call_too_few_args_suggest
5810 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5811 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5812 << static_cast<unsigned>(Args.size())
5813 << TC.getCorrectionRange());
5814 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5815 Diag(RParenLoc,
5816 MinArgs == NumParams && !Proto->isVariadic()
5817 ? diag::err_typecheck_call_too_few_args_one
5818 : diag::err_typecheck_call_too_few_args_at_least_one)
5819 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5820 else
5821 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5822 ? diag::err_typecheck_call_too_few_args
5823 : diag::err_typecheck_call_too_few_args_at_least)
5824 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5825 << Fn->getSourceRange();
5826
5827 // Emit the location of the prototype.
5828 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5829 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5830
5831 return true;
5832 }
5833 // We reserve space for the default arguments when we create
5834 // the call expression, before calling ConvertArgumentsForCall.
5835 assert((Call->getNumArgs() == NumParams) &&
5836 "We should have reserved space for the default arguments before!");
5837 }
5838
5839 // If too many are passed and not variadic, error on the extras and drop
5840 // them.
5841 if (Args.size() > NumParams) {
5842 if (!Proto->isVariadic()) {
5843 TypoCorrection TC;
5844 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5845 unsigned diag_id =
5846 MinArgs == NumParams && !Proto->isVariadic()
5847 ? diag::err_typecheck_call_too_many_args_suggest
5848 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5849 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5850 << static_cast<unsigned>(Args.size())
5851 << TC.getCorrectionRange());
5852 } else if (NumParams == 1 && FDecl &&
5853 FDecl->getParamDecl(0)->getDeclName())
5854 Diag(Args[NumParams]->getBeginLoc(),
5855 MinArgs == NumParams
5856 ? diag::err_typecheck_call_too_many_args_one
5857 : diag::err_typecheck_call_too_many_args_at_most_one)
5858 << FnKind << FDecl->getParamDecl(0)
5859 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5860 << SourceRange(Args[NumParams]->getBeginLoc(),
5861 Args.back()->getEndLoc());
5862 else
5863 Diag(Args[NumParams]->getBeginLoc(),
5864 MinArgs == NumParams
5865 ? diag::err_typecheck_call_too_many_args
5866 : diag::err_typecheck_call_too_many_args_at_most)
5867 << FnKind << NumParams << static_cast<unsigned>(Args.size())
5868 << Fn->getSourceRange()
5869 << SourceRange(Args[NumParams]->getBeginLoc(),
5870 Args.back()->getEndLoc());
5871
5872 // Emit the location of the prototype.
5873 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5874 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5875
5876 // This deletes the extra arguments.
5877 Call->shrinkNumArgs(NumParams);
5878 return true;
5879 }
5880 }
5881 SmallVector<Expr *, 8> AllArgs;
5882 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5883
5884 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5885 AllArgs, CallType);
5886 if (Invalid)
5887 return true;
5888 unsigned TotalNumArgs = AllArgs.size();
5889 for (unsigned i = 0; i < TotalNumArgs; ++i)
5890 Call->setArg(i, AllArgs[i]);
5891
5892 return false;
5893 }
5894
GatherArgumentsForCall(SourceLocation CallLoc,FunctionDecl * FDecl,const FunctionProtoType * Proto,unsigned FirstParam,ArrayRef<Expr * > Args,SmallVectorImpl<Expr * > & AllArgs,VariadicCallType CallType,bool AllowExplicit,bool IsListInitialization)5895 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5896 const FunctionProtoType *Proto,
5897 unsigned FirstParam, ArrayRef<Expr *> Args,
5898 SmallVectorImpl<Expr *> &AllArgs,
5899 VariadicCallType CallType, bool AllowExplicit,
5900 bool IsListInitialization) {
5901 unsigned NumParams = Proto->getNumParams();
5902 bool Invalid = false;
5903 size_t ArgIx = 0;
5904 // Continue to check argument types (even if we have too few/many args).
5905 for (unsigned i = FirstParam; i < NumParams; i++) {
5906 QualType ProtoArgType = Proto->getParamType(i);
5907
5908 Expr *Arg;
5909 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5910 if (ArgIx < Args.size()) {
5911 Arg = Args[ArgIx++];
5912
5913 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5914 diag::err_call_incomplete_argument, Arg))
5915 return true;
5916
5917 // Strip the unbridged-cast placeholder expression off, if applicable.
5918 bool CFAudited = false;
5919 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5920 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5921 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5922 Arg = stripARCUnbridgedCast(Arg);
5923 else if (getLangOpts().ObjCAutoRefCount &&
5924 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5925 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5926 CFAudited = true;
5927
5928 if (Proto->getExtParameterInfo(i).isNoEscape() &&
5929 ProtoArgType->isBlockPointerType())
5930 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5931 BE->getBlockDecl()->setDoesNotEscape();
5932
5933 InitializedEntity Entity =
5934 Param ? InitializedEntity::InitializeParameter(Context, Param,
5935 ProtoArgType)
5936 : InitializedEntity::InitializeParameter(
5937 Context, ProtoArgType, Proto->isParamConsumed(i));
5938
5939 // Remember that parameter belongs to a CF audited API.
5940 if (CFAudited)
5941 Entity.setParameterCFAudited();
5942
5943 ExprResult ArgE = PerformCopyInitialization(
5944 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5945 if (ArgE.isInvalid())
5946 return true;
5947
5948 Arg = ArgE.getAs<Expr>();
5949 } else {
5950 assert(Param && "can't use default arguments without a known callee");
5951
5952 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5953 if (ArgExpr.isInvalid())
5954 return true;
5955
5956 Arg = ArgExpr.getAs<Expr>();
5957 }
5958
5959 // Check for array bounds violations for each argument to the call. This
5960 // check only triggers warnings when the argument isn't a more complex Expr
5961 // with its own checking, such as a BinaryOperator.
5962 CheckArrayAccess(Arg);
5963
5964 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5965 CheckStaticArrayArgument(CallLoc, Param, Arg);
5966
5967 AllArgs.push_back(Arg);
5968 }
5969
5970 // If this is a variadic call, handle args passed through "...".
5971 if (CallType != VariadicDoesNotApply) {
5972 // Assume that extern "C" functions with variadic arguments that
5973 // return __unknown_anytype aren't *really* variadic.
5974 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5975 FDecl->isExternC()) {
5976 for (Expr *A : Args.slice(ArgIx)) {
5977 QualType paramType; // ignored
5978 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5979 Invalid |= arg.isInvalid();
5980 AllArgs.push_back(arg.get());
5981 }
5982
5983 // Otherwise do argument promotion, (C99 6.5.2.2p7).
5984 } else {
5985 for (Expr *A : Args.slice(ArgIx)) {
5986 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5987 Invalid |= Arg.isInvalid();
5988 AllArgs.push_back(Arg.get());
5989 }
5990 }
5991
5992 // Check for array bounds violations.
5993 for (Expr *A : Args.slice(ArgIx))
5994 CheckArrayAccess(A);
5995 }
5996 return Invalid;
5997 }
5998
DiagnoseCalleeStaticArrayParam(Sema & S,ParmVarDecl * PVD)5999 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
6000 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6001 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6002 TL = DTL.getOriginalLoc();
6003 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6004 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6005 << ATL.getLocalSourceRange();
6006 }
6007
6008 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6009 /// array parameter, check that it is non-null, and that if it is formed by
6010 /// array-to-pointer decay, the underlying array is sufficiently large.
6011 ///
6012 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6013 /// array type derivation, then for each call to the function, the value of the
6014 /// corresponding actual argument shall provide access to the first element of
6015 /// an array with at least as many elements as specified by the size expression.
6016 void
CheckStaticArrayArgument(SourceLocation CallLoc,ParmVarDecl * Param,const Expr * ArgExpr)6017 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
6018 ParmVarDecl *Param,
6019 const Expr *ArgExpr) {
6020 // Static array parameters are not supported in C++.
6021 if (!Param || getLangOpts().CPlusPlus)
6022 return;
6023
6024 QualType OrigTy = Param->getOriginalType();
6025
6026 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6027 if (!AT || AT->getSizeModifier() != ArrayType::Static)
6028 return;
6029
6030 if (ArgExpr->isNullPointerConstant(Context,
6031 Expr::NPC_NeverValueDependent)) {
6032 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6033 DiagnoseCalleeStaticArrayParam(*this, Param);
6034 return;
6035 }
6036
6037 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6038 if (!CAT)
6039 return;
6040
6041 const ConstantArrayType *ArgCAT =
6042 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6043 if (!ArgCAT)
6044 return;
6045
6046 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6047 ArgCAT->getElementType())) {
6048 if (ArgCAT->getSize().ult(CAT->getSize())) {
6049 Diag(CallLoc, diag::warn_static_array_too_small)
6050 << ArgExpr->getSourceRange()
6051 << (unsigned)ArgCAT->getSize().getZExtValue()
6052 << (unsigned)CAT->getSize().getZExtValue() << 0;
6053 DiagnoseCalleeStaticArrayParam(*this, Param);
6054 }
6055 return;
6056 }
6057
6058 Optional<CharUnits> ArgSize =
6059 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6060 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6061 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6062 Diag(CallLoc, diag::warn_static_array_too_small)
6063 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6064 << (unsigned)ParmSize->getQuantity() << 1;
6065 DiagnoseCalleeStaticArrayParam(*this, Param);
6066 }
6067 }
6068
6069 /// Given a function expression of unknown-any type, try to rebuild it
6070 /// to have a function type.
6071 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6072
6073 /// Is the given type a placeholder that we need to lower out
6074 /// immediately during argument processing?
isPlaceholderToRemoveAsArg(QualType type)6075 static bool isPlaceholderToRemoveAsArg(QualType type) {
6076 // Placeholders are never sugared.
6077 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6078 if (!placeholder) return false;
6079
6080 switch (placeholder->getKind()) {
6081 // Ignore all the non-placeholder types.
6082 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6083 case BuiltinType::Id:
6084 #include "clang/Basic/OpenCLImageTypes.def"
6085 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6086 case BuiltinType::Id:
6087 #include "clang/Basic/OpenCLExtensionTypes.def"
6088 // In practice we'll never use this, since all SVE types are sugared
6089 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6090 #define SVE_TYPE(Name, Id, SingletonId) \
6091 case BuiltinType::Id:
6092 #include "clang/Basic/AArch64SVEACLETypes.def"
6093 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6094 case BuiltinType::Id:
6095 #include "clang/Basic/PPCTypes.def"
6096 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6097 #include "clang/Basic/RISCVVTypes.def"
6098 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6099 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6100 #include "clang/AST/BuiltinTypes.def"
6101 return false;
6102
6103 // We cannot lower out overload sets; they might validly be resolved
6104 // by the call machinery.
6105 case BuiltinType::Overload:
6106 return false;
6107
6108 // Unbridged casts in ARC can be handled in some call positions and
6109 // should be left in place.
6110 case BuiltinType::ARCUnbridgedCast:
6111 return false;
6112
6113 // Pseudo-objects should be converted as soon as possible.
6114 case BuiltinType::PseudoObject:
6115 return true;
6116
6117 // The debugger mode could theoretically but currently does not try
6118 // to resolve unknown-typed arguments based on known parameter types.
6119 case BuiltinType::UnknownAny:
6120 return true;
6121
6122 // These are always invalid as call arguments and should be reported.
6123 case BuiltinType::BoundMember:
6124 case BuiltinType::BuiltinFn:
6125 case BuiltinType::IncompleteMatrixIdx:
6126 case BuiltinType::OMPArraySection:
6127 case BuiltinType::OMPArrayShaping:
6128 case BuiltinType::OMPIterator:
6129 return true;
6130
6131 }
6132 llvm_unreachable("bad builtin type kind");
6133 }
6134
6135 /// Check an argument list for placeholders that we won't try to
6136 /// handle later.
checkArgsForPlaceholders(Sema & S,MultiExprArg args)6137 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6138 // Apply this processing to all the arguments at once instead of
6139 // dying at the first failure.
6140 bool hasInvalid = false;
6141 for (size_t i = 0, e = args.size(); i != e; i++) {
6142 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6143 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6144 if (result.isInvalid()) hasInvalid = true;
6145 else args[i] = result.get();
6146 }
6147 }
6148 return hasInvalid;
6149 }
6150
6151 /// If a builtin function has a pointer argument with no explicit address
6152 /// space, then it should be able to accept a pointer to any address
6153 /// space as input. In order to do this, we need to replace the
6154 /// standard builtin declaration with one that uses the same address space
6155 /// as the call.
6156 ///
6157 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6158 /// it does not contain any pointer arguments without
6159 /// an address space qualifer. Otherwise the rewritten
6160 /// FunctionDecl is returned.
6161 /// TODO: Handle pointer return types.
rewriteBuiltinFunctionDecl(Sema * Sema,ASTContext & Context,FunctionDecl * FDecl,MultiExprArg ArgExprs)6162 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6163 FunctionDecl *FDecl,
6164 MultiExprArg ArgExprs) {
6165
6166 QualType DeclType = FDecl->getType();
6167 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6168
6169 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6170 ArgExprs.size() < FT->getNumParams())
6171 return nullptr;
6172
6173 bool NeedsNewDecl = false;
6174 unsigned i = 0;
6175 SmallVector<QualType, 8> OverloadParams;
6176
6177 for (QualType ParamType : FT->param_types()) {
6178
6179 // Convert array arguments to pointer to simplify type lookup.
6180 ExprResult ArgRes =
6181 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6182 if (ArgRes.isInvalid())
6183 return nullptr;
6184 Expr *Arg = ArgRes.get();
6185 QualType ArgType = Arg->getType();
6186 if (!ParamType->isPointerType() ||
6187 ParamType.hasAddressSpace() ||
6188 !ArgType->isPointerType() ||
6189 !ArgType->getPointeeType().hasAddressSpace()) {
6190 OverloadParams.push_back(ParamType);
6191 continue;
6192 }
6193
6194 QualType PointeeType = ParamType->getPointeeType();
6195 if (PointeeType.hasAddressSpace())
6196 continue;
6197
6198 NeedsNewDecl = true;
6199 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6200
6201 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6202 OverloadParams.push_back(Context.getPointerType(PointeeType));
6203 }
6204
6205 if (!NeedsNewDecl)
6206 return nullptr;
6207
6208 FunctionProtoType::ExtProtoInfo EPI;
6209 EPI.Variadic = FT->isVariadic();
6210 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6211 OverloadParams, EPI);
6212 DeclContext *Parent = FDecl->getParent();
6213 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6214 FDecl->getLocation(),
6215 FDecl->getLocation(),
6216 FDecl->getIdentifier(),
6217 OverloadTy,
6218 /*TInfo=*/nullptr,
6219 SC_Extern, false,
6220 /*hasPrototype=*/true);
6221 SmallVector<ParmVarDecl*, 16> Params;
6222 FT = cast<FunctionProtoType>(OverloadTy);
6223 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6224 QualType ParamType = FT->getParamType(i);
6225 ParmVarDecl *Parm =
6226 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6227 SourceLocation(), nullptr, ParamType,
6228 /*TInfo=*/nullptr, SC_None, nullptr);
6229 Parm->setScopeInfo(0, i);
6230 Params.push_back(Parm);
6231 }
6232 OverloadDecl->setParams(Params);
6233 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6234 return OverloadDecl;
6235 }
6236
checkDirectCallValidity(Sema & S,const Expr * Fn,FunctionDecl * Callee,MultiExprArg ArgExprs)6237 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6238 FunctionDecl *Callee,
6239 MultiExprArg ArgExprs) {
6240 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6241 // similar attributes) really don't like it when functions are called with an
6242 // invalid number of args.
6243 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6244 /*PartialOverloading=*/false) &&
6245 !Callee->isVariadic())
6246 return;
6247 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6248 return;
6249
6250 if (const EnableIfAttr *Attr =
6251 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6252 S.Diag(Fn->getBeginLoc(),
6253 isa<CXXMethodDecl>(Callee)
6254 ? diag::err_ovl_no_viable_member_function_in_call
6255 : diag::err_ovl_no_viable_function_in_call)
6256 << Callee << Callee->getSourceRange();
6257 S.Diag(Callee->getLocation(),
6258 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6259 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6260 return;
6261 }
6262 }
6263
enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr * const UME,Sema & S)6264 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6265 const UnresolvedMemberExpr *const UME, Sema &S) {
6266
6267 const auto GetFunctionLevelDCIfCXXClass =
6268 [](Sema &S) -> const CXXRecordDecl * {
6269 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6270 if (!DC || !DC->getParent())
6271 return nullptr;
6272
6273 // If the call to some member function was made from within a member
6274 // function body 'M' return return 'M's parent.
6275 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6276 return MD->getParent()->getCanonicalDecl();
6277 // else the call was made from within a default member initializer of a
6278 // class, so return the class.
6279 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6280 return RD->getCanonicalDecl();
6281 return nullptr;
6282 };
6283 // If our DeclContext is neither a member function nor a class (in the
6284 // case of a lambda in a default member initializer), we can't have an
6285 // enclosing 'this'.
6286
6287 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6288 if (!CurParentClass)
6289 return false;
6290
6291 // The naming class for implicit member functions call is the class in which
6292 // name lookup starts.
6293 const CXXRecordDecl *const NamingClass =
6294 UME->getNamingClass()->getCanonicalDecl();
6295 assert(NamingClass && "Must have naming class even for implicit access");
6296
6297 // If the unresolved member functions were found in a 'naming class' that is
6298 // related (either the same or derived from) to the class that contains the
6299 // member function that itself contained the implicit member access.
6300
6301 return CurParentClass == NamingClass ||
6302 CurParentClass->isDerivedFrom(NamingClass);
6303 }
6304
6305 static void
tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema & S,const UnresolvedMemberExpr * const UME,SourceLocation CallLoc)6306 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6307 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6308
6309 if (!UME)
6310 return;
6311
6312 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6313 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6314 // already been captured, or if this is an implicit member function call (if
6315 // it isn't, an attempt to capture 'this' should already have been made).
6316 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6317 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6318 return;
6319
6320 // Check if the naming class in which the unresolved members were found is
6321 // related (same as or is a base of) to the enclosing class.
6322
6323 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6324 return;
6325
6326
6327 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6328 // If the enclosing function is not dependent, then this lambda is
6329 // capture ready, so if we can capture this, do so.
6330 if (!EnclosingFunctionCtx->isDependentContext()) {
6331 // If the current lambda and all enclosing lambdas can capture 'this' -
6332 // then go ahead and capture 'this' (since our unresolved overload set
6333 // contains at least one non-static member function).
6334 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6335 S.CheckCXXThisCapture(CallLoc);
6336 } else if (S.CurContext->isDependentContext()) {
6337 // ... since this is an implicit member reference, that might potentially
6338 // involve a 'this' capture, mark 'this' for potential capture in
6339 // enclosing lambdas.
6340 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6341 CurLSI->addPotentialThisCapture(CallLoc);
6342 }
6343 }
6344
ActOnCallExpr(Scope * Scope,Expr * Fn,SourceLocation LParenLoc,MultiExprArg ArgExprs,SourceLocation RParenLoc,Expr * ExecConfig)6345 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6346 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6347 Expr *ExecConfig) {
6348 ExprResult Call =
6349 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6350 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6351 if (Call.isInvalid())
6352 return Call;
6353
6354 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6355 // language modes.
6356 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6357 if (ULE->hasExplicitTemplateArgs() &&
6358 ULE->decls_begin() == ULE->decls_end()) {
6359 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6360 ? diag::warn_cxx17_compat_adl_only_template_id
6361 : diag::ext_adl_only_template_id)
6362 << ULE->getName();
6363 }
6364 }
6365
6366 if (LangOpts.OpenMP)
6367 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6368 ExecConfig);
6369
6370 return Call;
6371 }
6372
6373 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6374 /// This provides the location of the left/right parens and a list of comma
6375 /// locations.
BuildCallExpr(Scope * Scope,Expr * Fn,SourceLocation LParenLoc,MultiExprArg ArgExprs,SourceLocation RParenLoc,Expr * ExecConfig,bool IsExecConfig,bool AllowRecovery)6376 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6377 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6378 Expr *ExecConfig, bool IsExecConfig,
6379 bool AllowRecovery) {
6380 // Since this might be a postfix expression, get rid of ParenListExprs.
6381 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6382 if (Result.isInvalid()) return ExprError();
6383 Fn = Result.get();
6384
6385 if (checkArgsForPlaceholders(*this, ArgExprs))
6386 return ExprError();
6387
6388 if (getLangOpts().CPlusPlus) {
6389 // If this is a pseudo-destructor expression, build the call immediately.
6390 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6391 if (!ArgExprs.empty()) {
6392 // Pseudo-destructor calls should not have any arguments.
6393 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6394 << FixItHint::CreateRemoval(
6395 SourceRange(ArgExprs.front()->getBeginLoc(),
6396 ArgExprs.back()->getEndLoc()));
6397 }
6398
6399 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6400 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6401 }
6402 if (Fn->getType() == Context.PseudoObjectTy) {
6403 ExprResult result = CheckPlaceholderExpr(Fn);
6404 if (result.isInvalid()) return ExprError();
6405 Fn = result.get();
6406 }
6407
6408 // Determine whether this is a dependent call inside a C++ template,
6409 // in which case we won't do any semantic analysis now.
6410 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6411 if (ExecConfig) {
6412 return CUDAKernelCallExpr::Create(
6413 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6414 Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides());
6415 } else {
6416
6417 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6418 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6419 Fn->getBeginLoc());
6420
6421 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6422 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6423 }
6424 }
6425
6426 // Determine whether this is a call to an object (C++ [over.call.object]).
6427 if (Fn->getType()->isRecordType())
6428 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6429 RParenLoc);
6430
6431 if (Fn->getType() == Context.UnknownAnyTy) {
6432 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6433 if (result.isInvalid()) return ExprError();
6434 Fn = result.get();
6435 }
6436
6437 if (Fn->getType() == Context.BoundMemberTy) {
6438 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6439 RParenLoc, AllowRecovery);
6440 }
6441 }
6442
6443 // Check for overloaded calls. This can happen even in C due to extensions.
6444 if (Fn->getType() == Context.OverloadTy) {
6445 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6446
6447 // We aren't supposed to apply this logic if there's an '&' involved.
6448 if (!find.HasFormOfMemberPointer) {
6449 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6450 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6451 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6452 OverloadExpr *ovl = find.Expression;
6453 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6454 return BuildOverloadedCallExpr(
6455 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6456 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6457 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6458 RParenLoc, AllowRecovery);
6459 }
6460 }
6461
6462 // If we're directly calling a function, get the appropriate declaration.
6463 if (Fn->getType() == Context.UnknownAnyTy) {
6464 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6465 if (result.isInvalid()) return ExprError();
6466 Fn = result.get();
6467 }
6468
6469 Expr *NakedFn = Fn->IgnoreParens();
6470
6471 bool CallingNDeclIndirectly = false;
6472 NamedDecl *NDecl = nullptr;
6473 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6474 if (UnOp->getOpcode() == UO_AddrOf) {
6475 CallingNDeclIndirectly = true;
6476 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6477 }
6478 }
6479
6480 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6481 NDecl = DRE->getDecl();
6482
6483 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6484 if (FDecl && FDecl->getBuiltinID()) {
6485 // Rewrite the function decl for this builtin by replacing parameters
6486 // with no explicit address space with the address space of the arguments
6487 // in ArgExprs.
6488 if ((FDecl =
6489 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6490 NDecl = FDecl;
6491 Fn = DeclRefExpr::Create(
6492 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6493 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6494 nullptr, DRE->isNonOdrUse());
6495 }
6496 }
6497 } else if (isa<MemberExpr>(NakedFn))
6498 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6499
6500 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6501 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6502 FD, /*Complain=*/true, Fn->getBeginLoc()))
6503 return ExprError();
6504
6505 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6506 }
6507
6508 if (Context.isDependenceAllowed() &&
6509 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6510 assert(!getLangOpts().CPlusPlus);
6511 assert((Fn->containsErrors() ||
6512 llvm::any_of(ArgExprs,
6513 [](clang::Expr *E) { return E->containsErrors(); })) &&
6514 "should only occur in error-recovery path.");
6515 QualType ReturnType =
6516 llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6517 ? cast<FunctionDecl>(NDecl)->getCallResultType()
6518 : Context.DependentTy;
6519 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6520 Expr::getValueKindForType(ReturnType), RParenLoc,
6521 CurFPFeatureOverrides());
6522 }
6523 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6524 ExecConfig, IsExecConfig);
6525 }
6526
6527 /// Parse a __builtin_astype expression.
6528 ///
6529 /// __builtin_astype( value, dst type )
6530 ///
ActOnAsTypeExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)6531 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6532 SourceLocation BuiltinLoc,
6533 SourceLocation RParenLoc) {
6534 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6535 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6536 }
6537
6538 /// Create a new AsTypeExpr node (bitcast) from the arguments.
BuildAsTypeExpr(Expr * E,QualType DestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)6539 ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6540 SourceLocation BuiltinLoc,
6541 SourceLocation RParenLoc) {
6542 ExprValueKind VK = VK_RValue;
6543 ExprObjectKind OK = OK_Ordinary;
6544 QualType SrcTy = E->getType();
6545 if (!SrcTy->isDependentType() &&
6546 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6547 return ExprError(
6548 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6549 << DestTy << SrcTy << E->getSourceRange());
6550 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6551 }
6552
6553 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6554 /// provided arguments.
6555 ///
6556 /// __builtin_convertvector( value, dst type )
6557 ///
ActOnConvertVectorExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)6558 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6559 SourceLocation BuiltinLoc,
6560 SourceLocation RParenLoc) {
6561 TypeSourceInfo *TInfo;
6562 GetTypeFromParser(ParsedDestTy, &TInfo);
6563 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6564 }
6565
6566 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6567 /// i.e. an expression not of \p OverloadTy. The expression should
6568 /// unary-convert to an expression of function-pointer or
6569 /// block-pointer type.
6570 ///
6571 /// \param NDecl the declaration being called, if available
BuildResolvedCallExpr(Expr * Fn,NamedDecl * NDecl,SourceLocation LParenLoc,ArrayRef<Expr * > Args,SourceLocation RParenLoc,Expr * Config,bool IsExecConfig,ADLCallKind UsesADL)6572 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6573 SourceLocation LParenLoc,
6574 ArrayRef<Expr *> Args,
6575 SourceLocation RParenLoc, Expr *Config,
6576 bool IsExecConfig, ADLCallKind UsesADL) {
6577 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6578 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6579
6580 // Functions with 'interrupt' attribute cannot be called directly.
6581 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6582 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6583 return ExprError();
6584 }
6585
6586 // Interrupt handlers don't save off the VFP regs automatically on ARM,
6587 // so there's some risk when calling out to non-interrupt handler functions
6588 // that the callee might not preserve them. This is easy to diagnose here,
6589 // but can be very challenging to debug.
6590 // Likewise, X86 interrupt handlers may only call routines with attribute
6591 // no_caller_saved_registers since there is no efficient way to
6592 // save and restore the non-GPR state.
6593 if (auto *Caller = getCurFunctionDecl()) {
6594 if (Caller->hasAttr<ARMInterruptAttr>()) {
6595 bool VFP = Context.getTargetInfo().hasFeature("vfp");
6596 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6597 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6598 if (FDecl)
6599 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6600 }
6601 }
6602 if (Caller->hasAttr<AnyX86InterruptAttr>() &&
6603 ((!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()))) {
6604 Diag(Fn->getExprLoc(), diag::warn_anyx86_interrupt_regsave);
6605 if (FDecl)
6606 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6607 }
6608 }
6609
6610 // Promote the function operand.
6611 // We special-case function promotion here because we only allow promoting
6612 // builtin functions to function pointers in the callee of a call.
6613 ExprResult Result;
6614 QualType ResultTy;
6615 if (BuiltinID &&
6616 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6617 // Extract the return type from the (builtin) function pointer type.
6618 // FIXME Several builtins still have setType in
6619 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6620 // Builtins.def to ensure they are correct before removing setType calls.
6621 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6622 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6623 ResultTy = FDecl->getCallResultType();
6624 } else {
6625 Result = CallExprUnaryConversions(Fn);
6626 ResultTy = Context.BoolTy;
6627 }
6628 if (Result.isInvalid())
6629 return ExprError();
6630 Fn = Result.get();
6631
6632 // Check for a valid function type, but only if it is not a builtin which
6633 // requires custom type checking. These will be handled by
6634 // CheckBuiltinFunctionCall below just after creation of the call expression.
6635 const FunctionType *FuncT = nullptr;
6636 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6637 retry:
6638 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6639 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6640 // have type pointer to function".
6641 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6642 if (!FuncT)
6643 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6644 << Fn->getType() << Fn->getSourceRange());
6645 } else if (const BlockPointerType *BPT =
6646 Fn->getType()->getAs<BlockPointerType>()) {
6647 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6648 } else {
6649 // Handle calls to expressions of unknown-any type.
6650 if (Fn->getType() == Context.UnknownAnyTy) {
6651 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6652 if (rewrite.isInvalid())
6653 return ExprError();
6654 Fn = rewrite.get();
6655 goto retry;
6656 }
6657
6658 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6659 << Fn->getType() << Fn->getSourceRange());
6660 }
6661 }
6662
6663 // Get the number of parameters in the function prototype, if any.
6664 // We will allocate space for max(Args.size(), NumParams) arguments
6665 // in the call expression.
6666 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6667 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6668
6669 CallExpr *TheCall;
6670 if (Config) {
6671 assert(UsesADL == ADLCallKind::NotADL &&
6672 "CUDAKernelCallExpr should not use ADL");
6673 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6674 Args, ResultTy, VK_RValue, RParenLoc,
6675 CurFPFeatureOverrides(), NumParams);
6676 } else {
6677 TheCall =
6678 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6679 CurFPFeatureOverrides(), NumParams, UsesADL);
6680 }
6681
6682 if (!Context.isDependenceAllowed()) {
6683 // Forget about the nulled arguments since typo correction
6684 // do not handle them well.
6685 TheCall->shrinkNumArgs(Args.size());
6686 // C cannot always handle TypoExpr nodes in builtin calls and direct
6687 // function calls as their argument checking don't necessarily handle
6688 // dependent types properly, so make sure any TypoExprs have been
6689 // dealt with.
6690 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6691 if (!Result.isUsable()) return ExprError();
6692 CallExpr *TheOldCall = TheCall;
6693 TheCall = dyn_cast<CallExpr>(Result.get());
6694 bool CorrectedTypos = TheCall != TheOldCall;
6695 if (!TheCall) return Result;
6696 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6697
6698 // A new call expression node was created if some typos were corrected.
6699 // However it may not have been constructed with enough storage. In this
6700 // case, rebuild the node with enough storage. The waste of space is
6701 // immaterial since this only happens when some typos were corrected.
6702 if (CorrectedTypos && Args.size() < NumParams) {
6703 if (Config)
6704 TheCall = CUDAKernelCallExpr::Create(
6705 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6706 RParenLoc, CurFPFeatureOverrides(), NumParams);
6707 else
6708 TheCall =
6709 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6710 CurFPFeatureOverrides(), NumParams, UsesADL);
6711 }
6712 // We can now handle the nulled arguments for the default arguments.
6713 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6714 }
6715
6716 // Bail out early if calling a builtin with custom type checking.
6717 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6718 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6719
6720 if (getLangOpts().CUDA) {
6721 if (Config) {
6722 // CUDA: Kernel calls must be to global functions
6723 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6724 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6725 << FDecl << Fn->getSourceRange());
6726
6727 // CUDA: Kernel function must have 'void' return type
6728 if (!FuncT->getReturnType()->isVoidType() &&
6729 !FuncT->getReturnType()->getAs<AutoType>() &&
6730 !FuncT->getReturnType()->isInstantiationDependentType())
6731 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6732 << Fn->getType() << Fn->getSourceRange());
6733 } else {
6734 // CUDA: Calls to global functions must be configured
6735 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6736 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6737 << FDecl << Fn->getSourceRange());
6738 }
6739 }
6740
6741 // Check for a valid return type
6742 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6743 FDecl))
6744 return ExprError();
6745
6746 // We know the result type of the call, set it.
6747 TheCall->setType(FuncT->getCallResultType(Context));
6748 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6749
6750 if (Proto) {
6751 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6752 IsExecConfig))
6753 return ExprError();
6754 } else {
6755 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6756
6757 if (FDecl) {
6758 // Check if we have too few/too many template arguments, based
6759 // on our knowledge of the function definition.
6760 const FunctionDecl *Def = nullptr;
6761 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6762 Proto = Def->getType()->getAs<FunctionProtoType>();
6763 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6764 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6765 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6766 }
6767
6768 // If the function we're calling isn't a function prototype, but we have
6769 // a function prototype from a prior declaratiom, use that prototype.
6770 if (!FDecl->hasPrototype())
6771 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6772 }
6773
6774 // Promote the arguments (C99 6.5.2.2p6).
6775 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6776 Expr *Arg = Args[i];
6777
6778 if (Proto && i < Proto->getNumParams()) {
6779 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6780 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6781 ExprResult ArgE =
6782 PerformCopyInitialization(Entity, SourceLocation(), Arg);
6783 if (ArgE.isInvalid())
6784 return true;
6785
6786 Arg = ArgE.getAs<Expr>();
6787
6788 } else {
6789 ExprResult ArgE = DefaultArgumentPromotion(Arg);
6790
6791 if (ArgE.isInvalid())
6792 return true;
6793
6794 Arg = ArgE.getAs<Expr>();
6795 }
6796
6797 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6798 diag::err_call_incomplete_argument, Arg))
6799 return ExprError();
6800
6801 TheCall->setArg(i, Arg);
6802 }
6803 }
6804
6805 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6806 if (!Method->isStatic())
6807 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6808 << Fn->getSourceRange());
6809
6810 // Check for sentinels
6811 if (NDecl)
6812 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6813
6814 // Warn for unions passing across security boundary (CMSE).
6815 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6816 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6817 if (const auto *RT =
6818 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6819 if (RT->getDecl()->isOrContainsUnion())
6820 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6821 << 0 << i;
6822 }
6823 }
6824 }
6825
6826 // Do special checking on direct calls to functions.
6827 if (FDecl) {
6828 if (CheckFunctionCall(FDecl, TheCall, Proto))
6829 return ExprError();
6830
6831 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6832
6833 if (BuiltinID)
6834 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6835 } else if (NDecl) {
6836 if (CheckPointerCall(NDecl, TheCall, Proto))
6837 return ExprError();
6838 } else {
6839 if (CheckOtherCall(TheCall, Proto))
6840 return ExprError();
6841 }
6842
6843 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6844 }
6845
6846 ExprResult
ActOnCompoundLiteral(SourceLocation LParenLoc,ParsedType Ty,SourceLocation RParenLoc,Expr * InitExpr)6847 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6848 SourceLocation RParenLoc, Expr *InitExpr) {
6849 assert(Ty && "ActOnCompoundLiteral(): missing type");
6850 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6851
6852 TypeSourceInfo *TInfo;
6853 QualType literalType = GetTypeFromParser(Ty, &TInfo);
6854 if (!TInfo)
6855 TInfo = Context.getTrivialTypeSourceInfo(literalType);
6856
6857 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6858 }
6859
6860 ExprResult
BuildCompoundLiteralExpr(SourceLocation LParenLoc,TypeSourceInfo * TInfo,SourceLocation RParenLoc,Expr * LiteralExpr)6861 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6862 SourceLocation RParenLoc, Expr *LiteralExpr) {
6863 QualType literalType = TInfo->getType();
6864
6865 if (literalType->isArrayType()) {
6866 if (RequireCompleteSizedType(
6867 LParenLoc, Context.getBaseElementType(literalType),
6868 diag::err_array_incomplete_or_sizeless_type,
6869 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6870 return ExprError();
6871 if (literalType->isVariableArrayType()) {
6872 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
6873 diag::err_variable_object_no_init)) {
6874 return ExprError();
6875 }
6876 }
6877 } else if (!literalType->isDependentType() &&
6878 RequireCompleteType(LParenLoc, literalType,
6879 diag::err_typecheck_decl_incomplete_type,
6880 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6881 return ExprError();
6882
6883 InitializedEntity Entity
6884 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6885 InitializationKind Kind
6886 = InitializationKind::CreateCStyleCast(LParenLoc,
6887 SourceRange(LParenLoc, RParenLoc),
6888 /*InitList=*/true);
6889 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6890 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6891 &literalType);
6892 if (Result.isInvalid())
6893 return ExprError();
6894 LiteralExpr = Result.get();
6895
6896 bool isFileScope = !CurContext->isFunctionOrMethod();
6897
6898 // In C, compound literals are l-values for some reason.
6899 // For GCC compatibility, in C++, file-scope array compound literals with
6900 // constant initializers are also l-values, and compound literals are
6901 // otherwise prvalues.
6902 //
6903 // (GCC also treats C++ list-initialized file-scope array prvalues with
6904 // constant initializers as l-values, but that's non-conforming, so we don't
6905 // follow it there.)
6906 //
6907 // FIXME: It would be better to handle the lvalue cases as materializing and
6908 // lifetime-extending a temporary object, but our materialized temporaries
6909 // representation only supports lifetime extension from a variable, not "out
6910 // of thin air".
6911 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6912 // is bound to the result of applying array-to-pointer decay to the compound
6913 // literal.
6914 // FIXME: GCC supports compound literals of reference type, which should
6915 // obviously have a value kind derived from the kind of reference involved.
6916 ExprValueKind VK =
6917 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6918 ? VK_RValue
6919 : VK_LValue;
6920
6921 if (isFileScope)
6922 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6923 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6924 Expr *Init = ILE->getInit(i);
6925 ILE->setInit(i, ConstantExpr::Create(Context, Init));
6926 }
6927
6928 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6929 VK, LiteralExpr, isFileScope);
6930 if (isFileScope) {
6931 if (!LiteralExpr->isTypeDependent() &&
6932 !LiteralExpr->isValueDependent() &&
6933 !literalType->isDependentType()) // C99 6.5.2.5p3
6934 if (CheckForConstantInitializer(LiteralExpr, literalType))
6935 return ExprError();
6936 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6937 literalType.getAddressSpace() != LangAS::Default) {
6938 // Embedded-C extensions to C99 6.5.2.5:
6939 // "If the compound literal occurs inside the body of a function, the
6940 // type name shall not be qualified by an address-space qualifier."
6941 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6942 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6943 return ExprError();
6944 }
6945
6946 if (!isFileScope && !getLangOpts().CPlusPlus) {
6947 // Compound literals that have automatic storage duration are destroyed at
6948 // the end of the scope in C; in C++, they're just temporaries.
6949
6950 // Emit diagnostics if it is or contains a C union type that is non-trivial
6951 // to destruct.
6952 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6953 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6954 NTCUC_CompoundLiteral, NTCUK_Destruct);
6955
6956 // Diagnose jumps that enter or exit the lifetime of the compound literal.
6957 if (literalType.isDestructedType()) {
6958 Cleanup.setExprNeedsCleanups(true);
6959 ExprCleanupObjects.push_back(E);
6960 getCurFunction()->setHasBranchProtectedScope();
6961 }
6962 }
6963
6964 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6965 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6966 checkNonTrivialCUnionInInitializer(E->getInitializer(),
6967 E->getInitializer()->getExprLoc());
6968
6969 return MaybeBindToTemporary(E);
6970 }
6971
6972 ExprResult
ActOnInitList(SourceLocation LBraceLoc,MultiExprArg InitArgList,SourceLocation RBraceLoc)6973 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6974 SourceLocation RBraceLoc) {
6975 // Only produce each kind of designated initialization diagnostic once.
6976 SourceLocation FirstDesignator;
6977 bool DiagnosedArrayDesignator = false;
6978 bool DiagnosedNestedDesignator = false;
6979 bool DiagnosedMixedDesignator = false;
6980
6981 // Check that any designated initializers are syntactically valid in the
6982 // current language mode.
6983 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6984 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6985 if (FirstDesignator.isInvalid())
6986 FirstDesignator = DIE->getBeginLoc();
6987
6988 if (!getLangOpts().CPlusPlus)
6989 break;
6990
6991 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6992 DiagnosedNestedDesignator = true;
6993 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6994 << DIE->getDesignatorsSourceRange();
6995 }
6996
6997 for (auto &Desig : DIE->designators()) {
6998 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6999 DiagnosedArrayDesignator = true;
7000 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7001 << Desig.getSourceRange();
7002 }
7003 }
7004
7005 if (!DiagnosedMixedDesignator &&
7006 !isa<DesignatedInitExpr>(InitArgList[0])) {
7007 DiagnosedMixedDesignator = true;
7008 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7009 << DIE->getSourceRange();
7010 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7011 << InitArgList[0]->getSourceRange();
7012 }
7013 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7014 isa<DesignatedInitExpr>(InitArgList[0])) {
7015 DiagnosedMixedDesignator = true;
7016 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7017 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7018 << DIE->getSourceRange();
7019 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7020 << InitArgList[I]->getSourceRange();
7021 }
7022 }
7023
7024 if (FirstDesignator.isValid()) {
7025 // Only diagnose designated initiaization as a C++20 extension if we didn't
7026 // already diagnose use of (non-C++20) C99 designator syntax.
7027 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7028 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7029 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7030 ? diag::warn_cxx17_compat_designated_init
7031 : diag::ext_cxx_designated_init);
7032 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7033 Diag(FirstDesignator, diag::ext_designated_init);
7034 }
7035 }
7036
7037 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7038 }
7039
7040 ExprResult
BuildInitList(SourceLocation LBraceLoc,MultiExprArg InitArgList,SourceLocation RBraceLoc)7041 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
7042 SourceLocation RBraceLoc) {
7043 // Semantic analysis for initializers is done by ActOnDeclarator() and
7044 // CheckInitializer() - it requires knowledge of the object being initialized.
7045
7046 // Immediately handle non-overload placeholders. Overloads can be
7047 // resolved contextually, but everything else here can't.
7048 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7049 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7050 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7051
7052 // Ignore failures; dropping the entire initializer list because
7053 // of one failure would be terrible for indexing/etc.
7054 if (result.isInvalid()) continue;
7055
7056 InitArgList[I] = result.get();
7057 }
7058 }
7059
7060 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7061 RBraceLoc);
7062 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7063 return E;
7064 }
7065
7066 /// Do an explicit extend of the given block pointer if we're in ARC.
maybeExtendBlockObject(ExprResult & E)7067 void Sema::maybeExtendBlockObject(ExprResult &E) {
7068 assert(E.get()->getType()->isBlockPointerType());
7069 assert(E.get()->isRValue());
7070
7071 // Only do this in an r-value context.
7072 if (!getLangOpts().ObjCAutoRefCount) return;
7073
7074 E = ImplicitCastExpr::Create(
7075 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7076 /*base path*/ nullptr, VK_RValue, FPOptionsOverride());
7077 Cleanup.setExprNeedsCleanups(true);
7078 }
7079
7080 /// Prepare a conversion of the given expression to an ObjC object
7081 /// pointer type.
PrepareCastToObjCObjectPointer(ExprResult & E)7082 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7083 QualType type = E.get()->getType();
7084 if (type->isObjCObjectPointerType()) {
7085 return CK_BitCast;
7086 } else if (type->isBlockPointerType()) {
7087 maybeExtendBlockObject(E);
7088 return CK_BlockPointerToObjCPointerCast;
7089 } else {
7090 assert(type->isPointerType());
7091 return CK_CPointerToObjCPointerCast;
7092 }
7093 }
7094
7095 /// Prepares for a scalar cast, performing all the necessary stages
7096 /// except the final cast and returning the kind required.
PrepareScalarCast(ExprResult & Src,QualType DestTy)7097 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7098 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7099 // Also, callers should have filtered out the invalid cases with
7100 // pointers. Everything else should be possible.
7101
7102 QualType SrcTy = Src.get()->getType();
7103 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7104 return CK_NoOp;
7105
7106 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7107 case Type::STK_MemberPointer:
7108 llvm_unreachable("member pointer type in C");
7109
7110 case Type::STK_CPointer:
7111 case Type::STK_BlockPointer:
7112 case Type::STK_ObjCObjectPointer:
7113 switch (DestTy->getScalarTypeKind()) {
7114 case Type::STK_CPointer: {
7115 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7116 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7117 if (SrcAS != DestAS)
7118 return CK_AddressSpaceConversion;
7119 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7120 return CK_NoOp;
7121 return CK_BitCast;
7122 }
7123 case Type::STK_BlockPointer:
7124 return (SrcKind == Type::STK_BlockPointer
7125 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7126 case Type::STK_ObjCObjectPointer:
7127 if (SrcKind == Type::STK_ObjCObjectPointer)
7128 return CK_BitCast;
7129 if (SrcKind == Type::STK_CPointer)
7130 return CK_CPointerToObjCPointerCast;
7131 maybeExtendBlockObject(Src);
7132 return CK_BlockPointerToObjCPointerCast;
7133 case Type::STK_Bool:
7134 return CK_PointerToBoolean;
7135 case Type::STK_Integral:
7136 return CK_PointerToIntegral;
7137 case Type::STK_Floating:
7138 case Type::STK_FloatingComplex:
7139 case Type::STK_IntegralComplex:
7140 case Type::STK_MemberPointer:
7141 case Type::STK_FixedPoint:
7142 llvm_unreachable("illegal cast from pointer");
7143 }
7144 llvm_unreachable("Should have returned before this");
7145
7146 case Type::STK_FixedPoint:
7147 switch (DestTy->getScalarTypeKind()) {
7148 case Type::STK_FixedPoint:
7149 return CK_FixedPointCast;
7150 case Type::STK_Bool:
7151 return CK_FixedPointToBoolean;
7152 case Type::STK_Integral:
7153 return CK_FixedPointToIntegral;
7154 case Type::STK_Floating:
7155 return CK_FixedPointToFloating;
7156 case Type::STK_IntegralComplex:
7157 case Type::STK_FloatingComplex:
7158 Diag(Src.get()->getExprLoc(),
7159 diag::err_unimplemented_conversion_with_fixed_point_type)
7160 << DestTy;
7161 return CK_IntegralCast;
7162 case Type::STK_CPointer:
7163 case Type::STK_ObjCObjectPointer:
7164 case Type::STK_BlockPointer:
7165 case Type::STK_MemberPointer:
7166 llvm_unreachable("illegal cast to pointer type");
7167 }
7168 llvm_unreachable("Should have returned before this");
7169
7170 case Type::STK_Bool: // casting from bool is like casting from an integer
7171 case Type::STK_Integral:
7172 switch (DestTy->getScalarTypeKind()) {
7173 case Type::STK_CPointer:
7174 case Type::STK_ObjCObjectPointer:
7175 case Type::STK_BlockPointer:
7176 if (Src.get()->isNullPointerConstant(Context,
7177 Expr::NPC_ValueDependentIsNull))
7178 return CK_NullToPointer;
7179 return CK_IntegralToPointer;
7180 case Type::STK_Bool:
7181 return CK_IntegralToBoolean;
7182 case Type::STK_Integral:
7183 return CK_IntegralCast;
7184 case Type::STK_Floating:
7185 return CK_IntegralToFloating;
7186 case Type::STK_IntegralComplex:
7187 Src = ImpCastExprToType(Src.get(),
7188 DestTy->castAs<ComplexType>()->getElementType(),
7189 CK_IntegralCast);
7190 return CK_IntegralRealToComplex;
7191 case Type::STK_FloatingComplex:
7192 Src = ImpCastExprToType(Src.get(),
7193 DestTy->castAs<ComplexType>()->getElementType(),
7194 CK_IntegralToFloating);
7195 return CK_FloatingRealToComplex;
7196 case Type::STK_MemberPointer:
7197 llvm_unreachable("member pointer type in C");
7198 case Type::STK_FixedPoint:
7199 return CK_IntegralToFixedPoint;
7200 }
7201 llvm_unreachable("Should have returned before this");
7202
7203 case Type::STK_Floating:
7204 switch (DestTy->getScalarTypeKind()) {
7205 case Type::STK_Floating:
7206 return CK_FloatingCast;
7207 case Type::STK_Bool:
7208 return CK_FloatingToBoolean;
7209 case Type::STK_Integral:
7210 return CK_FloatingToIntegral;
7211 case Type::STK_FloatingComplex:
7212 Src = ImpCastExprToType(Src.get(),
7213 DestTy->castAs<ComplexType>()->getElementType(),
7214 CK_FloatingCast);
7215 return CK_FloatingRealToComplex;
7216 case Type::STK_IntegralComplex:
7217 Src = ImpCastExprToType(Src.get(),
7218 DestTy->castAs<ComplexType>()->getElementType(),
7219 CK_FloatingToIntegral);
7220 return CK_IntegralRealToComplex;
7221 case Type::STK_CPointer:
7222 case Type::STK_ObjCObjectPointer:
7223 case Type::STK_BlockPointer:
7224 llvm_unreachable("valid float->pointer cast?");
7225 case Type::STK_MemberPointer:
7226 llvm_unreachable("member pointer type in C");
7227 case Type::STK_FixedPoint:
7228 return CK_FloatingToFixedPoint;
7229 }
7230 llvm_unreachable("Should have returned before this");
7231
7232 case Type::STK_FloatingComplex:
7233 switch (DestTy->getScalarTypeKind()) {
7234 case Type::STK_FloatingComplex:
7235 return CK_FloatingComplexCast;
7236 case Type::STK_IntegralComplex:
7237 return CK_FloatingComplexToIntegralComplex;
7238 case Type::STK_Floating: {
7239 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7240 if (Context.hasSameType(ET, DestTy))
7241 return CK_FloatingComplexToReal;
7242 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7243 return CK_FloatingCast;
7244 }
7245 case Type::STK_Bool:
7246 return CK_FloatingComplexToBoolean;
7247 case Type::STK_Integral:
7248 Src = ImpCastExprToType(Src.get(),
7249 SrcTy->castAs<ComplexType>()->getElementType(),
7250 CK_FloatingComplexToReal);
7251 return CK_FloatingToIntegral;
7252 case Type::STK_CPointer:
7253 case Type::STK_ObjCObjectPointer:
7254 case Type::STK_BlockPointer:
7255 llvm_unreachable("valid complex float->pointer cast?");
7256 case Type::STK_MemberPointer:
7257 llvm_unreachable("member pointer type in C");
7258 case Type::STK_FixedPoint:
7259 Diag(Src.get()->getExprLoc(),
7260 diag::err_unimplemented_conversion_with_fixed_point_type)
7261 << SrcTy;
7262 return CK_IntegralCast;
7263 }
7264 llvm_unreachable("Should have returned before this");
7265
7266 case Type::STK_IntegralComplex:
7267 switch (DestTy->getScalarTypeKind()) {
7268 case Type::STK_FloatingComplex:
7269 return CK_IntegralComplexToFloatingComplex;
7270 case Type::STK_IntegralComplex:
7271 return CK_IntegralComplexCast;
7272 case Type::STK_Integral: {
7273 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7274 if (Context.hasSameType(ET, DestTy))
7275 return CK_IntegralComplexToReal;
7276 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7277 return CK_IntegralCast;
7278 }
7279 case Type::STK_Bool:
7280 return CK_IntegralComplexToBoolean;
7281 case Type::STK_Floating:
7282 Src = ImpCastExprToType(Src.get(),
7283 SrcTy->castAs<ComplexType>()->getElementType(),
7284 CK_IntegralComplexToReal);
7285 return CK_IntegralToFloating;
7286 case Type::STK_CPointer:
7287 case Type::STK_ObjCObjectPointer:
7288 case Type::STK_BlockPointer:
7289 llvm_unreachable("valid complex int->pointer cast?");
7290 case Type::STK_MemberPointer:
7291 llvm_unreachable("member pointer type in C");
7292 case Type::STK_FixedPoint:
7293 Diag(Src.get()->getExprLoc(),
7294 diag::err_unimplemented_conversion_with_fixed_point_type)
7295 << SrcTy;
7296 return CK_IntegralCast;
7297 }
7298 llvm_unreachable("Should have returned before this");
7299 }
7300
7301 llvm_unreachable("Unhandled scalar cast");
7302 }
7303
breakDownVectorType(QualType type,uint64_t & len,QualType & eltType)7304 static bool breakDownVectorType(QualType type, uint64_t &len,
7305 QualType &eltType) {
7306 // Vectors are simple.
7307 if (const VectorType *vecType = type->getAs<VectorType>()) {
7308 len = vecType->getNumElements();
7309 eltType = vecType->getElementType();
7310 assert(eltType->isScalarType());
7311 return true;
7312 }
7313
7314 // We allow lax conversion to and from non-vector types, but only if
7315 // they're real types (i.e. non-complex, non-pointer scalar types).
7316 if (!type->isRealType()) return false;
7317
7318 len = 1;
7319 eltType = type;
7320 return true;
7321 }
7322
7323 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7324 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7325 /// allowed?
7326 ///
7327 /// This will also return false if the two given types do not make sense from
7328 /// the perspective of SVE bitcasts.
isValidSveBitcast(QualType srcTy,QualType destTy)7329 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7330 assert(srcTy->isVectorType() || destTy->isVectorType());
7331
7332 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7333 if (!FirstType->isSizelessBuiltinType())
7334 return false;
7335
7336 const auto *VecTy = SecondType->getAs<VectorType>();
7337 return VecTy &&
7338 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7339 };
7340
7341 return ValidScalableConversion(srcTy, destTy) ||
7342 ValidScalableConversion(destTy, srcTy);
7343 }
7344
7345 /// Are the two types matrix types and do they have the same dimensions i.e.
7346 /// do they have the same number of rows and the same number of columns?
areMatrixTypesOfTheSameDimension(QualType srcTy,QualType destTy)7347 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
7348 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7349 return false;
7350
7351 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7352 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7353
7354 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7355 matSrcType->getNumColumns() == matDestType->getNumColumns();
7356 }
7357
areVectorTypesSameSize(QualType SrcTy,QualType DestTy)7358 bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7359 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7360
7361 uint64_t SrcLen, DestLen;
7362 QualType SrcEltTy, DestEltTy;
7363 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7364 return false;
7365 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7366 return false;
7367
7368 // ASTContext::getTypeSize will return the size rounded up to a
7369 // power of 2, so instead of using that, we need to use the raw
7370 // element size multiplied by the element count.
7371 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7372 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7373
7374 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7375 }
7376
7377 /// Are the two types lax-compatible vector types? That is, given
7378 /// that one of them is a vector, do they have equal storage sizes,
7379 /// where the storage size is the number of elements times the element
7380 /// size?
7381 ///
7382 /// This will also return false if either of the types is neither a
7383 /// vector nor a real type.
areLaxCompatibleVectorTypes(QualType srcTy,QualType destTy)7384 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7385 assert(destTy->isVectorType() || srcTy->isVectorType());
7386
7387 // Disallow lax conversions between scalars and ExtVectors (these
7388 // conversions are allowed for other vector types because common headers
7389 // depend on them). Most scalar OP ExtVector cases are handled by the
7390 // splat path anyway, which does what we want (convert, not bitcast).
7391 // What this rules out for ExtVectors is crazy things like char4*float.
7392 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7393 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7394
7395 return areVectorTypesSameSize(srcTy, destTy);
7396 }
7397
7398 /// Is this a legal conversion between two types, one of which is
7399 /// known to be a vector type?
isLaxVectorConversion(QualType srcTy,QualType destTy)7400 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7401 assert(destTy->isVectorType() || srcTy->isVectorType());
7402
7403 switch (Context.getLangOpts().getLaxVectorConversions()) {
7404 case LangOptions::LaxVectorConversionKind::None:
7405 return false;
7406
7407 case LangOptions::LaxVectorConversionKind::Integer:
7408 if (!srcTy->isIntegralOrEnumerationType()) {
7409 auto *Vec = srcTy->getAs<VectorType>();
7410 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7411 return false;
7412 }
7413 if (!destTy->isIntegralOrEnumerationType()) {
7414 auto *Vec = destTy->getAs<VectorType>();
7415 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7416 return false;
7417 }
7418 // OK, integer (vector) -> integer (vector) bitcast.
7419 break;
7420
7421 case LangOptions::LaxVectorConversionKind::All:
7422 break;
7423 }
7424
7425 return areLaxCompatibleVectorTypes(srcTy, destTy);
7426 }
7427
CheckMatrixCast(SourceRange R,QualType DestTy,QualType SrcTy,CastKind & Kind)7428 bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7429 CastKind &Kind) {
7430 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7431 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7432 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7433 << DestTy << SrcTy << R;
7434 }
7435 } else if (SrcTy->isMatrixType()) {
7436 return Diag(R.getBegin(),
7437 diag::err_invalid_conversion_between_matrix_and_type)
7438 << SrcTy << DestTy << R;
7439 } else if (DestTy->isMatrixType()) {
7440 return Diag(R.getBegin(),
7441 diag::err_invalid_conversion_between_matrix_and_type)
7442 << DestTy << SrcTy << R;
7443 }
7444
7445 Kind = CK_MatrixCast;
7446 return false;
7447 }
7448
CheckVectorCast(SourceRange R,QualType VectorTy,QualType Ty,CastKind & Kind)7449 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7450 CastKind &Kind) {
7451 assert(VectorTy->isVectorType() && "Not a vector type!");
7452
7453 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7454 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7455 return Diag(R.getBegin(),
7456 Ty->isVectorType() ?
7457 diag::err_invalid_conversion_between_vectors :
7458 diag::err_invalid_conversion_between_vector_and_integer)
7459 << VectorTy << Ty << R;
7460 } else
7461 return Diag(R.getBegin(),
7462 diag::err_invalid_conversion_between_vector_and_scalar)
7463 << VectorTy << Ty << R;
7464
7465 Kind = CK_BitCast;
7466 return false;
7467 }
7468
prepareVectorSplat(QualType VectorTy,Expr * SplattedExpr)7469 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7470 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7471
7472 if (DestElemTy == SplattedExpr->getType())
7473 return SplattedExpr;
7474
7475 assert(DestElemTy->isFloatingType() ||
7476 DestElemTy->isIntegralOrEnumerationType());
7477
7478 CastKind CK;
7479 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7480 // OpenCL requires that we convert `true` boolean expressions to -1, but
7481 // only when splatting vectors.
7482 if (DestElemTy->isFloatingType()) {
7483 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7484 // in two steps: boolean to signed integral, then to floating.
7485 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7486 CK_BooleanToSignedIntegral);
7487 SplattedExpr = CastExprRes.get();
7488 CK = CK_IntegralToFloating;
7489 } else {
7490 CK = CK_BooleanToSignedIntegral;
7491 }
7492 } else {
7493 ExprResult CastExprRes = SplattedExpr;
7494 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7495 if (CastExprRes.isInvalid())
7496 return ExprError();
7497 SplattedExpr = CastExprRes.get();
7498 }
7499 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7500 }
7501
CheckExtVectorCast(SourceRange R,QualType DestTy,Expr * CastExpr,CastKind & Kind)7502 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7503 Expr *CastExpr, CastKind &Kind) {
7504 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7505
7506 QualType SrcTy = CastExpr->getType();
7507
7508 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7509 // an ExtVectorType.
7510 // In OpenCL, casts between vectors of different types are not allowed.
7511 // (See OpenCL 6.2).
7512 if (SrcTy->isVectorType()) {
7513 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7514 (getLangOpts().OpenCL &&
7515 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7516 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7517 << DestTy << SrcTy << R;
7518 return ExprError();
7519 }
7520 Kind = CK_BitCast;
7521 return CastExpr;
7522 }
7523
7524 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7525 // conversion will take place first from scalar to elt type, and then
7526 // splat from elt type to vector.
7527 if (SrcTy->isPointerType())
7528 return Diag(R.getBegin(),
7529 diag::err_invalid_conversion_between_vector_and_scalar)
7530 << DestTy << SrcTy << R;
7531
7532 Kind = CK_VectorSplat;
7533 return prepareVectorSplat(DestTy, CastExpr);
7534 }
7535
7536 ExprResult
ActOnCastExpr(Scope * S,SourceLocation LParenLoc,Declarator & D,ParsedType & Ty,SourceLocation RParenLoc,Expr * CastExpr)7537 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7538 Declarator &D, ParsedType &Ty,
7539 SourceLocation RParenLoc, Expr *CastExpr) {
7540 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7541 "ActOnCastExpr(): missing type or expr");
7542
7543 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7544 if (D.isInvalidType())
7545 return ExprError();
7546
7547 if (getLangOpts().CPlusPlus) {
7548 // Check that there are no default arguments (C++ only).
7549 CheckExtraCXXDefaultArguments(D);
7550 } else {
7551 // Make sure any TypoExprs have been dealt with.
7552 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7553 if (!Res.isUsable())
7554 return ExprError();
7555 CastExpr = Res.get();
7556 }
7557
7558 checkUnusedDeclAttributes(D);
7559
7560 QualType castType = castTInfo->getType();
7561 Ty = CreateParsedType(castType, castTInfo);
7562
7563 bool isVectorLiteral = false;
7564
7565 // Check for an altivec or OpenCL literal,
7566 // i.e. all the elements are integer constants.
7567 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7568 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7569 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7570 && castType->isVectorType() && (PE || PLE)) {
7571 if (PLE && PLE->getNumExprs() == 0) {
7572 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7573 return ExprError();
7574 }
7575 if (PE || PLE->getNumExprs() == 1) {
7576 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7577 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7578 isVectorLiteral = true;
7579 }
7580 else
7581 isVectorLiteral = true;
7582 }
7583
7584 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7585 // then handle it as such.
7586 if (isVectorLiteral)
7587 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7588
7589 // If the Expr being casted is a ParenListExpr, handle it specially.
7590 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7591 // sequence of BinOp comma operators.
7592 if (isa<ParenListExpr>(CastExpr)) {
7593 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7594 if (Result.isInvalid()) return ExprError();
7595 CastExpr = Result.get();
7596 }
7597
7598 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7599 !getSourceManager().isInSystemMacro(LParenLoc))
7600 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7601
7602 CheckTollFreeBridgeCast(castType, CastExpr);
7603
7604 CheckObjCBridgeRelatedCast(castType, CastExpr);
7605
7606 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7607
7608 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7609 }
7610
BuildVectorLiteral(SourceLocation LParenLoc,SourceLocation RParenLoc,Expr * E,TypeSourceInfo * TInfo)7611 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7612 SourceLocation RParenLoc, Expr *E,
7613 TypeSourceInfo *TInfo) {
7614 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7615 "Expected paren or paren list expression");
7616
7617 Expr **exprs;
7618 unsigned numExprs;
7619 Expr *subExpr;
7620 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7621 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7622 LiteralLParenLoc = PE->getLParenLoc();
7623 LiteralRParenLoc = PE->getRParenLoc();
7624 exprs = PE->getExprs();
7625 numExprs = PE->getNumExprs();
7626 } else { // isa<ParenExpr> by assertion at function entrance
7627 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7628 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7629 subExpr = cast<ParenExpr>(E)->getSubExpr();
7630 exprs = &subExpr;
7631 numExprs = 1;
7632 }
7633
7634 QualType Ty = TInfo->getType();
7635 assert(Ty->isVectorType() && "Expected vector type");
7636
7637 SmallVector<Expr *, 8> initExprs;
7638 const VectorType *VTy = Ty->castAs<VectorType>();
7639 unsigned numElems = VTy->getNumElements();
7640
7641 // '(...)' form of vector initialization in AltiVec: the number of
7642 // initializers must be one or must match the size of the vector.
7643 // If a single value is specified in the initializer then it will be
7644 // replicated to all the components of the vector
7645 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7646 // The number of initializers must be one or must match the size of the
7647 // vector. If a single value is specified in the initializer then it will
7648 // be replicated to all the components of the vector
7649 if (numExprs == 1) {
7650 QualType ElemTy = VTy->getElementType();
7651 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7652 if (Literal.isInvalid())
7653 return ExprError();
7654 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7655 PrepareScalarCast(Literal, ElemTy));
7656 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7657 }
7658 else if (numExprs < numElems) {
7659 Diag(E->getExprLoc(),
7660 diag::err_incorrect_number_of_vector_initializers);
7661 return ExprError();
7662 }
7663 else
7664 initExprs.append(exprs, exprs + numExprs);
7665 }
7666 else {
7667 // For OpenCL, when the number of initializers is a single value,
7668 // it will be replicated to all components of the vector.
7669 if (getLangOpts().OpenCL &&
7670 VTy->getVectorKind() == VectorType::GenericVector &&
7671 numExprs == 1) {
7672 QualType ElemTy = VTy->getElementType();
7673 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7674 if (Literal.isInvalid())
7675 return ExprError();
7676 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7677 PrepareScalarCast(Literal, ElemTy));
7678 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7679 }
7680
7681 initExprs.append(exprs, exprs + numExprs);
7682 }
7683 // FIXME: This means that pretty-printing the final AST will produce curly
7684 // braces instead of the original commas.
7685 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7686 initExprs, LiteralRParenLoc);
7687 initE->setType(Ty);
7688 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7689 }
7690
7691 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7692 /// the ParenListExpr into a sequence of comma binary operators.
7693 ExprResult
MaybeConvertParenListExprToParenExpr(Scope * S,Expr * OrigExpr)7694 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7695 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7696 if (!E)
7697 return OrigExpr;
7698
7699 ExprResult Result(E->getExpr(0));
7700
7701 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7702 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7703 E->getExpr(i));
7704
7705 if (Result.isInvalid()) return ExprError();
7706
7707 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7708 }
7709
ActOnParenListExpr(SourceLocation L,SourceLocation R,MultiExprArg Val)7710 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7711 SourceLocation R,
7712 MultiExprArg Val) {
7713 return ParenListExpr::Create(Context, L, Val, R);
7714 }
7715
7716 /// Emit a specialized diagnostic when one expression is a null pointer
7717 /// constant and the other is not a pointer. Returns true if a diagnostic is
7718 /// emitted.
DiagnoseConditionalForNull(Expr * LHSExpr,Expr * RHSExpr,SourceLocation QuestionLoc)7719 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7720 SourceLocation QuestionLoc) {
7721 Expr *NullExpr = LHSExpr;
7722 Expr *NonPointerExpr = RHSExpr;
7723 Expr::NullPointerConstantKind NullKind =
7724 NullExpr->isNullPointerConstant(Context,
7725 Expr::NPC_ValueDependentIsNotNull);
7726
7727 if (NullKind == Expr::NPCK_NotNull) {
7728 NullExpr = RHSExpr;
7729 NonPointerExpr = LHSExpr;
7730 NullKind =
7731 NullExpr->isNullPointerConstant(Context,
7732 Expr::NPC_ValueDependentIsNotNull);
7733 }
7734
7735 if (NullKind == Expr::NPCK_NotNull)
7736 return false;
7737
7738 if (NullKind == Expr::NPCK_ZeroExpression)
7739 return false;
7740
7741 if (NullKind == Expr::NPCK_ZeroLiteral) {
7742 // In this case, check to make sure that we got here from a "NULL"
7743 // string in the source code.
7744 NullExpr = NullExpr->IgnoreParenImpCasts();
7745 SourceLocation loc = NullExpr->getExprLoc();
7746 if (!findMacroSpelling(loc, "NULL"))
7747 return false;
7748 }
7749
7750 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7751 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7752 << NonPointerExpr->getType() << DiagType
7753 << NonPointerExpr->getSourceRange();
7754 return true;
7755 }
7756
7757 /// Return false if the condition expression is valid, true otherwise.
checkCondition(Sema & S,Expr * Cond,SourceLocation QuestionLoc)7758 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7759 QualType CondTy = Cond->getType();
7760
7761 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7762 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7763 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7764 << CondTy << Cond->getSourceRange();
7765 return true;
7766 }
7767
7768 // C99 6.5.15p2
7769 if (CondTy->isScalarType()) return false;
7770
7771 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7772 << CondTy << Cond->getSourceRange();
7773 return true;
7774 }
7775
7776 /// Handle when one or both operands are void type.
checkConditionalVoidType(Sema & S,ExprResult & LHS,ExprResult & RHS)7777 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7778 ExprResult &RHS) {
7779 Expr *LHSExpr = LHS.get();
7780 Expr *RHSExpr = RHS.get();
7781
7782 if (!LHSExpr->getType()->isVoidType())
7783 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7784 << RHSExpr->getSourceRange();
7785 if (!RHSExpr->getType()->isVoidType())
7786 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7787 << LHSExpr->getSourceRange();
7788 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7789 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7790 return S.Context.VoidTy;
7791 }
7792
7793 /// Return false if the NullExpr can be promoted to PointerTy,
7794 /// true otherwise.
checkConditionalNullPointer(Sema & S,ExprResult & NullExpr,QualType PointerTy)7795 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7796 QualType PointerTy) {
7797 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7798 !NullExpr.get()->isNullPointerConstant(S.Context,
7799 Expr::NPC_ValueDependentIsNull))
7800 return true;
7801
7802 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7803 return false;
7804 }
7805
7806 /// Checks compatibility between two pointers and return the resulting
7807 /// type.
checkConditionalPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)7808 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7809 ExprResult &RHS,
7810 SourceLocation Loc) {
7811 QualType LHSTy = LHS.get()->getType();
7812 QualType RHSTy = RHS.get()->getType();
7813
7814 if (S.Context.hasSameType(LHSTy, RHSTy)) {
7815 // Two identical pointers types are always compatible.
7816 return LHSTy;
7817 }
7818
7819 QualType lhptee, rhptee;
7820
7821 // Get the pointee types.
7822 bool IsBlockPointer = false;
7823 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7824 lhptee = LHSBTy->getPointeeType();
7825 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7826 IsBlockPointer = true;
7827 } else {
7828 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7829 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7830 }
7831
7832 // C99 6.5.15p6: If both operands are pointers to compatible types or to
7833 // differently qualified versions of compatible types, the result type is
7834 // a pointer to an appropriately qualified version of the composite
7835 // type.
7836
7837 // Only CVR-qualifiers exist in the standard, and the differently-qualified
7838 // clause doesn't make sense for our extensions. E.g. address space 2 should
7839 // be incompatible with address space 3: they may live on different devices or
7840 // anything.
7841 Qualifiers lhQual = lhptee.getQualifiers();
7842 Qualifiers rhQual = rhptee.getQualifiers();
7843
7844 LangAS ResultAddrSpace = LangAS::Default;
7845 LangAS LAddrSpace = lhQual.getAddressSpace();
7846 LangAS RAddrSpace = rhQual.getAddressSpace();
7847
7848 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7849 // spaces is disallowed.
7850 if (lhQual.isAddressSpaceSupersetOf(rhQual))
7851 ResultAddrSpace = LAddrSpace;
7852 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7853 ResultAddrSpace = RAddrSpace;
7854 else {
7855 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7856 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7857 << RHS.get()->getSourceRange();
7858 return QualType();
7859 }
7860
7861 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7862 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7863 lhQual.removeCVRQualifiers();
7864 rhQual.removeCVRQualifiers();
7865
7866 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7867 // (C99 6.7.3) for address spaces. We assume that the check should behave in
7868 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7869 // qual types are compatible iff
7870 // * corresponded types are compatible
7871 // * CVR qualifiers are equal
7872 // * address spaces are equal
7873 // Thus for conditional operator we merge CVR and address space unqualified
7874 // pointees and if there is a composite type we return a pointer to it with
7875 // merged qualifiers.
7876 LHSCastKind =
7877 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7878 RHSCastKind =
7879 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7880 lhQual.removeAddressSpace();
7881 rhQual.removeAddressSpace();
7882
7883 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7884 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7885
7886 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7887
7888 if (CompositeTy.isNull()) {
7889 // In this situation, we assume void* type. No especially good
7890 // reason, but this is what gcc does, and we do have to pick
7891 // to get a consistent AST.
7892 QualType incompatTy;
7893 incompatTy = S.Context.getPointerType(
7894 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7895 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7896 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7897
7898 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7899 // for casts between types with incompatible address space qualifiers.
7900 // For the following code the compiler produces casts between global and
7901 // local address spaces of the corresponded innermost pointees:
7902 // local int *global *a;
7903 // global int *global *b;
7904 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7905 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7906 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7907 << RHS.get()->getSourceRange();
7908
7909 return incompatTy;
7910 }
7911
7912 // The pointer types are compatible.
7913 // In case of OpenCL ResultTy should have the address space qualifier
7914 // which is a superset of address spaces of both the 2nd and the 3rd
7915 // operands of the conditional operator.
7916 QualType ResultTy = [&, ResultAddrSpace]() {
7917 if (S.getLangOpts().OpenCL) {
7918 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7919 CompositeQuals.setAddressSpace(ResultAddrSpace);
7920 return S.Context
7921 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7922 .withCVRQualifiers(MergedCVRQual);
7923 }
7924 return CompositeTy.withCVRQualifiers(MergedCVRQual);
7925 }();
7926 if (IsBlockPointer)
7927 ResultTy = S.Context.getBlockPointerType(ResultTy);
7928 else
7929 ResultTy = S.Context.getPointerType(ResultTy);
7930
7931 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7932 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7933 return ResultTy;
7934 }
7935
7936 /// Return the resulting type when the operands are both block pointers.
checkConditionalBlockPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)7937 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7938 ExprResult &LHS,
7939 ExprResult &RHS,
7940 SourceLocation Loc) {
7941 QualType LHSTy = LHS.get()->getType();
7942 QualType RHSTy = RHS.get()->getType();
7943
7944 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7945 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7946 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7947 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7948 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7949 return destType;
7950 }
7951 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7952 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7953 << RHS.get()->getSourceRange();
7954 return QualType();
7955 }
7956
7957 // We have 2 block pointer types.
7958 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7959 }
7960
7961 /// Return the resulting type when the operands are both pointers.
7962 static QualType
checkConditionalObjectPointersCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)7963 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7964 ExprResult &RHS,
7965 SourceLocation Loc) {
7966 // get the pointer types
7967 QualType LHSTy = LHS.get()->getType();
7968 QualType RHSTy = RHS.get()->getType();
7969
7970 // get the "pointed to" types
7971 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7972 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7973
7974 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7975 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7976 // Figure out necessary qualifiers (C99 6.5.15p6)
7977 QualType destPointee
7978 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7979 QualType destType = S.Context.getPointerType(destPointee);
7980 // Add qualifiers if necessary.
7981 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7982 // Promote to void*.
7983 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7984 return destType;
7985 }
7986 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7987 QualType destPointee
7988 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7989 QualType destType = S.Context.getPointerType(destPointee);
7990 // Add qualifiers if necessary.
7991 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7992 // Promote to void*.
7993 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7994 return destType;
7995 }
7996
7997 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7998 }
7999
8000 /// Return false if the first expression is not an integer and the second
8001 /// expression is not a pointer, true otherwise.
checkPointerIntegerMismatch(Sema & S,ExprResult & Int,Expr * PointerExpr,SourceLocation Loc,bool IsIntFirstExpr)8002 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
8003 Expr* PointerExpr, SourceLocation Loc,
8004 bool IsIntFirstExpr) {
8005 if (!PointerExpr->getType()->isPointerType() ||
8006 !Int.get()->getType()->isIntegerType())
8007 return false;
8008
8009 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8010 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8011
8012 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8013 << Expr1->getType() << Expr2->getType()
8014 << Expr1->getSourceRange() << Expr2->getSourceRange();
8015 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8016 CK_IntegralToPointer);
8017 return true;
8018 }
8019
8020 /// Simple conversion between integer and floating point types.
8021 ///
8022 /// Used when handling the OpenCL conditional operator where the
8023 /// condition is a vector while the other operands are scalar.
8024 ///
8025 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8026 /// types are either integer or floating type. Between the two
8027 /// operands, the type with the higher rank is defined as the "result
8028 /// type". The other operand needs to be promoted to the same type. No
8029 /// other type promotion is allowed. We cannot use
8030 /// UsualArithmeticConversions() for this purpose, since it always
8031 /// promotes promotable types.
OpenCLArithmeticConversions(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)8032 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8033 ExprResult &RHS,
8034 SourceLocation QuestionLoc) {
8035 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
8036 if (LHS.isInvalid())
8037 return QualType();
8038 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8039 if (RHS.isInvalid())
8040 return QualType();
8041
8042 // For conversion purposes, we ignore any qualifiers.
8043 // For example, "const float" and "float" are equivalent.
8044 QualType LHSType =
8045 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
8046 QualType RHSType =
8047 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
8048
8049 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8050 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8051 << LHSType << LHS.get()->getSourceRange();
8052 return QualType();
8053 }
8054
8055 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8056 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8057 << RHSType << RHS.get()->getSourceRange();
8058 return QualType();
8059 }
8060
8061 // If both types are identical, no conversion is needed.
8062 if (LHSType == RHSType)
8063 return LHSType;
8064
8065 // Now handle "real" floating types (i.e. float, double, long double).
8066 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8067 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8068 /*IsCompAssign = */ false);
8069
8070 // Finally, we have two differing integer types.
8071 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8072 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8073 }
8074
8075 /// Convert scalar operands to a vector that matches the
8076 /// condition in length.
8077 ///
8078 /// Used when handling the OpenCL conditional operator where the
8079 /// condition is a vector while the other operands are scalar.
8080 ///
8081 /// We first compute the "result type" for the scalar operands
8082 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8083 /// into a vector of that type where the length matches the condition
8084 /// vector type. s6.11.6 requires that the element types of the result
8085 /// and the condition must have the same number of bits.
8086 static QualType
OpenCLConvertScalarsToVectors(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType CondTy,SourceLocation QuestionLoc)8087 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
8088 QualType CondTy, SourceLocation QuestionLoc) {
8089 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8090 if (ResTy.isNull()) return QualType();
8091
8092 const VectorType *CV = CondTy->getAs<VectorType>();
8093 assert(CV);
8094
8095 // Determine the vector result type
8096 unsigned NumElements = CV->getNumElements();
8097 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8098
8099 // Ensure that all types have the same number of bits
8100 if (S.Context.getTypeSize(CV->getElementType())
8101 != S.Context.getTypeSize(ResTy)) {
8102 // Since VectorTy is created internally, it does not pretty print
8103 // with an OpenCL name. Instead, we just print a description.
8104 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8105 SmallString<64> Str;
8106 llvm::raw_svector_ostream OS(Str);
8107 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8108 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8109 << CondTy << OS.str();
8110 return QualType();
8111 }
8112
8113 // Convert operands to the vector result type
8114 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8115 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8116
8117 return VectorTy;
8118 }
8119
8120 /// Return false if this is a valid OpenCL condition vector
checkOpenCLConditionVector(Sema & S,Expr * Cond,SourceLocation QuestionLoc)8121 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8122 SourceLocation QuestionLoc) {
8123 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8124 // integral type.
8125 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8126 assert(CondTy);
8127 QualType EleTy = CondTy->getElementType();
8128 if (EleTy->isIntegerType()) return false;
8129
8130 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8131 << Cond->getType() << Cond->getSourceRange();
8132 return true;
8133 }
8134
8135 /// Return false if the vector condition type and the vector
8136 /// result type are compatible.
8137 ///
8138 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8139 /// number of elements, and their element types have the same number
8140 /// of bits.
checkVectorResult(Sema & S,QualType CondTy,QualType VecResTy,SourceLocation QuestionLoc)8141 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8142 SourceLocation QuestionLoc) {
8143 const VectorType *CV = CondTy->getAs<VectorType>();
8144 const VectorType *RV = VecResTy->getAs<VectorType>();
8145 assert(CV && RV);
8146
8147 if (CV->getNumElements() != RV->getNumElements()) {
8148 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8149 << CondTy << VecResTy;
8150 return true;
8151 }
8152
8153 QualType CVE = CV->getElementType();
8154 QualType RVE = RV->getElementType();
8155
8156 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8157 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8158 << CondTy << VecResTy;
8159 return true;
8160 }
8161
8162 return false;
8163 }
8164
8165 /// Return the resulting type for the conditional operator in
8166 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
8167 /// s6.3.i) when the condition is a vector type.
8168 static QualType
OpenCLCheckVectorConditional(Sema & S,ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)8169 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8170 ExprResult &LHS, ExprResult &RHS,
8171 SourceLocation QuestionLoc) {
8172 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8173 if (Cond.isInvalid())
8174 return QualType();
8175 QualType CondTy = Cond.get()->getType();
8176
8177 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8178 return QualType();
8179
8180 // If either operand is a vector then find the vector type of the
8181 // result as specified in OpenCL v1.1 s6.3.i.
8182 if (LHS.get()->getType()->isVectorType() ||
8183 RHS.get()->getType()->isVectorType()) {
8184 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8185 /*isCompAssign*/false,
8186 /*AllowBothBool*/true,
8187 /*AllowBoolConversions*/false);
8188 if (VecResTy.isNull()) return QualType();
8189 // The result type must match the condition type as specified in
8190 // OpenCL v1.1 s6.11.6.
8191 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8192 return QualType();
8193 return VecResTy;
8194 }
8195
8196 // Both operands are scalar.
8197 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8198 }
8199
8200 /// Return true if the Expr is block type
checkBlockType(Sema & S,const Expr * E)8201 static bool checkBlockType(Sema &S, const Expr *E) {
8202 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8203 QualType Ty = CE->getCallee()->getType();
8204 if (Ty->isBlockPointerType()) {
8205 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8206 return true;
8207 }
8208 }
8209 return false;
8210 }
8211
8212 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8213 /// In that case, LHS = cond.
8214 /// C99 6.5.15
CheckConditionalOperands(ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation QuestionLoc)8215 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8216 ExprResult &RHS, ExprValueKind &VK,
8217 ExprObjectKind &OK,
8218 SourceLocation QuestionLoc) {
8219
8220 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8221 if (!LHSResult.isUsable()) return QualType();
8222 LHS = LHSResult;
8223
8224 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8225 if (!RHSResult.isUsable()) return QualType();
8226 RHS = RHSResult;
8227
8228 // C++ is sufficiently different to merit its own checker.
8229 if (getLangOpts().CPlusPlus)
8230 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8231
8232 VK = VK_RValue;
8233 OK = OK_Ordinary;
8234
8235 if (Context.isDependenceAllowed() &&
8236 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8237 RHS.get()->isTypeDependent())) {
8238 assert(!getLangOpts().CPlusPlus);
8239 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8240 RHS.get()->containsErrors()) &&
8241 "should only occur in error-recovery path.");
8242 return Context.DependentTy;
8243 }
8244
8245 // The OpenCL operator with a vector condition is sufficiently
8246 // different to merit its own checker.
8247 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8248 Cond.get()->getType()->isExtVectorType())
8249 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8250
8251 // First, check the condition.
8252 Cond = UsualUnaryConversions(Cond.get());
8253 if (Cond.isInvalid())
8254 return QualType();
8255 if (checkCondition(*this, Cond.get(), QuestionLoc))
8256 return QualType();
8257
8258 // Now check the two expressions.
8259 if (LHS.get()->getType()->isVectorType() ||
8260 RHS.get()->getType()->isVectorType())
8261 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8262 /*AllowBothBool*/true,
8263 /*AllowBoolConversions*/false);
8264
8265 QualType ResTy =
8266 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8267 if (LHS.isInvalid() || RHS.isInvalid())
8268 return QualType();
8269
8270 QualType LHSTy = LHS.get()->getType();
8271 QualType RHSTy = RHS.get()->getType();
8272
8273 // Diagnose attempts to convert between __float128 and long double where
8274 // such conversions currently can't be handled.
8275 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8276 Diag(QuestionLoc,
8277 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8278 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8279 return QualType();
8280 }
8281
8282 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8283 // selection operator (?:).
8284 if (getLangOpts().OpenCL &&
8285 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8286 return QualType();
8287 }
8288
8289 // If both operands have arithmetic type, do the usual arithmetic conversions
8290 // to find a common type: C99 6.5.15p3,5.
8291 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8292 // Disallow invalid arithmetic conversions, such as those between ExtInts of
8293 // different sizes, or between ExtInts and other types.
8294 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8295 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8296 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8297 << RHS.get()->getSourceRange();
8298 return QualType();
8299 }
8300
8301 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8302 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8303
8304 return ResTy;
8305 }
8306
8307 // And if they're both bfloat (which isn't arithmetic), that's fine too.
8308 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8309 return LHSTy;
8310 }
8311
8312 // If both operands are the same structure or union type, the result is that
8313 // type.
8314 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8315 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8316 if (LHSRT->getDecl() == RHSRT->getDecl())
8317 // "If both the operands have structure or union type, the result has
8318 // that type." This implies that CV qualifiers are dropped.
8319 return LHSTy.getUnqualifiedType();
8320 // FIXME: Type of conditional expression must be complete in C mode.
8321 }
8322
8323 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8324 // The following || allows only one side to be void (a GCC-ism).
8325 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8326 return checkConditionalVoidType(*this, LHS, RHS);
8327 }
8328
8329 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8330 // the type of the other operand."
8331 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8332 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8333
8334 // All objective-c pointer type analysis is done here.
8335 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8336 QuestionLoc);
8337 if (LHS.isInvalid() || RHS.isInvalid())
8338 return QualType();
8339 if (!compositeType.isNull())
8340 return compositeType;
8341
8342
8343 // Handle block pointer types.
8344 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8345 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8346 QuestionLoc);
8347
8348 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8349 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8350 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8351 QuestionLoc);
8352
8353 // GCC compatibility: soften pointer/integer mismatch. Note that
8354 // null pointers have been filtered out by this point.
8355 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8356 /*IsIntFirstExpr=*/true))
8357 return RHSTy;
8358 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8359 /*IsIntFirstExpr=*/false))
8360 return LHSTy;
8361
8362 // Allow ?: operations in which both operands have the same
8363 // built-in sizeless type.
8364 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8365 return LHSTy;
8366
8367 // Emit a better diagnostic if one of the expressions is a null pointer
8368 // constant and the other is not a pointer type. In this case, the user most
8369 // likely forgot to take the address of the other expression.
8370 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8371 return QualType();
8372
8373 // Otherwise, the operands are not compatible.
8374 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8375 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8376 << RHS.get()->getSourceRange();
8377 return QualType();
8378 }
8379
8380 /// FindCompositeObjCPointerType - Helper method to find composite type of
8381 /// two objective-c pointer types of the two input expressions.
FindCompositeObjCPointerType(ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)8382 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8383 SourceLocation QuestionLoc) {
8384 QualType LHSTy = LHS.get()->getType();
8385 QualType RHSTy = RHS.get()->getType();
8386
8387 // Handle things like Class and struct objc_class*. Here we case the result
8388 // to the pseudo-builtin, because that will be implicitly cast back to the
8389 // redefinition type if an attempt is made to access its fields.
8390 if (LHSTy->isObjCClassType() &&
8391 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8392 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8393 return LHSTy;
8394 }
8395 if (RHSTy->isObjCClassType() &&
8396 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8397 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8398 return RHSTy;
8399 }
8400 // And the same for struct objc_object* / id
8401 if (LHSTy->isObjCIdType() &&
8402 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8403 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8404 return LHSTy;
8405 }
8406 if (RHSTy->isObjCIdType() &&
8407 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8408 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8409 return RHSTy;
8410 }
8411 // And the same for struct objc_selector* / SEL
8412 if (Context.isObjCSelType(LHSTy) &&
8413 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8414 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8415 return LHSTy;
8416 }
8417 if (Context.isObjCSelType(RHSTy) &&
8418 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8419 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8420 return RHSTy;
8421 }
8422 // Check constraints for Objective-C object pointers types.
8423 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8424
8425 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8426 // Two identical object pointer types are always compatible.
8427 return LHSTy;
8428 }
8429 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8430 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8431 QualType compositeType = LHSTy;
8432
8433 // If both operands are interfaces and either operand can be
8434 // assigned to the other, use that type as the composite
8435 // type. This allows
8436 // xxx ? (A*) a : (B*) b
8437 // where B is a subclass of A.
8438 //
8439 // Additionally, as for assignment, if either type is 'id'
8440 // allow silent coercion. Finally, if the types are
8441 // incompatible then make sure to use 'id' as the composite
8442 // type so the result is acceptable for sending messages to.
8443
8444 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8445 // It could return the composite type.
8446 if (!(compositeType =
8447 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8448 // Nothing more to do.
8449 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8450 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8451 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8452 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8453 } else if ((LHSOPT->isObjCQualifiedIdType() ||
8454 RHSOPT->isObjCQualifiedIdType()) &&
8455 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8456 true)) {
8457 // Need to handle "id<xx>" explicitly.
8458 // GCC allows qualified id and any Objective-C type to devolve to
8459 // id. Currently localizing to here until clear this should be
8460 // part of ObjCQualifiedIdTypesAreCompatible.
8461 compositeType = Context.getObjCIdType();
8462 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8463 compositeType = Context.getObjCIdType();
8464 } else {
8465 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8466 << LHSTy << RHSTy
8467 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8468 QualType incompatTy = Context.getObjCIdType();
8469 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8470 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8471 return incompatTy;
8472 }
8473 // The object pointer types are compatible.
8474 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8475 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8476 return compositeType;
8477 }
8478 // Check Objective-C object pointer types and 'void *'
8479 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8480 if (getLangOpts().ObjCAutoRefCount) {
8481 // ARC forbids the implicit conversion of object pointers to 'void *',
8482 // so these types are not compatible.
8483 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8484 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8485 LHS = RHS = true;
8486 return QualType();
8487 }
8488 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8489 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8490 QualType destPointee
8491 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8492 QualType destType = Context.getPointerType(destPointee);
8493 // Add qualifiers if necessary.
8494 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8495 // Promote to void*.
8496 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8497 return destType;
8498 }
8499 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8500 if (getLangOpts().ObjCAutoRefCount) {
8501 // ARC forbids the implicit conversion of object pointers to 'void *',
8502 // so these types are not compatible.
8503 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8504 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8505 LHS = RHS = true;
8506 return QualType();
8507 }
8508 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8509 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8510 QualType destPointee
8511 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8512 QualType destType = Context.getPointerType(destPointee);
8513 // Add qualifiers if necessary.
8514 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8515 // Promote to void*.
8516 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8517 return destType;
8518 }
8519 return QualType();
8520 }
8521
8522 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8523 /// ParenRange in parentheses.
SuggestParentheses(Sema & Self,SourceLocation Loc,const PartialDiagnostic & Note,SourceRange ParenRange)8524 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8525 const PartialDiagnostic &Note,
8526 SourceRange ParenRange) {
8527 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8528 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8529 EndLoc.isValid()) {
8530 Self.Diag(Loc, Note)
8531 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8532 << FixItHint::CreateInsertion(EndLoc, ")");
8533 } else {
8534 // We can't display the parentheses, so just show the bare note.
8535 Self.Diag(Loc, Note) << ParenRange;
8536 }
8537 }
8538
IsArithmeticOp(BinaryOperatorKind Opc)8539 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8540 return BinaryOperator::isAdditiveOp(Opc) ||
8541 BinaryOperator::isMultiplicativeOp(Opc) ||
8542 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8543 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8544 // not any of the logical operators. Bitwise-xor is commonly used as a
8545 // logical-xor because there is no logical-xor operator. The logical
8546 // operators, including uses of xor, have a high false positive rate for
8547 // precedence warnings.
8548 }
8549
8550 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8551 /// expression, either using a built-in or overloaded operator,
8552 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8553 /// expression.
IsArithmeticBinaryExpr(Expr * E,BinaryOperatorKind * Opcode,Expr ** RHSExprs)8554 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8555 Expr **RHSExprs) {
8556 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8557 E = E->IgnoreImpCasts();
8558 E = E->IgnoreConversionOperatorSingleStep();
8559 E = E->IgnoreImpCasts();
8560 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8561 E = MTE->getSubExpr();
8562 E = E->IgnoreImpCasts();
8563 }
8564
8565 // Built-in binary operator.
8566 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8567 if (IsArithmeticOp(OP->getOpcode())) {
8568 *Opcode = OP->getOpcode();
8569 *RHSExprs = OP->getRHS();
8570 return true;
8571 }
8572 }
8573
8574 // Overloaded operator.
8575 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8576 if (Call->getNumArgs() != 2)
8577 return false;
8578
8579 // Make sure this is really a binary operator that is safe to pass into
8580 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8581 OverloadedOperatorKind OO = Call->getOperator();
8582 if (OO < OO_Plus || OO > OO_Arrow ||
8583 OO == OO_PlusPlus || OO == OO_MinusMinus)
8584 return false;
8585
8586 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8587 if (IsArithmeticOp(OpKind)) {
8588 *Opcode = OpKind;
8589 *RHSExprs = Call->getArg(1);
8590 return true;
8591 }
8592 }
8593
8594 return false;
8595 }
8596
8597 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8598 /// or is a logical expression such as (x==y) which has int type, but is
8599 /// commonly interpreted as boolean.
ExprLooksBoolean(Expr * E)8600 static bool ExprLooksBoolean(Expr *E) {
8601 E = E->IgnoreParenImpCasts();
8602
8603 if (E->getType()->isBooleanType())
8604 return true;
8605 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8606 return OP->isComparisonOp() || OP->isLogicalOp();
8607 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8608 return OP->getOpcode() == UO_LNot;
8609 if (E->getType()->isPointerType())
8610 return true;
8611 // FIXME: What about overloaded operator calls returning "unspecified boolean
8612 // type"s (commonly pointer-to-members)?
8613
8614 return false;
8615 }
8616
8617 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8618 /// and binary operator are mixed in a way that suggests the programmer assumed
8619 /// the conditional operator has higher precedence, for example:
8620 /// "int x = a + someBinaryCondition ? 1 : 2".
DiagnoseConditionalPrecedence(Sema & Self,SourceLocation OpLoc,Expr * Condition,Expr * LHSExpr,Expr * RHSExpr)8621 static void DiagnoseConditionalPrecedence(Sema &Self,
8622 SourceLocation OpLoc,
8623 Expr *Condition,
8624 Expr *LHSExpr,
8625 Expr *RHSExpr) {
8626 BinaryOperatorKind CondOpcode;
8627 Expr *CondRHS;
8628
8629 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8630 return;
8631 if (!ExprLooksBoolean(CondRHS))
8632 return;
8633
8634 // The condition is an arithmetic binary expression, with a right-
8635 // hand side that looks boolean, so warn.
8636
8637 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8638 ? diag::warn_precedence_bitwise_conditional
8639 : diag::warn_precedence_conditional;
8640
8641 Self.Diag(OpLoc, DiagID)
8642 << Condition->getSourceRange()
8643 << BinaryOperator::getOpcodeStr(CondOpcode);
8644
8645 SuggestParentheses(
8646 Self, OpLoc,
8647 Self.PDiag(diag::note_precedence_silence)
8648 << BinaryOperator::getOpcodeStr(CondOpcode),
8649 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8650
8651 SuggestParentheses(Self, OpLoc,
8652 Self.PDiag(diag::note_precedence_conditional_first),
8653 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8654 }
8655
8656 /// Compute the nullability of a conditional expression.
computeConditionalNullability(QualType ResTy,bool IsBin,QualType LHSTy,QualType RHSTy,ASTContext & Ctx)8657 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8658 QualType LHSTy, QualType RHSTy,
8659 ASTContext &Ctx) {
8660 if (!ResTy->isAnyPointerType())
8661 return ResTy;
8662
8663 auto GetNullability = [&Ctx](QualType Ty) {
8664 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8665 if (Kind) {
8666 // For our purposes, treat _Nullable_result as _Nullable.
8667 if (*Kind == NullabilityKind::NullableResult)
8668 return NullabilityKind::Nullable;
8669 return *Kind;
8670 }
8671 return NullabilityKind::Unspecified;
8672 };
8673
8674 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8675 NullabilityKind MergedKind;
8676
8677 // Compute nullability of a binary conditional expression.
8678 if (IsBin) {
8679 if (LHSKind == NullabilityKind::NonNull)
8680 MergedKind = NullabilityKind::NonNull;
8681 else
8682 MergedKind = RHSKind;
8683 // Compute nullability of a normal conditional expression.
8684 } else {
8685 if (LHSKind == NullabilityKind::Nullable ||
8686 RHSKind == NullabilityKind::Nullable)
8687 MergedKind = NullabilityKind::Nullable;
8688 else if (LHSKind == NullabilityKind::NonNull)
8689 MergedKind = RHSKind;
8690 else if (RHSKind == NullabilityKind::NonNull)
8691 MergedKind = LHSKind;
8692 else
8693 MergedKind = NullabilityKind::Unspecified;
8694 }
8695
8696 // Return if ResTy already has the correct nullability.
8697 if (GetNullability(ResTy) == MergedKind)
8698 return ResTy;
8699
8700 // Strip all nullability from ResTy.
8701 while (ResTy->getNullability(Ctx))
8702 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8703
8704 // Create a new AttributedType with the new nullability kind.
8705 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8706 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8707 }
8708
8709 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
8710 /// in the case of a the GNU conditional expr extension.
ActOnConditionalOp(SourceLocation QuestionLoc,SourceLocation ColonLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr)8711 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8712 SourceLocation ColonLoc,
8713 Expr *CondExpr, Expr *LHSExpr,
8714 Expr *RHSExpr) {
8715 if (!Context.isDependenceAllowed()) {
8716 // C cannot handle TypoExpr nodes in the condition because it
8717 // doesn't handle dependent types properly, so make sure any TypoExprs have
8718 // been dealt with before checking the operands.
8719 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8720 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8721 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8722
8723 if (!CondResult.isUsable())
8724 return ExprError();
8725
8726 if (LHSExpr) {
8727 if (!LHSResult.isUsable())
8728 return ExprError();
8729 }
8730
8731 if (!RHSResult.isUsable())
8732 return ExprError();
8733
8734 CondExpr = CondResult.get();
8735 LHSExpr = LHSResult.get();
8736 RHSExpr = RHSResult.get();
8737 }
8738
8739 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8740 // was the condition.
8741 OpaqueValueExpr *opaqueValue = nullptr;
8742 Expr *commonExpr = nullptr;
8743 if (!LHSExpr) {
8744 commonExpr = CondExpr;
8745 // Lower out placeholder types first. This is important so that we don't
8746 // try to capture a placeholder. This happens in few cases in C++; such
8747 // as Objective-C++'s dictionary subscripting syntax.
8748 if (commonExpr->hasPlaceholderType()) {
8749 ExprResult result = CheckPlaceholderExpr(commonExpr);
8750 if (!result.isUsable()) return ExprError();
8751 commonExpr = result.get();
8752 }
8753 // We usually want to apply unary conversions *before* saving, except
8754 // in the special case of a C++ l-value conditional.
8755 if (!(getLangOpts().CPlusPlus
8756 && !commonExpr->isTypeDependent()
8757 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8758 && commonExpr->isGLValue()
8759 && commonExpr->isOrdinaryOrBitFieldObject()
8760 && RHSExpr->isOrdinaryOrBitFieldObject()
8761 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8762 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8763 if (commonRes.isInvalid())
8764 return ExprError();
8765 commonExpr = commonRes.get();
8766 }
8767
8768 // If the common expression is a class or array prvalue, materialize it
8769 // so that we can safely refer to it multiple times.
8770 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8771 commonExpr->getType()->isArrayType())) {
8772 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8773 if (MatExpr.isInvalid())
8774 return ExprError();
8775 commonExpr = MatExpr.get();
8776 }
8777
8778 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8779 commonExpr->getType(),
8780 commonExpr->getValueKind(),
8781 commonExpr->getObjectKind(),
8782 commonExpr);
8783 LHSExpr = CondExpr = opaqueValue;
8784 }
8785
8786 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8787 ExprValueKind VK = VK_RValue;
8788 ExprObjectKind OK = OK_Ordinary;
8789 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8790 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8791 VK, OK, QuestionLoc);
8792 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8793 RHS.isInvalid())
8794 return ExprError();
8795
8796 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8797 RHS.get());
8798
8799 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8800
8801 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8802 Context);
8803
8804 if (!commonExpr)
8805 return new (Context)
8806 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8807 RHS.get(), result, VK, OK);
8808
8809 return new (Context) BinaryConditionalOperator(
8810 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8811 ColonLoc, result, VK, OK);
8812 }
8813
8814 // Check if we have a conversion between incompatible cmse function pointer
8815 // types, that is, a conversion between a function pointer with the
8816 // cmse_nonsecure_call attribute and one without.
IsInvalidCmseNSCallConversion(Sema & S,QualType FromType,QualType ToType)8817 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8818 QualType ToType) {
8819 if (const auto *ToFn =
8820 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8821 if (const auto *FromFn =
8822 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8823 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8824 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8825
8826 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8827 }
8828 }
8829 return false;
8830 }
8831
8832 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8833 // being closely modeled after the C99 spec:-). The odd characteristic of this
8834 // routine is it effectively iqnores the qualifiers on the top level pointee.
8835 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8836 // FIXME: add a couple examples in this comment.
8837 static Sema::AssignConvertType
checkPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)8838 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8839 assert(LHSType.isCanonical() && "LHS not canonicalized!");
8840 assert(RHSType.isCanonical() && "RHS not canonicalized!");
8841
8842 // get the "pointed to" type (ignoring qualifiers at the top level)
8843 const Type *lhptee, *rhptee;
8844 Qualifiers lhq, rhq;
8845 std::tie(lhptee, lhq) =
8846 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8847 std::tie(rhptee, rhq) =
8848 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8849
8850 Sema::AssignConvertType ConvTy = Sema::Compatible;
8851
8852 // C99 6.5.16.1p1: This following citation is common to constraints
8853 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8854 // qualifiers of the type *pointed to* by the right;
8855
8856 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8857 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8858 lhq.compatiblyIncludesObjCLifetime(rhq)) {
8859 // Ignore lifetime for further calculation.
8860 lhq.removeObjCLifetime();
8861 rhq.removeObjCLifetime();
8862 }
8863
8864 if (!lhq.compatiblyIncludes(rhq)) {
8865 // Treat address-space mismatches as fatal.
8866 if (!lhq.isAddressSpaceSupersetOf(rhq))
8867 return Sema::IncompatiblePointerDiscardsQualifiers;
8868
8869 // It's okay to add or remove GC or lifetime qualifiers when converting to
8870 // and from void*.
8871 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8872 .compatiblyIncludes(
8873 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8874 && (lhptee->isVoidType() || rhptee->isVoidType()))
8875 ; // keep old
8876
8877 // Treat lifetime mismatches as fatal.
8878 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8879 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8880
8881 // For GCC/MS compatibility, other qualifier mismatches are treated
8882 // as still compatible in C.
8883 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8884 }
8885
8886 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8887 // incomplete type and the other is a pointer to a qualified or unqualified
8888 // version of void...
8889 if (lhptee->isVoidType()) {
8890 if (rhptee->isIncompleteOrObjectType())
8891 return ConvTy;
8892
8893 // As an extension, we allow cast to/from void* to function pointer.
8894 assert(rhptee->isFunctionType());
8895 return Sema::FunctionVoidPointer;
8896 }
8897
8898 if (rhptee->isVoidType()) {
8899 if (lhptee->isIncompleteOrObjectType())
8900 return ConvTy;
8901
8902 // As an extension, we allow cast to/from void* to function pointer.
8903 assert(lhptee->isFunctionType());
8904 return Sema::FunctionVoidPointer;
8905 }
8906
8907 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8908 // unqualified versions of compatible types, ...
8909 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8910 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8911 // Check if the pointee types are compatible ignoring the sign.
8912 // We explicitly check for char so that we catch "char" vs
8913 // "unsigned char" on systems where "char" is unsigned.
8914 if (lhptee->isCharType())
8915 ltrans = S.Context.UnsignedCharTy;
8916 else if (lhptee->hasSignedIntegerRepresentation())
8917 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8918
8919 if (rhptee->isCharType())
8920 rtrans = S.Context.UnsignedCharTy;
8921 else if (rhptee->hasSignedIntegerRepresentation())
8922 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8923
8924 if (ltrans == rtrans) {
8925 // Types are compatible ignoring the sign. Qualifier incompatibility
8926 // takes priority over sign incompatibility because the sign
8927 // warning can be disabled.
8928 if (ConvTy != Sema::Compatible)
8929 return ConvTy;
8930
8931 return Sema::IncompatiblePointerSign;
8932 }
8933
8934 // If we are a multi-level pointer, it's possible that our issue is simply
8935 // one of qualification - e.g. char ** -> const char ** is not allowed. If
8936 // the eventual target type is the same and the pointers have the same
8937 // level of indirection, this must be the issue.
8938 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8939 do {
8940 std::tie(lhptee, lhq) =
8941 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8942 std::tie(rhptee, rhq) =
8943 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8944
8945 // Inconsistent address spaces at this point is invalid, even if the
8946 // address spaces would be compatible.
8947 // FIXME: This doesn't catch address space mismatches for pointers of
8948 // different nesting levels, like:
8949 // __local int *** a;
8950 // int ** b = a;
8951 // It's not clear how to actually determine when such pointers are
8952 // invalidly incompatible.
8953 if (lhq.getAddressSpace() != rhq.getAddressSpace())
8954 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8955
8956 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8957
8958 if (lhptee == rhptee)
8959 return Sema::IncompatibleNestedPointerQualifiers;
8960 }
8961
8962 // General pointer incompatibility takes priority over qualifiers.
8963 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8964 return Sema::IncompatibleFunctionPointer;
8965 return Sema::IncompatiblePointer;
8966 }
8967 if (!S.getLangOpts().CPlusPlus &&
8968 S.IsFunctionConversion(ltrans, rtrans, ltrans))
8969 return Sema::IncompatibleFunctionPointer;
8970 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8971 return Sema::IncompatibleFunctionPointer;
8972 return ConvTy;
8973 }
8974
8975 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8976 /// block pointer types are compatible or whether a block and normal pointer
8977 /// are compatible. It is more restrict than comparing two function pointer
8978 // types.
8979 static Sema::AssignConvertType
checkBlockPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)8980 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8981 QualType RHSType) {
8982 assert(LHSType.isCanonical() && "LHS not canonicalized!");
8983 assert(RHSType.isCanonical() && "RHS not canonicalized!");
8984
8985 QualType lhptee, rhptee;
8986
8987 // get the "pointed to" type (ignoring qualifiers at the top level)
8988 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8989 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8990
8991 // In C++, the types have to match exactly.
8992 if (S.getLangOpts().CPlusPlus)
8993 return Sema::IncompatibleBlockPointer;
8994
8995 Sema::AssignConvertType ConvTy = Sema::Compatible;
8996
8997 // For blocks we enforce that qualifiers are identical.
8998 Qualifiers LQuals = lhptee.getLocalQualifiers();
8999 Qualifiers RQuals = rhptee.getLocalQualifiers();
9000 if (S.getLangOpts().OpenCL) {
9001 LQuals.removeAddressSpace();
9002 RQuals.removeAddressSpace();
9003 }
9004 if (LQuals != RQuals)
9005 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
9006
9007 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9008 // assignment.
9009 // The current behavior is similar to C++ lambdas. A block might be
9010 // assigned to a variable iff its return type and parameters are compatible
9011 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9012 // an assignment. Presumably it should behave in way that a function pointer
9013 // assignment does in C, so for each parameter and return type:
9014 // * CVR and address space of LHS should be a superset of CVR and address
9015 // space of RHS.
9016 // * unqualified types should be compatible.
9017 if (S.getLangOpts().OpenCL) {
9018 if (!S.Context.typesAreBlockPointerCompatible(
9019 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9020 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9021 return Sema::IncompatibleBlockPointer;
9022 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9023 return Sema::IncompatibleBlockPointer;
9024
9025 return ConvTy;
9026 }
9027
9028 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9029 /// for assignment compatibility.
9030 static Sema::AssignConvertType
checkObjCPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)9031 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
9032 QualType RHSType) {
9033 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9034 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9035
9036 if (LHSType->isObjCBuiltinType()) {
9037 // Class is not compatible with ObjC object pointers.
9038 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9039 !RHSType->isObjCQualifiedClassType())
9040 return Sema::IncompatiblePointer;
9041 return Sema::Compatible;
9042 }
9043 if (RHSType->isObjCBuiltinType()) {
9044 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9045 !LHSType->isObjCQualifiedClassType())
9046 return Sema::IncompatiblePointer;
9047 return Sema::Compatible;
9048 }
9049 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9050 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9051
9052 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9053 // make an exception for id<P>
9054 !LHSType->isObjCQualifiedIdType())
9055 return Sema::CompatiblePointerDiscardsQualifiers;
9056
9057 if (S.Context.typesAreCompatible(LHSType, RHSType))
9058 return Sema::Compatible;
9059 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9060 return Sema::IncompatibleObjCQualifiedId;
9061 return Sema::IncompatiblePointer;
9062 }
9063
9064 Sema::AssignConvertType
CheckAssignmentConstraints(SourceLocation Loc,QualType LHSType,QualType RHSType)9065 Sema::CheckAssignmentConstraints(SourceLocation Loc,
9066 QualType LHSType, QualType RHSType) {
9067 // Fake up an opaque expression. We don't actually care about what
9068 // cast operations are required, so if CheckAssignmentConstraints
9069 // adds casts to this they'll be wasted, but fortunately that doesn't
9070 // usually happen on valid code.
9071 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
9072 ExprResult RHSPtr = &RHSExpr;
9073 CastKind K;
9074
9075 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9076 }
9077
9078 /// This helper function returns true if QT is a vector type that has element
9079 /// type ElementType.
isVector(QualType QT,QualType ElementType)9080 static bool isVector(QualType QT, QualType ElementType) {
9081 if (const VectorType *VT = QT->getAs<VectorType>())
9082 return VT->getElementType().getCanonicalType() == ElementType;
9083 return false;
9084 }
9085
9086 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9087 /// has code to accommodate several GCC extensions when type checking
9088 /// pointers. Here are some objectionable examples that GCC considers warnings:
9089 ///
9090 /// int a, *pint;
9091 /// short *pshort;
9092 /// struct foo *pfoo;
9093 ///
9094 /// pint = pshort; // warning: assignment from incompatible pointer type
9095 /// a = pint; // warning: assignment makes integer from pointer without a cast
9096 /// pint = a; // warning: assignment makes pointer from integer without a cast
9097 /// pint = pfoo; // warning: assignment from incompatible pointer type
9098 ///
9099 /// As a result, the code for dealing with pointers is more complex than the
9100 /// C99 spec dictates.
9101 ///
9102 /// Sets 'Kind' for any result kind except Incompatible.
9103 Sema::AssignConvertType
CheckAssignmentConstraints(QualType LHSType,ExprResult & RHS,CastKind & Kind,bool ConvertRHS)9104 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9105 CastKind &Kind, bool ConvertRHS) {
9106 QualType RHSType = RHS.get()->getType();
9107 QualType OrigLHSType = LHSType;
9108
9109 // Get canonical types. We're not formatting these types, just comparing
9110 // them.
9111 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9112 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9113
9114 // Common case: no conversion required.
9115 if (LHSType == RHSType) {
9116 Kind = CK_NoOp;
9117 return Compatible;
9118 }
9119
9120 // If we have an atomic type, try a non-atomic assignment, then just add an
9121 // atomic qualification step.
9122 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9123 Sema::AssignConvertType result =
9124 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9125 if (result != Compatible)
9126 return result;
9127 if (Kind != CK_NoOp && ConvertRHS)
9128 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9129 Kind = CK_NonAtomicToAtomic;
9130 return Compatible;
9131 }
9132
9133 // If the left-hand side is a reference type, then we are in a
9134 // (rare!) case where we've allowed the use of references in C,
9135 // e.g., as a parameter type in a built-in function. In this case,
9136 // just make sure that the type referenced is compatible with the
9137 // right-hand side type. The caller is responsible for adjusting
9138 // LHSType so that the resulting expression does not have reference
9139 // type.
9140 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9141 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9142 Kind = CK_LValueBitCast;
9143 return Compatible;
9144 }
9145 return Incompatible;
9146 }
9147
9148 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9149 // to the same ExtVector type.
9150 if (LHSType->isExtVectorType()) {
9151 if (RHSType->isExtVectorType())
9152 return Incompatible;
9153 if (RHSType->isArithmeticType()) {
9154 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9155 if (ConvertRHS)
9156 RHS = prepareVectorSplat(LHSType, RHS.get());
9157 Kind = CK_VectorSplat;
9158 return Compatible;
9159 }
9160 }
9161
9162 // Conversions to or from vector type.
9163 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9164 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9165 // Allow assignments of an AltiVec vector type to an equivalent GCC
9166 // vector type and vice versa
9167 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9168 Kind = CK_BitCast;
9169 return Compatible;
9170 }
9171
9172 // If we are allowing lax vector conversions, and LHS and RHS are both
9173 // vectors, the total size only needs to be the same. This is a bitcast;
9174 // no bits are changed but the result type is different.
9175 if (isLaxVectorConversion(RHSType, LHSType)) {
9176 Kind = CK_BitCast;
9177 return IncompatibleVectors;
9178 }
9179 }
9180
9181 // When the RHS comes from another lax conversion (e.g. binops between
9182 // scalars and vectors) the result is canonicalized as a vector. When the
9183 // LHS is also a vector, the lax is allowed by the condition above. Handle
9184 // the case where LHS is a scalar.
9185 if (LHSType->isScalarType()) {
9186 const VectorType *VecType = RHSType->getAs<VectorType>();
9187 if (VecType && VecType->getNumElements() == 1 &&
9188 isLaxVectorConversion(RHSType, LHSType)) {
9189 ExprResult *VecExpr = &RHS;
9190 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9191 Kind = CK_BitCast;
9192 return Compatible;
9193 }
9194 }
9195
9196 // Allow assignments between fixed-length and sizeless SVE vectors.
9197 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9198 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9199 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9200 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9201 Kind = CK_BitCast;
9202 return Compatible;
9203 }
9204
9205 return Incompatible;
9206 }
9207
9208 // Diagnose attempts to convert between __float128 and long double where
9209 // such conversions currently can't be handled.
9210 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9211 return Incompatible;
9212
9213 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9214 // discards the imaginary part.
9215 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9216 !LHSType->getAs<ComplexType>())
9217 return Incompatible;
9218
9219 // Arithmetic conversions.
9220 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9221 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9222 if (ConvertRHS)
9223 Kind = PrepareScalarCast(RHS, LHSType);
9224 return Compatible;
9225 }
9226
9227 // Conversions to normal pointers.
9228 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9229 // U* -> T*
9230 if (isa<PointerType>(RHSType)) {
9231 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9232 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9233 if (AddrSpaceL != AddrSpaceR)
9234 Kind = CK_AddressSpaceConversion;
9235 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9236 Kind = CK_NoOp;
9237 else
9238 Kind = CK_BitCast;
9239 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9240 }
9241
9242 // int -> T*
9243 if (RHSType->isIntegerType()) {
9244 Kind = CK_IntegralToPointer; // FIXME: null?
9245 return IntToPointer;
9246 }
9247
9248 // C pointers are not compatible with ObjC object pointers,
9249 // with two exceptions:
9250 if (isa<ObjCObjectPointerType>(RHSType)) {
9251 // - conversions to void*
9252 if (LHSPointer->getPointeeType()->isVoidType()) {
9253 Kind = CK_BitCast;
9254 return Compatible;
9255 }
9256
9257 // - conversions from 'Class' to the redefinition type
9258 if (RHSType->isObjCClassType() &&
9259 Context.hasSameType(LHSType,
9260 Context.getObjCClassRedefinitionType())) {
9261 Kind = CK_BitCast;
9262 return Compatible;
9263 }
9264
9265 Kind = CK_BitCast;
9266 return IncompatiblePointer;
9267 }
9268
9269 // U^ -> void*
9270 if (RHSType->getAs<BlockPointerType>()) {
9271 if (LHSPointer->getPointeeType()->isVoidType()) {
9272 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9273 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9274 ->getPointeeType()
9275 .getAddressSpace();
9276 Kind =
9277 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9278 return Compatible;
9279 }
9280 }
9281
9282 return Incompatible;
9283 }
9284
9285 // Conversions to block pointers.
9286 if (isa<BlockPointerType>(LHSType)) {
9287 // U^ -> T^
9288 if (RHSType->isBlockPointerType()) {
9289 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9290 ->getPointeeType()
9291 .getAddressSpace();
9292 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9293 ->getPointeeType()
9294 .getAddressSpace();
9295 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9296 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9297 }
9298
9299 // int or null -> T^
9300 if (RHSType->isIntegerType()) {
9301 Kind = CK_IntegralToPointer; // FIXME: null
9302 return IntToBlockPointer;
9303 }
9304
9305 // id -> T^
9306 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9307 Kind = CK_AnyPointerToBlockPointerCast;
9308 return Compatible;
9309 }
9310
9311 // void* -> T^
9312 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9313 if (RHSPT->getPointeeType()->isVoidType()) {
9314 Kind = CK_AnyPointerToBlockPointerCast;
9315 return Compatible;
9316 }
9317
9318 return Incompatible;
9319 }
9320
9321 // Conversions to Objective-C pointers.
9322 if (isa<ObjCObjectPointerType>(LHSType)) {
9323 // A* -> B*
9324 if (RHSType->isObjCObjectPointerType()) {
9325 Kind = CK_BitCast;
9326 Sema::AssignConvertType result =
9327 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9328 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9329 result == Compatible &&
9330 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9331 result = IncompatibleObjCWeakRef;
9332 return result;
9333 }
9334
9335 // int or null -> A*
9336 if (RHSType->isIntegerType()) {
9337 Kind = CK_IntegralToPointer; // FIXME: null
9338 return IntToPointer;
9339 }
9340
9341 // In general, C pointers are not compatible with ObjC object pointers,
9342 // with two exceptions:
9343 if (isa<PointerType>(RHSType)) {
9344 Kind = CK_CPointerToObjCPointerCast;
9345
9346 // - conversions from 'void*'
9347 if (RHSType->isVoidPointerType()) {
9348 return Compatible;
9349 }
9350
9351 // - conversions to 'Class' from its redefinition type
9352 if (LHSType->isObjCClassType() &&
9353 Context.hasSameType(RHSType,
9354 Context.getObjCClassRedefinitionType())) {
9355 return Compatible;
9356 }
9357
9358 return IncompatiblePointer;
9359 }
9360
9361 // Only under strict condition T^ is compatible with an Objective-C pointer.
9362 if (RHSType->isBlockPointerType() &&
9363 LHSType->isBlockCompatibleObjCPointerType(Context)) {
9364 if (ConvertRHS)
9365 maybeExtendBlockObject(RHS);
9366 Kind = CK_BlockPointerToObjCPointerCast;
9367 return Compatible;
9368 }
9369
9370 return Incompatible;
9371 }
9372
9373 // Conversions from pointers that are not covered by the above.
9374 if (isa<PointerType>(RHSType)) {
9375 // T* -> _Bool
9376 if (LHSType == Context.BoolTy) {
9377 Kind = CK_PointerToBoolean;
9378 return Compatible;
9379 }
9380
9381 // T* -> int
9382 if (LHSType->isIntegerType()) {
9383 Kind = CK_PointerToIntegral;
9384 return PointerToInt;
9385 }
9386
9387 return Incompatible;
9388 }
9389
9390 // Conversions from Objective-C pointers that are not covered by the above.
9391 if (isa<ObjCObjectPointerType>(RHSType)) {
9392 // T* -> _Bool
9393 if (LHSType == Context.BoolTy) {
9394 Kind = CK_PointerToBoolean;
9395 return Compatible;
9396 }
9397
9398 // T* -> int
9399 if (LHSType->isIntegerType()) {
9400 Kind = CK_PointerToIntegral;
9401 return PointerToInt;
9402 }
9403
9404 return Incompatible;
9405 }
9406
9407 // struct A -> struct B
9408 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9409 if (Context.typesAreCompatible(LHSType, RHSType)) {
9410 Kind = CK_NoOp;
9411 return Compatible;
9412 }
9413 }
9414
9415 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9416 Kind = CK_IntToOCLSampler;
9417 return Compatible;
9418 }
9419
9420 return Incompatible;
9421 }
9422
9423 /// Constructs a transparent union from an expression that is
9424 /// used to initialize the transparent union.
ConstructTransparentUnion(Sema & S,ASTContext & C,ExprResult & EResult,QualType UnionType,FieldDecl * Field)9425 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9426 ExprResult &EResult, QualType UnionType,
9427 FieldDecl *Field) {
9428 // Build an initializer list that designates the appropriate member
9429 // of the transparent union.
9430 Expr *E = EResult.get();
9431 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9432 E, SourceLocation());
9433 Initializer->setType(UnionType);
9434 Initializer->setInitializedFieldInUnion(Field);
9435
9436 // Build a compound literal constructing a value of the transparent
9437 // union type from this initializer list.
9438 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9439 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9440 VK_RValue, Initializer, false);
9441 }
9442
9443 Sema::AssignConvertType
CheckTransparentUnionArgumentConstraints(QualType ArgType,ExprResult & RHS)9444 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9445 ExprResult &RHS) {
9446 QualType RHSType = RHS.get()->getType();
9447
9448 // If the ArgType is a Union type, we want to handle a potential
9449 // transparent_union GCC extension.
9450 const RecordType *UT = ArgType->getAsUnionType();
9451 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9452 return Incompatible;
9453
9454 // The field to initialize within the transparent union.
9455 RecordDecl *UD = UT->getDecl();
9456 FieldDecl *InitField = nullptr;
9457 // It's compatible if the expression matches any of the fields.
9458 for (auto *it : UD->fields()) {
9459 if (it->getType()->isPointerType()) {
9460 // If the transparent union contains a pointer type, we allow:
9461 // 1) void pointer
9462 // 2) null pointer constant
9463 if (RHSType->isPointerType())
9464 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9465 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9466 InitField = it;
9467 break;
9468 }
9469
9470 if (RHS.get()->isNullPointerConstant(Context,
9471 Expr::NPC_ValueDependentIsNull)) {
9472 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9473 CK_NullToPointer);
9474 InitField = it;
9475 break;
9476 }
9477 }
9478
9479 CastKind Kind;
9480 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9481 == Compatible) {
9482 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9483 InitField = it;
9484 break;
9485 }
9486 }
9487
9488 if (!InitField)
9489 return Incompatible;
9490
9491 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9492 return Compatible;
9493 }
9494
9495 Sema::AssignConvertType
CheckSingleAssignmentConstraints(QualType LHSType,ExprResult & CallerRHS,bool Diagnose,bool DiagnoseCFAudited,bool ConvertRHS)9496 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9497 bool Diagnose,
9498 bool DiagnoseCFAudited,
9499 bool ConvertRHS) {
9500 // We need to be able to tell the caller whether we diagnosed a problem, if
9501 // they ask us to issue diagnostics.
9502 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9503
9504 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9505 // we can't avoid *all* modifications at the moment, so we need some somewhere
9506 // to put the updated value.
9507 ExprResult LocalRHS = CallerRHS;
9508 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9509
9510 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9511 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9512 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9513 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9514 Diag(RHS.get()->getExprLoc(),
9515 diag::warn_noderef_to_dereferenceable_pointer)
9516 << RHS.get()->getSourceRange();
9517 }
9518 }
9519 }
9520
9521 if (getLangOpts().CPlusPlus) {
9522 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9523 // C++ 5.17p3: If the left operand is not of class type, the
9524 // expression is implicitly converted (C++ 4) to the
9525 // cv-unqualified type of the left operand.
9526 QualType RHSType = RHS.get()->getType();
9527 if (Diagnose) {
9528 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9529 AA_Assigning);
9530 } else {
9531 ImplicitConversionSequence ICS =
9532 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9533 /*SuppressUserConversions=*/false,
9534 AllowedExplicit::None,
9535 /*InOverloadResolution=*/false,
9536 /*CStyle=*/false,
9537 /*AllowObjCWritebackConversion=*/false);
9538 if (ICS.isFailure())
9539 return Incompatible;
9540 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9541 ICS, AA_Assigning);
9542 }
9543 if (RHS.isInvalid())
9544 return Incompatible;
9545 Sema::AssignConvertType result = Compatible;
9546 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9547 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9548 result = IncompatibleObjCWeakRef;
9549 return result;
9550 }
9551
9552 // FIXME: Currently, we fall through and treat C++ classes like C
9553 // structures.
9554 // FIXME: We also fall through for atomics; not sure what should
9555 // happen there, though.
9556 } else if (RHS.get()->getType() == Context.OverloadTy) {
9557 // As a set of extensions to C, we support overloading on functions. These
9558 // functions need to be resolved here.
9559 DeclAccessPair DAP;
9560 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9561 RHS.get(), LHSType, /*Complain=*/false, DAP))
9562 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9563 else
9564 return Incompatible;
9565 }
9566
9567 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9568 // a null pointer constant.
9569 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9570 LHSType->isBlockPointerType()) &&
9571 RHS.get()->isNullPointerConstant(Context,
9572 Expr::NPC_ValueDependentIsNull)) {
9573 if (Diagnose || ConvertRHS) {
9574 CastKind Kind;
9575 CXXCastPath Path;
9576 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9577 /*IgnoreBaseAccess=*/false, Diagnose);
9578 if (ConvertRHS)
9579 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9580 }
9581 return Compatible;
9582 }
9583
9584 // OpenCL queue_t type assignment.
9585 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9586 Context, Expr::NPC_ValueDependentIsNull)) {
9587 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9588 return Compatible;
9589 }
9590
9591 // This check seems unnatural, however it is necessary to ensure the proper
9592 // conversion of functions/arrays. If the conversion were done for all
9593 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9594 // expressions that suppress this implicit conversion (&, sizeof).
9595 //
9596 // Suppress this for references: C++ 8.5.3p5.
9597 if (!LHSType->isReferenceType()) {
9598 // FIXME: We potentially allocate here even if ConvertRHS is false.
9599 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9600 if (RHS.isInvalid())
9601 return Incompatible;
9602 }
9603 CastKind Kind;
9604 Sema::AssignConvertType result =
9605 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9606
9607 // C99 6.5.16.1p2: The value of the right operand is converted to the
9608 // type of the assignment expression.
9609 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9610 // so that we can use references in built-in functions even in C.
9611 // The getNonReferenceType() call makes sure that the resulting expression
9612 // does not have reference type.
9613 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9614 QualType Ty = LHSType.getNonLValueExprType(Context);
9615 Expr *E = RHS.get();
9616
9617 // Check for various Objective-C errors. If we are not reporting
9618 // diagnostics and just checking for errors, e.g., during overload
9619 // resolution, return Incompatible to indicate the failure.
9620 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9621 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9622 Diagnose, DiagnoseCFAudited) != ACR_okay) {
9623 if (!Diagnose)
9624 return Incompatible;
9625 }
9626 if (getLangOpts().ObjC &&
9627 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9628 E->getType(), E, Diagnose) ||
9629 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9630 if (!Diagnose)
9631 return Incompatible;
9632 // Replace the expression with a corrected version and continue so we
9633 // can find further errors.
9634 RHS = E;
9635 return Compatible;
9636 }
9637
9638 if (ConvertRHS)
9639 RHS = ImpCastExprToType(E, Ty, Kind);
9640 }
9641
9642 return result;
9643 }
9644
9645 namespace {
9646 /// The original operand to an operator, prior to the application of the usual
9647 /// arithmetic conversions and converting the arguments of a builtin operator
9648 /// candidate.
9649 struct OriginalOperand {
OriginalOperand__anond87cafbf0c11::OriginalOperand9650 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9651 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9652 Op = MTE->getSubExpr();
9653 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9654 Op = BTE->getSubExpr();
9655 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9656 Orig = ICE->getSubExprAsWritten();
9657 Conversion = ICE->getConversionFunction();
9658 }
9659 }
9660
getType__anond87cafbf0c11::OriginalOperand9661 QualType getType() const { return Orig->getType(); }
9662
9663 Expr *Orig;
9664 NamedDecl *Conversion;
9665 };
9666 }
9667
InvalidOperands(SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)9668 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9669 ExprResult &RHS) {
9670 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9671
9672 Diag(Loc, diag::err_typecheck_invalid_operands)
9673 << OrigLHS.getType() << OrigRHS.getType()
9674 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9675
9676 // If a user-defined conversion was applied to either of the operands prior
9677 // to applying the built-in operator rules, tell the user about it.
9678 if (OrigLHS.Conversion) {
9679 Diag(OrigLHS.Conversion->getLocation(),
9680 diag::note_typecheck_invalid_operands_converted)
9681 << 0 << LHS.get()->getType();
9682 }
9683 if (OrigRHS.Conversion) {
9684 Diag(OrigRHS.Conversion->getLocation(),
9685 diag::note_typecheck_invalid_operands_converted)
9686 << 1 << RHS.get()->getType();
9687 }
9688
9689 return QualType();
9690 }
9691
9692 // Diagnose cases where a scalar was implicitly converted to a vector and
9693 // diagnose the underlying types. Otherwise, diagnose the error
9694 // as invalid vector logical operands for non-C++ cases.
InvalidLogicalVectorOperands(SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)9695 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9696 ExprResult &RHS) {
9697 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9698 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9699
9700 bool LHSNatVec = LHSType->isVectorType();
9701 bool RHSNatVec = RHSType->isVectorType();
9702
9703 if (!(LHSNatVec && RHSNatVec)) {
9704 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9705 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9706 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9707 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9708 << Vector->getSourceRange();
9709 return QualType();
9710 }
9711
9712 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9713 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9714 << RHS.get()->getSourceRange();
9715
9716 return QualType();
9717 }
9718
9719 /// Try to convert a value of non-vector type to a vector type by converting
9720 /// the type to the element type of the vector and then performing a splat.
9721 /// If the language is OpenCL, we only use conversions that promote scalar
9722 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9723 /// for float->int.
9724 ///
9725 /// OpenCL V2.0 6.2.6.p2:
9726 /// An error shall occur if any scalar operand type has greater rank
9727 /// than the type of the vector element.
9728 ///
9729 /// \param scalar - if non-null, actually perform the conversions
9730 /// \return true if the operation fails (but without diagnosing the failure)
tryVectorConvertAndSplat(Sema & S,ExprResult * scalar,QualType scalarTy,QualType vectorEltTy,QualType vectorTy,unsigned & DiagID)9731 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9732 QualType scalarTy,
9733 QualType vectorEltTy,
9734 QualType vectorTy,
9735 unsigned &DiagID) {
9736 // The conversion to apply to the scalar before splatting it,
9737 // if necessary.
9738 CastKind scalarCast = CK_NoOp;
9739
9740 if (vectorEltTy->isIntegralType(S.Context)) {
9741 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9742 (scalarTy->isIntegerType() &&
9743 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9744 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9745 return true;
9746 }
9747 if (!scalarTy->isIntegralType(S.Context))
9748 return true;
9749 scalarCast = CK_IntegralCast;
9750 } else if (vectorEltTy->isRealFloatingType()) {
9751 if (scalarTy->isRealFloatingType()) {
9752 if (S.getLangOpts().OpenCL &&
9753 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9754 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9755 return true;
9756 }
9757 scalarCast = CK_FloatingCast;
9758 }
9759 else if (scalarTy->isIntegralType(S.Context))
9760 scalarCast = CK_IntegralToFloating;
9761 else
9762 return true;
9763 } else {
9764 return true;
9765 }
9766
9767 // Adjust scalar if desired.
9768 if (scalar) {
9769 if (scalarCast != CK_NoOp)
9770 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9771 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9772 }
9773 return false;
9774 }
9775
9776 /// Convert vector E to a vector with the same number of elements but different
9777 /// element type.
convertVector(Expr * E,QualType ElementType,Sema & S)9778 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9779 const auto *VecTy = E->getType()->getAs<VectorType>();
9780 assert(VecTy && "Expression E must be a vector");
9781 QualType NewVecTy = S.Context.getVectorType(ElementType,
9782 VecTy->getNumElements(),
9783 VecTy->getVectorKind());
9784
9785 // Look through the implicit cast. Return the subexpression if its type is
9786 // NewVecTy.
9787 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9788 if (ICE->getSubExpr()->getType() == NewVecTy)
9789 return ICE->getSubExpr();
9790
9791 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9792 return S.ImpCastExprToType(E, NewVecTy, Cast);
9793 }
9794
9795 /// Test if a (constant) integer Int can be casted to another integer type
9796 /// IntTy without losing precision.
canConvertIntToOtherIntTy(Sema & S,ExprResult * Int,QualType OtherIntTy)9797 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9798 QualType OtherIntTy) {
9799 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9800
9801 // Reject cases where the value of the Int is unknown as that would
9802 // possibly cause truncation, but accept cases where the scalar can be
9803 // demoted without loss of precision.
9804 Expr::EvalResult EVResult;
9805 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9806 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9807 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9808 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9809
9810 if (CstInt) {
9811 // If the scalar is constant and is of a higher order and has more active
9812 // bits that the vector element type, reject it.
9813 llvm::APSInt Result = EVResult.Val.getInt();
9814 unsigned NumBits = IntSigned
9815 ? (Result.isNegative() ? Result.getMinSignedBits()
9816 : Result.getActiveBits())
9817 : Result.getActiveBits();
9818 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9819 return true;
9820
9821 // If the signedness of the scalar type and the vector element type
9822 // differs and the number of bits is greater than that of the vector
9823 // element reject it.
9824 return (IntSigned != OtherIntSigned &&
9825 NumBits > S.Context.getIntWidth(OtherIntTy));
9826 }
9827
9828 // Reject cases where the value of the scalar is not constant and it's
9829 // order is greater than that of the vector element type.
9830 return (Order < 0);
9831 }
9832
9833 /// Test if a (constant) integer Int can be casted to floating point type
9834 /// FloatTy without losing precision.
canConvertIntTyToFloatTy(Sema & S,ExprResult * Int,QualType FloatTy)9835 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9836 QualType FloatTy) {
9837 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9838
9839 // Determine if the integer constant can be expressed as a floating point
9840 // number of the appropriate type.
9841 Expr::EvalResult EVResult;
9842 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9843
9844 uint64_t Bits = 0;
9845 if (CstInt) {
9846 // Reject constants that would be truncated if they were converted to
9847 // the floating point type. Test by simple to/from conversion.
9848 // FIXME: Ideally the conversion to an APFloat and from an APFloat
9849 // could be avoided if there was a convertFromAPInt method
9850 // which could signal back if implicit truncation occurred.
9851 llvm::APSInt Result = EVResult.Val.getInt();
9852 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9853 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9854 llvm::APFloat::rmTowardZero);
9855 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9856 !IntTy->hasSignedIntegerRepresentation());
9857 bool Ignored = false;
9858 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9859 &Ignored);
9860 if (Result != ConvertBack)
9861 return true;
9862 } else {
9863 // Reject types that cannot be fully encoded into the mantissa of
9864 // the float.
9865 Bits = S.Context.getTypeSize(IntTy);
9866 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9867 S.Context.getFloatTypeSemantics(FloatTy));
9868 if (Bits > FloatPrec)
9869 return true;
9870 }
9871
9872 return false;
9873 }
9874
9875 /// Attempt to convert and splat Scalar into a vector whose types matches
9876 /// Vector following GCC conversion rules. The rule is that implicit
9877 /// conversion can occur when Scalar can be casted to match Vector's element
9878 /// type without causing truncation of Scalar.
tryGCCVectorConvertAndSplat(Sema & S,ExprResult * Scalar,ExprResult * Vector)9879 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9880 ExprResult *Vector) {
9881 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9882 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9883 const VectorType *VT = VectorTy->getAs<VectorType>();
9884
9885 assert(!isa<ExtVectorType>(VT) &&
9886 "ExtVectorTypes should not be handled here!");
9887
9888 QualType VectorEltTy = VT->getElementType();
9889
9890 // Reject cases where the vector element type or the scalar element type are
9891 // not integral or floating point types.
9892 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9893 return true;
9894
9895 // The conversion to apply to the scalar before splatting it,
9896 // if necessary.
9897 CastKind ScalarCast = CK_NoOp;
9898
9899 // Accept cases where the vector elements are integers and the scalar is
9900 // an integer.
9901 // FIXME: Notionally if the scalar was a floating point value with a precise
9902 // integral representation, we could cast it to an appropriate integer
9903 // type and then perform the rest of the checks here. GCC will perform
9904 // this conversion in some cases as determined by the input language.
9905 // We should accept it on a language independent basis.
9906 if (VectorEltTy->isIntegralType(S.Context) &&
9907 ScalarTy->isIntegralType(S.Context) &&
9908 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9909
9910 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9911 return true;
9912
9913 ScalarCast = CK_IntegralCast;
9914 } else if (VectorEltTy->isIntegralType(S.Context) &&
9915 ScalarTy->isRealFloatingType()) {
9916 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9917 ScalarCast = CK_FloatingToIntegral;
9918 else
9919 return true;
9920 } else if (VectorEltTy->isRealFloatingType()) {
9921 if (ScalarTy->isRealFloatingType()) {
9922
9923 // Reject cases where the scalar type is not a constant and has a higher
9924 // Order than the vector element type.
9925 llvm::APFloat Result(0.0);
9926
9927 // Determine whether this is a constant scalar. In the event that the
9928 // value is dependent (and thus cannot be evaluated by the constant
9929 // evaluator), skip the evaluation. This will then diagnose once the
9930 // expression is instantiated.
9931 bool CstScalar = Scalar->get()->isValueDependent() ||
9932 Scalar->get()->EvaluateAsFloat(Result, S.Context);
9933 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9934 if (!CstScalar && Order < 0)
9935 return true;
9936
9937 // If the scalar cannot be safely casted to the vector element type,
9938 // reject it.
9939 if (CstScalar) {
9940 bool Truncated = false;
9941 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9942 llvm::APFloat::rmNearestTiesToEven, &Truncated);
9943 if (Truncated)
9944 return true;
9945 }
9946
9947 ScalarCast = CK_FloatingCast;
9948 } else if (ScalarTy->isIntegralType(S.Context)) {
9949 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9950 return true;
9951
9952 ScalarCast = CK_IntegralToFloating;
9953 } else
9954 return true;
9955 } else if (ScalarTy->isEnumeralType())
9956 return true;
9957
9958 // Adjust scalar if desired.
9959 if (Scalar) {
9960 if (ScalarCast != CK_NoOp)
9961 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9962 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9963 }
9964 return false;
9965 }
9966
CheckVectorOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign,bool AllowBothBool,bool AllowBoolConversions)9967 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9968 SourceLocation Loc, bool IsCompAssign,
9969 bool AllowBothBool,
9970 bool AllowBoolConversions) {
9971 if (!IsCompAssign) {
9972 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9973 if (LHS.isInvalid())
9974 return QualType();
9975 }
9976 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9977 if (RHS.isInvalid())
9978 return QualType();
9979
9980 // For conversion purposes, we ignore any qualifiers.
9981 // For example, "const float" and "float" are equivalent.
9982 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9983 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9984
9985 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9986 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9987 assert(LHSVecType || RHSVecType);
9988
9989 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
9990 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
9991 return InvalidOperands(Loc, LHS, RHS);
9992
9993 // AltiVec-style "vector bool op vector bool" combinations are allowed
9994 // for some operators but not others.
9995 if (!AllowBothBool &&
9996 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9997 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9998 return InvalidOperands(Loc, LHS, RHS);
9999
10000 // If the vector types are identical, return.
10001 if (Context.hasSameType(LHSType, RHSType))
10002 return LHSType;
10003
10004 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10005 if (LHSVecType && RHSVecType &&
10006 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10007 if (isa<ExtVectorType>(LHSVecType)) {
10008 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10009 return LHSType;
10010 }
10011
10012 if (!IsCompAssign)
10013 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10014 return RHSType;
10015 }
10016
10017 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10018 // can be mixed, with the result being the non-bool type. The non-bool
10019 // operand must have integer element type.
10020 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10021 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10022 (Context.getTypeSize(LHSVecType->getElementType()) ==
10023 Context.getTypeSize(RHSVecType->getElementType()))) {
10024 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10025 LHSVecType->getElementType()->isIntegerType() &&
10026 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
10027 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10028 return LHSType;
10029 }
10030 if (!IsCompAssign &&
10031 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
10032 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
10033 RHSVecType->getElementType()->isIntegerType()) {
10034 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10035 return RHSType;
10036 }
10037 }
10038
10039 // Expressions containing fixed-length and sizeless SVE vectors are invalid
10040 // since the ambiguity can affect the ABI.
10041 auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
10042 const VectorType *VecType = SecondType->getAs<VectorType>();
10043 return FirstType->isSizelessBuiltinType() && VecType &&
10044 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
10045 VecType->getVectorKind() ==
10046 VectorType::SveFixedLengthPredicateVector);
10047 };
10048
10049 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
10050 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
10051 return QualType();
10052 }
10053
10054 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10055 // since the ambiguity can affect the ABI.
10056 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
10057 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10058 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10059
10060 if (FirstVecType && SecondVecType)
10061 return FirstVecType->getVectorKind() == VectorType::GenericVector &&
10062 (SecondVecType->getVectorKind() ==
10063 VectorType::SveFixedLengthDataVector ||
10064 SecondVecType->getVectorKind() ==
10065 VectorType::SveFixedLengthPredicateVector);
10066
10067 return FirstType->isSizelessBuiltinType() && SecondVecType &&
10068 SecondVecType->getVectorKind() == VectorType::GenericVector;
10069 };
10070
10071 if (IsSveGnuConversion(LHSType, RHSType) ||
10072 IsSveGnuConversion(RHSType, LHSType)) {
10073 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
10074 return QualType();
10075 }
10076
10077 // If there's a vector type and a scalar, try to convert the scalar to
10078 // the vector element type and splat.
10079 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10080 if (!RHSVecType) {
10081 if (isa<ExtVectorType>(LHSVecType)) {
10082 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10083 LHSVecType->getElementType(), LHSType,
10084 DiagID))
10085 return LHSType;
10086 } else {
10087 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10088 return LHSType;
10089 }
10090 }
10091 if (!LHSVecType) {
10092 if (isa<ExtVectorType>(RHSVecType)) {
10093 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10094 LHSType, RHSVecType->getElementType(),
10095 RHSType, DiagID))
10096 return RHSType;
10097 } else {
10098 if (LHS.get()->getValueKind() == VK_LValue ||
10099 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10100 return RHSType;
10101 }
10102 }
10103
10104 // FIXME: The code below also handles conversion between vectors and
10105 // non-scalars, we should break this down into fine grained specific checks
10106 // and emit proper diagnostics.
10107 QualType VecType = LHSVecType ? LHSType : RHSType;
10108 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10109 QualType OtherType = LHSVecType ? RHSType : LHSType;
10110 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10111 if (isLaxVectorConversion(OtherType, VecType)) {
10112 // If we're allowing lax vector conversions, only the total (data) size
10113 // needs to be the same. For non compound assignment, if one of the types is
10114 // scalar, the result is always the vector type.
10115 if (!IsCompAssign) {
10116 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10117 return VecType;
10118 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10119 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10120 // type. Note that this is already done by non-compound assignments in
10121 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10122 // <1 x T> -> T. The result is also a vector type.
10123 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10124 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10125 ExprResult *RHSExpr = &RHS;
10126 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10127 return VecType;
10128 }
10129 }
10130
10131 // Okay, the expression is invalid.
10132
10133 // If there's a non-vector, non-real operand, diagnose that.
10134 if ((!RHSVecType && !RHSType->isRealType()) ||
10135 (!LHSVecType && !LHSType->isRealType())) {
10136 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10137 << LHSType << RHSType
10138 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10139 return QualType();
10140 }
10141
10142 // OpenCL V1.1 6.2.6.p1:
10143 // If the operands are of more than one vector type, then an error shall
10144 // occur. Implicit conversions between vector types are not permitted, per
10145 // section 6.2.1.
10146 if (getLangOpts().OpenCL &&
10147 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10148 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10149 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10150 << RHSType;
10151 return QualType();
10152 }
10153
10154
10155 // If there is a vector type that is not a ExtVector and a scalar, we reach
10156 // this point if scalar could not be converted to the vector's element type
10157 // without truncation.
10158 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10159 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10160 QualType Scalar = LHSVecType ? RHSType : LHSType;
10161 QualType Vector = LHSVecType ? LHSType : RHSType;
10162 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10163 Diag(Loc,
10164 diag::err_typecheck_vector_not_convertable_implict_truncation)
10165 << ScalarOrVector << Scalar << Vector;
10166
10167 return QualType();
10168 }
10169
10170 // Otherwise, use the generic diagnostic.
10171 Diag(Loc, DiagID)
10172 << LHSType << RHSType
10173 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10174 return QualType();
10175 }
10176
10177 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10178 // expression. These are mainly cases where the null pointer is used as an
10179 // integer instead of a pointer.
checkArithmeticNull(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompare)10180 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10181 SourceLocation Loc, bool IsCompare) {
10182 // The canonical way to check for a GNU null is with isNullPointerConstant,
10183 // but we use a bit of a hack here for speed; this is a relatively
10184 // hot path, and isNullPointerConstant is slow.
10185 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10186 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10187
10188 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10189
10190 // Avoid analyzing cases where the result will either be invalid (and
10191 // diagnosed as such) or entirely valid and not something to warn about.
10192 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10193 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10194 return;
10195
10196 // Comparison operations would not make sense with a null pointer no matter
10197 // what the other expression is.
10198 if (!IsCompare) {
10199 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10200 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10201 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10202 return;
10203 }
10204
10205 // The rest of the operations only make sense with a null pointer
10206 // if the other expression is a pointer.
10207 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10208 NonNullType->canDecayToPointerType())
10209 return;
10210
10211 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10212 << LHSNull /* LHS is NULL */ << NonNullType
10213 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10214 }
10215
DiagnoseDivisionSizeofPointerOrArray(Sema & S,Expr * LHS,Expr * RHS,SourceLocation Loc)10216 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10217 SourceLocation Loc) {
10218 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10219 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10220 if (!LUE || !RUE)
10221 return;
10222 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10223 RUE->getKind() != UETT_SizeOf)
10224 return;
10225
10226 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10227 QualType LHSTy = LHSArg->getType();
10228 QualType RHSTy;
10229
10230 if (RUE->isArgumentType())
10231 RHSTy = RUE->getArgumentType().getNonReferenceType();
10232 else
10233 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10234
10235 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10236 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10237 return;
10238
10239 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10240 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10241 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10242 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10243 << LHSArgDecl;
10244 }
10245 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10246 QualType ArrayElemTy = ArrayTy->getElementType();
10247 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10248 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10249 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10250 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10251 return;
10252 S.Diag(Loc, diag::warn_division_sizeof_array)
10253 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10254 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10255 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10256 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10257 << LHSArgDecl;
10258 }
10259
10260 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10261 }
10262 }
10263
DiagnoseBadDivideOrRemainderValues(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsDiv)10264 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10265 ExprResult &RHS,
10266 SourceLocation Loc, bool IsDiv) {
10267 // Check for division/remainder by zero.
10268 Expr::EvalResult RHSValue;
10269 if (!RHS.get()->isValueDependent() &&
10270 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10271 RHSValue.Val.getInt() == 0)
10272 S.DiagRuntimeBehavior(Loc, RHS.get(),
10273 S.PDiag(diag::warn_remainder_division_by_zero)
10274 << IsDiv << RHS.get()->getSourceRange());
10275 }
10276
CheckMultiplyDivideOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign,bool IsDiv)10277 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10278 SourceLocation Loc,
10279 bool IsCompAssign, bool IsDiv) {
10280 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10281
10282 QualType LHSTy = LHS.get()->getType();
10283 QualType RHSTy = RHS.get()->getType();
10284 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10285 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10286 /*AllowBothBool*/getLangOpts().AltiVec,
10287 /*AllowBoolConversions*/false);
10288 if (!IsDiv &&
10289 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10290 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10291 // For division, only matrix-by-scalar is supported. Other combinations with
10292 // matrix types are invalid.
10293 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10294 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10295
10296 QualType compType = UsualArithmeticConversions(
10297 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10298 if (LHS.isInvalid() || RHS.isInvalid())
10299 return QualType();
10300
10301
10302 if (compType.isNull() || !compType->isArithmeticType())
10303 return InvalidOperands(Loc, LHS, RHS);
10304 if (IsDiv) {
10305 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10306 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10307 }
10308 return compType;
10309 }
10310
CheckRemainderOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)10311 QualType Sema::CheckRemainderOperands(
10312 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10313 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10314
10315 if (LHS.get()->getType()->isVectorType() ||
10316 RHS.get()->getType()->isVectorType()) {
10317 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10318 RHS.get()->getType()->hasIntegerRepresentation())
10319 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10320 /*AllowBothBool*/getLangOpts().AltiVec,
10321 /*AllowBoolConversions*/false);
10322 return InvalidOperands(Loc, LHS, RHS);
10323 }
10324
10325 QualType compType = UsualArithmeticConversions(
10326 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10327 if (LHS.isInvalid() || RHS.isInvalid())
10328 return QualType();
10329
10330 if (compType.isNull() || !compType->isIntegerType())
10331 return InvalidOperands(Loc, LHS, RHS);
10332 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10333 return compType;
10334 }
10335
10336 /// Diagnose invalid arithmetic on two void pointers.
diagnoseArithmeticOnTwoVoidPointers(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)10337 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10338 Expr *LHSExpr, Expr *RHSExpr) {
10339 S.Diag(Loc, S.getLangOpts().CPlusPlus
10340 ? diag::err_typecheck_pointer_arith_void_type
10341 : diag::ext_gnu_void_ptr)
10342 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10343 << RHSExpr->getSourceRange();
10344 }
10345
10346 /// Diagnose invalid arithmetic on a void pointer.
diagnoseArithmeticOnVoidPointer(Sema & S,SourceLocation Loc,Expr * Pointer)10347 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10348 Expr *Pointer) {
10349 S.Diag(Loc, S.getLangOpts().CPlusPlus
10350 ? diag::err_typecheck_pointer_arith_void_type
10351 : diag::ext_gnu_void_ptr)
10352 << 0 /* one pointer */ << Pointer->getSourceRange();
10353 }
10354
10355 /// Diagnose invalid arithmetic on a null pointer.
10356 ///
10357 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10358 /// idiom, which we recognize as a GNU extension.
10359 ///
diagnoseArithmeticOnNullPointer(Sema & S,SourceLocation Loc,Expr * Pointer,bool IsGNUIdiom)10360 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10361 Expr *Pointer, bool IsGNUIdiom) {
10362 if (IsGNUIdiom)
10363 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10364 << Pointer->getSourceRange();
10365 else
10366 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10367 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10368 }
10369
10370 /// Diagnose invalid arithmetic on two function pointers.
diagnoseArithmeticOnTwoFunctionPointers(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS)10371 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10372 Expr *LHS, Expr *RHS) {
10373 assert(LHS->getType()->isAnyPointerType());
10374 assert(RHS->getType()->isAnyPointerType());
10375 S.Diag(Loc, S.getLangOpts().CPlusPlus
10376 ? diag::err_typecheck_pointer_arith_function_type
10377 : diag::ext_gnu_ptr_func_arith)
10378 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10379 // We only show the second type if it differs from the first.
10380 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10381 RHS->getType())
10382 << RHS->getType()->getPointeeType()
10383 << LHS->getSourceRange() << RHS->getSourceRange();
10384 }
10385
10386 /// Diagnose invalid arithmetic on a function pointer.
diagnoseArithmeticOnFunctionPointer(Sema & S,SourceLocation Loc,Expr * Pointer)10387 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10388 Expr *Pointer) {
10389 assert(Pointer->getType()->isAnyPointerType());
10390 S.Diag(Loc, S.getLangOpts().CPlusPlus
10391 ? diag::err_typecheck_pointer_arith_function_type
10392 : diag::ext_gnu_ptr_func_arith)
10393 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10394 << 0 /* one pointer, so only one type */
10395 << Pointer->getSourceRange();
10396 }
10397
10398 /// Emit error if Operand is incomplete pointer type
10399 ///
10400 /// \returns True if pointer has incomplete type
checkArithmeticIncompletePointerType(Sema & S,SourceLocation Loc,Expr * Operand)10401 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10402 Expr *Operand) {
10403 QualType ResType = Operand->getType();
10404 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10405 ResType = ResAtomicType->getValueType();
10406
10407 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10408 QualType PointeeTy = ResType->getPointeeType();
10409 return S.RequireCompleteSizedType(
10410 Loc, PointeeTy,
10411 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10412 Operand->getSourceRange());
10413 }
10414
10415 /// Check the validity of an arithmetic pointer operand.
10416 ///
10417 /// If the operand has pointer type, this code will check for pointer types
10418 /// which are invalid in arithmetic operations. These will be diagnosed
10419 /// appropriately, including whether or not the use is supported as an
10420 /// extension.
10421 ///
10422 /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticOpPointerOperand(Sema & S,SourceLocation Loc,Expr * Operand)10423 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10424 Expr *Operand) {
10425 QualType ResType = Operand->getType();
10426 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10427 ResType = ResAtomicType->getValueType();
10428
10429 if (!ResType->isAnyPointerType()) return true;
10430
10431 QualType PointeeTy = ResType->getPointeeType();
10432 if (PointeeTy->isVoidType()) {
10433 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10434 return !S.getLangOpts().CPlusPlus;
10435 }
10436 if (PointeeTy->isFunctionType()) {
10437 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10438 return !S.getLangOpts().CPlusPlus;
10439 }
10440
10441 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10442
10443 return true;
10444 }
10445
10446 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10447 /// operands.
10448 ///
10449 /// This routine will diagnose any invalid arithmetic on pointer operands much
10450 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10451 /// for emitting a single diagnostic even for operations where both LHS and RHS
10452 /// are (potentially problematic) pointers.
10453 ///
10454 /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticBinOpPointerOperands(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)10455 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10456 Expr *LHSExpr, Expr *RHSExpr) {
10457 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10458 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10459 if (!isLHSPointer && !isRHSPointer) return true;
10460
10461 QualType LHSPointeeTy, RHSPointeeTy;
10462 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10463 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10464
10465 // if both are pointers check if operation is valid wrt address spaces
10466 if (isLHSPointer && isRHSPointer) {
10467 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10468 S.Diag(Loc,
10469 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10470 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10471 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10472 return false;
10473 }
10474 }
10475
10476 // Check for arithmetic on pointers to incomplete types.
10477 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10478 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10479 if (isLHSVoidPtr || isRHSVoidPtr) {
10480 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10481 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10482 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10483
10484 return !S.getLangOpts().CPlusPlus;
10485 }
10486
10487 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10488 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10489 if (isLHSFuncPtr || isRHSFuncPtr) {
10490 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10491 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10492 RHSExpr);
10493 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10494
10495 return !S.getLangOpts().CPlusPlus;
10496 }
10497
10498 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10499 return false;
10500 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10501 return false;
10502
10503 return true;
10504 }
10505
10506 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10507 /// literal.
diagnoseStringPlusInt(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10508 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10509 Expr *LHSExpr, Expr *RHSExpr) {
10510 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10511 Expr* IndexExpr = RHSExpr;
10512 if (!StrExpr) {
10513 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10514 IndexExpr = LHSExpr;
10515 }
10516
10517 bool IsStringPlusInt = StrExpr &&
10518 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10519 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10520 return;
10521
10522 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10523 Self.Diag(OpLoc, diag::warn_string_plus_int)
10524 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10525
10526 // Only print a fixit for "str" + int, not for int + "str".
10527 if (IndexExpr == RHSExpr) {
10528 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10529 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10530 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10531 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10532 << FixItHint::CreateInsertion(EndLoc, "]");
10533 } else
10534 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10535 }
10536
10537 /// Emit a warning when adding a char literal to a string.
diagnoseStringPlusChar(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10538 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10539 Expr *LHSExpr, Expr *RHSExpr) {
10540 const Expr *StringRefExpr = LHSExpr;
10541 const CharacterLiteral *CharExpr =
10542 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10543
10544 if (!CharExpr) {
10545 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10546 StringRefExpr = RHSExpr;
10547 }
10548
10549 if (!CharExpr || !StringRefExpr)
10550 return;
10551
10552 const QualType StringType = StringRefExpr->getType();
10553
10554 // Return if not a PointerType.
10555 if (!StringType->isAnyPointerType())
10556 return;
10557
10558 // Return if not a CharacterType.
10559 if (!StringType->getPointeeType()->isAnyCharacterType())
10560 return;
10561
10562 ASTContext &Ctx = Self.getASTContext();
10563 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10564
10565 const QualType CharType = CharExpr->getType();
10566 if (!CharType->isAnyCharacterType() &&
10567 CharType->isIntegerType() &&
10568 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10569 Self.Diag(OpLoc, diag::warn_string_plus_char)
10570 << DiagRange << Ctx.CharTy;
10571 } else {
10572 Self.Diag(OpLoc, diag::warn_string_plus_char)
10573 << DiagRange << CharExpr->getType();
10574 }
10575
10576 // Only print a fixit for str + char, not for char + str.
10577 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10578 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10579 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10580 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10581 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10582 << FixItHint::CreateInsertion(EndLoc, "]");
10583 } else {
10584 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10585 }
10586 }
10587
10588 /// Emit error when two pointers are incompatible.
diagnosePointerIncompatibility(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)10589 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10590 Expr *LHSExpr, Expr *RHSExpr) {
10591 assert(LHSExpr->getType()->isAnyPointerType());
10592 assert(RHSExpr->getType()->isAnyPointerType());
10593 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10594 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10595 << RHSExpr->getSourceRange();
10596 }
10597
10598 // C99 6.5.6
CheckAdditionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,QualType * CompLHSTy)10599 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10600 SourceLocation Loc, BinaryOperatorKind Opc,
10601 QualType* CompLHSTy) {
10602 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10603
10604 if (LHS.get()->getType()->isVectorType() ||
10605 RHS.get()->getType()->isVectorType()) {
10606 QualType compType = CheckVectorOperands(
10607 LHS, RHS, Loc, CompLHSTy,
10608 /*AllowBothBool*/getLangOpts().AltiVec,
10609 /*AllowBoolConversions*/getLangOpts().ZVector);
10610 if (CompLHSTy) *CompLHSTy = compType;
10611 return compType;
10612 }
10613
10614 if (LHS.get()->getType()->isConstantMatrixType() ||
10615 RHS.get()->getType()->isConstantMatrixType()) {
10616 QualType compType =
10617 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10618 if (CompLHSTy)
10619 *CompLHSTy = compType;
10620 return compType;
10621 }
10622
10623 QualType compType = UsualArithmeticConversions(
10624 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10625 if (LHS.isInvalid() || RHS.isInvalid())
10626 return QualType();
10627
10628 // Diagnose "string literal" '+' int and string '+' "char literal".
10629 if (Opc == BO_Add) {
10630 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10631 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10632 }
10633
10634 // handle the common case first (both operands are arithmetic).
10635 if (!compType.isNull() && compType->isArithmeticType()) {
10636 if (CompLHSTy) *CompLHSTy = compType;
10637 return compType;
10638 }
10639
10640 // Type-checking. Ultimately the pointer's going to be in PExp;
10641 // note that we bias towards the LHS being the pointer.
10642 Expr *PExp = LHS.get(), *IExp = RHS.get();
10643
10644 bool isObjCPointer;
10645 if (PExp->getType()->isPointerType()) {
10646 isObjCPointer = false;
10647 } else if (PExp->getType()->isObjCObjectPointerType()) {
10648 isObjCPointer = true;
10649 } else {
10650 std::swap(PExp, IExp);
10651 if (PExp->getType()->isPointerType()) {
10652 isObjCPointer = false;
10653 } else if (PExp->getType()->isObjCObjectPointerType()) {
10654 isObjCPointer = true;
10655 } else {
10656 return InvalidOperands(Loc, LHS, RHS);
10657 }
10658 }
10659 assert(PExp->getType()->isAnyPointerType());
10660
10661 if (!IExp->getType()->isIntegerType())
10662 return InvalidOperands(Loc, LHS, RHS);
10663
10664 // Adding to a null pointer results in undefined behavior.
10665 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10666 Context, Expr::NPC_ValueDependentIsNotNull)) {
10667 // In C++ adding zero to a null pointer is defined.
10668 Expr::EvalResult KnownVal;
10669 if (!getLangOpts().CPlusPlus ||
10670 (!IExp->isValueDependent() &&
10671 (!IExp->EvaluateAsInt(KnownVal, Context) ||
10672 KnownVal.Val.getInt() != 0))) {
10673 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10674 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10675 Context, BO_Add, PExp, IExp);
10676 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10677 }
10678 }
10679
10680 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10681 return QualType();
10682
10683 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10684 return QualType();
10685
10686 // Check array bounds for pointer arithemtic
10687 CheckArrayAccess(PExp, IExp);
10688
10689 if (CompLHSTy) {
10690 QualType LHSTy = Context.isPromotableBitField(LHS.get());
10691 if (LHSTy.isNull()) {
10692 LHSTy = LHS.get()->getType();
10693 if (LHSTy->isPromotableIntegerType())
10694 LHSTy = Context.getPromotedIntegerType(LHSTy);
10695 }
10696 *CompLHSTy = LHSTy;
10697 }
10698
10699 return PExp->getType();
10700 }
10701
10702 // C99 6.5.6
CheckSubtractionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,QualType * CompLHSTy)10703 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10704 SourceLocation Loc,
10705 QualType* CompLHSTy) {
10706 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10707
10708 if (LHS.get()->getType()->isVectorType() ||
10709 RHS.get()->getType()->isVectorType()) {
10710 QualType compType = CheckVectorOperands(
10711 LHS, RHS, Loc, CompLHSTy,
10712 /*AllowBothBool*/getLangOpts().AltiVec,
10713 /*AllowBoolConversions*/getLangOpts().ZVector);
10714 if (CompLHSTy) *CompLHSTy = compType;
10715 return compType;
10716 }
10717
10718 if (LHS.get()->getType()->isConstantMatrixType() ||
10719 RHS.get()->getType()->isConstantMatrixType()) {
10720 QualType compType =
10721 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10722 if (CompLHSTy)
10723 *CompLHSTy = compType;
10724 return compType;
10725 }
10726
10727 QualType compType = UsualArithmeticConversions(
10728 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10729 if (LHS.isInvalid() || RHS.isInvalid())
10730 return QualType();
10731
10732 // Enforce type constraints: C99 6.5.6p3.
10733
10734 // Handle the common case first (both operands are arithmetic).
10735 if (!compType.isNull() && compType->isArithmeticType()) {
10736 if (CompLHSTy) *CompLHSTy = compType;
10737 return compType;
10738 }
10739
10740 // Either ptr - int or ptr - ptr.
10741 if (LHS.get()->getType()->isAnyPointerType()) {
10742 QualType lpointee = LHS.get()->getType()->getPointeeType();
10743
10744 // Diagnose bad cases where we step over interface counts.
10745 if (LHS.get()->getType()->isObjCObjectPointerType() &&
10746 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10747 return QualType();
10748
10749 // The result type of a pointer-int computation is the pointer type.
10750 if (RHS.get()->getType()->isIntegerType()) {
10751 // Subtracting from a null pointer should produce a warning.
10752 // The last argument to the diagnose call says this doesn't match the
10753 // GNU int-to-pointer idiom.
10754 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10755 Expr::NPC_ValueDependentIsNotNull)) {
10756 // In C++ adding zero to a null pointer is defined.
10757 Expr::EvalResult KnownVal;
10758 if (!getLangOpts().CPlusPlus ||
10759 (!RHS.get()->isValueDependent() &&
10760 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10761 KnownVal.Val.getInt() != 0))) {
10762 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10763 }
10764 }
10765
10766 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10767 return QualType();
10768
10769 // Check array bounds for pointer arithemtic
10770 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10771 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10772
10773 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10774 return LHS.get()->getType();
10775 }
10776
10777 // Handle pointer-pointer subtractions.
10778 if (const PointerType *RHSPTy
10779 = RHS.get()->getType()->getAs<PointerType>()) {
10780 QualType rpointee = RHSPTy->getPointeeType();
10781
10782 if (getLangOpts().CPlusPlus) {
10783 // Pointee types must be the same: C++ [expr.add]
10784 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10785 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10786 }
10787 } else {
10788 // Pointee types must be compatible C99 6.5.6p3
10789 if (!Context.typesAreCompatible(
10790 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10791 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10792 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10793 return QualType();
10794 }
10795 }
10796
10797 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10798 LHS.get(), RHS.get()))
10799 return QualType();
10800
10801 // FIXME: Add warnings for nullptr - ptr.
10802
10803 // The pointee type may have zero size. As an extension, a structure or
10804 // union may have zero size or an array may have zero length. In this
10805 // case subtraction does not make sense.
10806 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10807 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10808 if (ElementSize.isZero()) {
10809 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10810 << rpointee.getUnqualifiedType()
10811 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10812 }
10813 }
10814
10815 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10816 return Context.getPointerDiffType();
10817 }
10818 }
10819
10820 return InvalidOperands(Loc, LHS, RHS);
10821 }
10822
isScopedEnumerationType(QualType T)10823 static bool isScopedEnumerationType(QualType T) {
10824 if (const EnumType *ET = T->getAs<EnumType>())
10825 return ET->getDecl()->isScoped();
10826 return false;
10827 }
10828
DiagnoseBadShiftValues(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,QualType LHSType)10829 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10830 SourceLocation Loc, BinaryOperatorKind Opc,
10831 QualType LHSType) {
10832 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10833 // so skip remaining warnings as we don't want to modify values within Sema.
10834 if (S.getLangOpts().OpenCL)
10835 return;
10836
10837 // Check right/shifter operand
10838 Expr::EvalResult RHSResult;
10839 if (RHS.get()->isValueDependent() ||
10840 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10841 return;
10842 llvm::APSInt Right = RHSResult.Val.getInt();
10843
10844 if (Right.isNegative()) {
10845 S.DiagRuntimeBehavior(Loc, RHS.get(),
10846 S.PDiag(diag::warn_shift_negative)
10847 << RHS.get()->getSourceRange());
10848 return;
10849 }
10850
10851 QualType LHSExprType = LHS.get()->getType();
10852 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10853 if (LHSExprType->isExtIntType())
10854 LeftSize = S.Context.getIntWidth(LHSExprType);
10855 else if (LHSExprType->isFixedPointType()) {
10856 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10857 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10858 }
10859 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10860 if (Right.uge(LeftBits)) {
10861 S.DiagRuntimeBehavior(Loc, RHS.get(),
10862 S.PDiag(diag::warn_shift_gt_typewidth)
10863 << RHS.get()->getSourceRange());
10864 return;
10865 }
10866
10867 // FIXME: We probably need to handle fixed point types specially here.
10868 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10869 return;
10870
10871 // When left shifting an ICE which is signed, we can check for overflow which
10872 // according to C++ standards prior to C++2a has undefined behavior
10873 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10874 // more than the maximum value representable in the result type, so never
10875 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10876 // expression is still probably a bug.)
10877 Expr::EvalResult LHSResult;
10878 if (LHS.get()->isValueDependent() ||
10879 LHSType->hasUnsignedIntegerRepresentation() ||
10880 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10881 return;
10882 llvm::APSInt Left = LHSResult.Val.getInt();
10883
10884 // If LHS does not have a signed type and non-negative value
10885 // then, the behavior is undefined before C++2a. Warn about it.
10886 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10887 !S.getLangOpts().CPlusPlus20) {
10888 S.DiagRuntimeBehavior(Loc, LHS.get(),
10889 S.PDiag(diag::warn_shift_lhs_negative)
10890 << LHS.get()->getSourceRange());
10891 return;
10892 }
10893
10894 llvm::APInt ResultBits =
10895 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10896 if (LeftBits.uge(ResultBits))
10897 return;
10898 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10899 Result = Result.shl(Right);
10900
10901 // Print the bit representation of the signed integer as an unsigned
10902 // hexadecimal number.
10903 SmallString<40> HexResult;
10904 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10905
10906 // If we are only missing a sign bit, this is less likely to result in actual
10907 // bugs -- if the result is cast back to an unsigned type, it will have the
10908 // expected value. Thus we place this behind a different warning that can be
10909 // turned off separately if needed.
10910 if (LeftBits == ResultBits - 1) {
10911 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10912 << HexResult << LHSType
10913 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10914 return;
10915 }
10916
10917 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10918 << HexResult.str() << Result.getMinSignedBits() << LHSType
10919 << Left.getBitWidth() << LHS.get()->getSourceRange()
10920 << RHS.get()->getSourceRange();
10921 }
10922
10923 /// Return the resulting type when a vector is shifted
10924 /// by a scalar or vector shift amount.
checkVectorShift(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)10925 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10926 SourceLocation Loc, bool IsCompAssign) {
10927 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10928 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10929 !LHS.get()->getType()->isVectorType()) {
10930 S.Diag(Loc, diag::err_shift_rhs_only_vector)
10931 << RHS.get()->getType() << LHS.get()->getType()
10932 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10933 return QualType();
10934 }
10935
10936 if (!IsCompAssign) {
10937 LHS = S.UsualUnaryConversions(LHS.get());
10938 if (LHS.isInvalid()) return QualType();
10939 }
10940
10941 RHS = S.UsualUnaryConversions(RHS.get());
10942 if (RHS.isInvalid()) return QualType();
10943
10944 QualType LHSType = LHS.get()->getType();
10945 // Note that LHS might be a scalar because the routine calls not only in
10946 // OpenCL case.
10947 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10948 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10949
10950 // Note that RHS might not be a vector.
10951 QualType RHSType = RHS.get()->getType();
10952 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10953 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10954
10955 // The operands need to be integers.
10956 if (!LHSEleType->isIntegerType()) {
10957 S.Diag(Loc, diag::err_typecheck_expect_int)
10958 << LHS.get()->getType() << LHS.get()->getSourceRange();
10959 return QualType();
10960 }
10961
10962 if (!RHSEleType->isIntegerType()) {
10963 S.Diag(Loc, diag::err_typecheck_expect_int)
10964 << RHS.get()->getType() << RHS.get()->getSourceRange();
10965 return QualType();
10966 }
10967
10968 if (!LHSVecTy) {
10969 assert(RHSVecTy);
10970 if (IsCompAssign)
10971 return RHSType;
10972 if (LHSEleType != RHSEleType) {
10973 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10974 LHSEleType = RHSEleType;
10975 }
10976 QualType VecTy =
10977 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10978 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10979 LHSType = VecTy;
10980 } else if (RHSVecTy) {
10981 // OpenCL v1.1 s6.3.j says that for vector types, the operators
10982 // are applied component-wise. So if RHS is a vector, then ensure
10983 // that the number of elements is the same as LHS...
10984 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10985 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10986 << LHS.get()->getType() << RHS.get()->getType()
10987 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10988 return QualType();
10989 }
10990 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10991 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10992 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10993 if (LHSBT != RHSBT &&
10994 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10995 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10996 << LHS.get()->getType() << RHS.get()->getType()
10997 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10998 }
10999 }
11000 } else {
11001 // ...else expand RHS to match the number of elements in LHS.
11002 QualType VecTy =
11003 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11004 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11005 }
11006
11007 return LHSType;
11008 }
11009
11010 // C99 6.5.7
CheckShiftOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,bool IsCompAssign)11011 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11012 SourceLocation Loc, BinaryOperatorKind Opc,
11013 bool IsCompAssign) {
11014 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11015
11016 // Vector shifts promote their scalar inputs to vector type.
11017 if (LHS.get()->getType()->isVectorType() ||
11018 RHS.get()->getType()->isVectorType()) {
11019 if (LangOpts.ZVector) {
11020 // The shift operators for the z vector extensions work basically
11021 // like general shifts, except that neither the LHS nor the RHS is
11022 // allowed to be a "vector bool".
11023 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11024 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
11025 return InvalidOperands(Loc, LHS, RHS);
11026 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11027 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
11028 return InvalidOperands(Loc, LHS, RHS);
11029 }
11030 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11031 }
11032
11033 // Shifts don't perform usual arithmetic conversions, they just do integer
11034 // promotions on each operand. C99 6.5.7p3
11035
11036 // For the LHS, do usual unary conversions, but then reset them away
11037 // if this is a compound assignment.
11038 ExprResult OldLHS = LHS;
11039 LHS = UsualUnaryConversions(LHS.get());
11040 if (LHS.isInvalid())
11041 return QualType();
11042 QualType LHSType = LHS.get()->getType();
11043 if (IsCompAssign) LHS = OldLHS;
11044
11045 // The RHS is simpler.
11046 RHS = UsualUnaryConversions(RHS.get());
11047 if (RHS.isInvalid())
11048 return QualType();
11049 QualType RHSType = RHS.get()->getType();
11050
11051 // C99 6.5.7p2: Each of the operands shall have integer type.
11052 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11053 if ((!LHSType->isFixedPointOrIntegerType() &&
11054 !LHSType->hasIntegerRepresentation()) ||
11055 !RHSType->hasIntegerRepresentation())
11056 return InvalidOperands(Loc, LHS, RHS);
11057
11058 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11059 // hasIntegerRepresentation() above instead of this.
11060 if (isScopedEnumerationType(LHSType) ||
11061 isScopedEnumerationType(RHSType)) {
11062 return InvalidOperands(Loc, LHS, RHS);
11063 }
11064 // Sanity-check shift operands
11065 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11066
11067 // "The type of the result is that of the promoted left operand."
11068 return LHSType;
11069 }
11070
11071 /// Diagnose bad pointer comparisons.
diagnoseDistinctPointerComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)11072 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
11073 ExprResult &LHS, ExprResult &RHS,
11074 bool IsError) {
11075 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11076 : diag::ext_typecheck_comparison_of_distinct_pointers)
11077 << LHS.get()->getType() << RHS.get()->getType()
11078 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11079 }
11080
11081 /// Returns false if the pointers are converted to a composite type,
11082 /// true otherwise.
convertPointersToCompositeType(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)11083 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
11084 ExprResult &LHS, ExprResult &RHS) {
11085 // C++ [expr.rel]p2:
11086 // [...] Pointer conversions (4.10) and qualification
11087 // conversions (4.4) are performed on pointer operands (or on
11088 // a pointer operand and a null pointer constant) to bring
11089 // them to their composite pointer type. [...]
11090 //
11091 // C++ [expr.eq]p1 uses the same notion for (in)equality
11092 // comparisons of pointers.
11093
11094 QualType LHSType = LHS.get()->getType();
11095 QualType RHSType = RHS.get()->getType();
11096 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11097 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11098
11099 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11100 if (T.isNull()) {
11101 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11102 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11103 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11104 else
11105 S.InvalidOperands(Loc, LHS, RHS);
11106 return true;
11107 }
11108
11109 return false;
11110 }
11111
diagnoseFunctionPointerToVoidComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)11112 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11113 ExprResult &LHS,
11114 ExprResult &RHS,
11115 bool IsError) {
11116 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11117 : diag::ext_typecheck_comparison_of_fptr_to_void)
11118 << LHS.get()->getType() << RHS.get()->getType()
11119 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11120 }
11121
isObjCObjectLiteral(ExprResult & E)11122 static bool isObjCObjectLiteral(ExprResult &E) {
11123 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11124 case Stmt::ObjCArrayLiteralClass:
11125 case Stmt::ObjCDictionaryLiteralClass:
11126 case Stmt::ObjCStringLiteralClass:
11127 case Stmt::ObjCBoxedExprClass:
11128 return true;
11129 default:
11130 // Note that ObjCBoolLiteral is NOT an object literal!
11131 return false;
11132 }
11133 }
11134
hasIsEqualMethod(Sema & S,const Expr * LHS,const Expr * RHS)11135 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11136 const ObjCObjectPointerType *Type =
11137 LHS->getType()->getAs<ObjCObjectPointerType>();
11138
11139 // If this is not actually an Objective-C object, bail out.
11140 if (!Type)
11141 return false;
11142
11143 // Get the LHS object's interface type.
11144 QualType InterfaceType = Type->getPointeeType();
11145
11146 // If the RHS isn't an Objective-C object, bail out.
11147 if (!RHS->getType()->isObjCObjectPointerType())
11148 return false;
11149
11150 // Try to find the -isEqual: method.
11151 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11152 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11153 InterfaceType,
11154 /*IsInstance=*/true);
11155 if (!Method) {
11156 if (Type->isObjCIdType()) {
11157 // For 'id', just check the global pool.
11158 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11159 /*receiverId=*/true);
11160 } else {
11161 // Check protocols.
11162 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11163 /*IsInstance=*/true);
11164 }
11165 }
11166
11167 if (!Method)
11168 return false;
11169
11170 QualType T = Method->parameters()[0]->getType();
11171 if (!T->isObjCObjectPointerType())
11172 return false;
11173
11174 QualType R = Method->getReturnType();
11175 if (!R->isScalarType())
11176 return false;
11177
11178 return true;
11179 }
11180
CheckLiteralKind(Expr * FromE)11181 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11182 FromE = FromE->IgnoreParenImpCasts();
11183 switch (FromE->getStmtClass()) {
11184 default:
11185 break;
11186 case Stmt::ObjCStringLiteralClass:
11187 // "string literal"
11188 return LK_String;
11189 case Stmt::ObjCArrayLiteralClass:
11190 // "array literal"
11191 return LK_Array;
11192 case Stmt::ObjCDictionaryLiteralClass:
11193 // "dictionary literal"
11194 return LK_Dictionary;
11195 case Stmt::BlockExprClass:
11196 return LK_Block;
11197 case Stmt::ObjCBoxedExprClass: {
11198 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11199 switch (Inner->getStmtClass()) {
11200 case Stmt::IntegerLiteralClass:
11201 case Stmt::FloatingLiteralClass:
11202 case Stmt::CharacterLiteralClass:
11203 case Stmt::ObjCBoolLiteralExprClass:
11204 case Stmt::CXXBoolLiteralExprClass:
11205 // "numeric literal"
11206 return LK_Numeric;
11207 case Stmt::ImplicitCastExprClass: {
11208 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11209 // Boolean literals can be represented by implicit casts.
11210 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11211 return LK_Numeric;
11212 break;
11213 }
11214 default:
11215 break;
11216 }
11217 return LK_Boxed;
11218 }
11219 }
11220 return LK_None;
11221 }
11222
diagnoseObjCLiteralComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,BinaryOperator::Opcode Opc)11223 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11224 ExprResult &LHS, ExprResult &RHS,
11225 BinaryOperator::Opcode Opc){
11226 Expr *Literal;
11227 Expr *Other;
11228 if (isObjCObjectLiteral(LHS)) {
11229 Literal = LHS.get();
11230 Other = RHS.get();
11231 } else {
11232 Literal = RHS.get();
11233 Other = LHS.get();
11234 }
11235
11236 // Don't warn on comparisons against nil.
11237 Other = Other->IgnoreParenCasts();
11238 if (Other->isNullPointerConstant(S.getASTContext(),
11239 Expr::NPC_ValueDependentIsNotNull))
11240 return;
11241
11242 // This should be kept in sync with warn_objc_literal_comparison.
11243 // LK_String should always be after the other literals, since it has its own
11244 // warning flag.
11245 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11246 assert(LiteralKind != Sema::LK_Block);
11247 if (LiteralKind == Sema::LK_None) {
11248 llvm_unreachable("Unknown Objective-C object literal kind");
11249 }
11250
11251 if (LiteralKind == Sema::LK_String)
11252 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11253 << Literal->getSourceRange();
11254 else
11255 S.Diag(Loc, diag::warn_objc_literal_comparison)
11256 << LiteralKind << Literal->getSourceRange();
11257
11258 if (BinaryOperator::isEqualityOp(Opc) &&
11259 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11260 SourceLocation Start = LHS.get()->getBeginLoc();
11261 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11262 CharSourceRange OpRange =
11263 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11264
11265 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11266 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11267 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11268 << FixItHint::CreateInsertion(End, "]");
11269 }
11270 }
11271
11272 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
diagnoseLogicalNotOnLHSofCheck(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)11273 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11274 ExprResult &RHS, SourceLocation Loc,
11275 BinaryOperatorKind Opc) {
11276 // Check that left hand side is !something.
11277 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11278 if (!UO || UO->getOpcode() != UO_LNot) return;
11279
11280 // Only check if the right hand side is non-bool arithmetic type.
11281 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11282
11283 // Make sure that the something in !something is not bool.
11284 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11285 if (SubExpr->isKnownToHaveBooleanValue()) return;
11286
11287 // Emit warning.
11288 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11289 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11290 << Loc << IsBitwiseOp;
11291
11292 // First note suggest !(x < y)
11293 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11294 SourceLocation FirstClose = RHS.get()->getEndLoc();
11295 FirstClose = S.getLocForEndOfToken(FirstClose);
11296 if (FirstClose.isInvalid())
11297 FirstOpen = SourceLocation();
11298 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11299 << IsBitwiseOp
11300 << FixItHint::CreateInsertion(FirstOpen, "(")
11301 << FixItHint::CreateInsertion(FirstClose, ")");
11302
11303 // Second note suggests (!x) < y
11304 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11305 SourceLocation SecondClose = LHS.get()->getEndLoc();
11306 SecondClose = S.getLocForEndOfToken(SecondClose);
11307 if (SecondClose.isInvalid())
11308 SecondOpen = SourceLocation();
11309 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11310 << FixItHint::CreateInsertion(SecondOpen, "(")
11311 << FixItHint::CreateInsertion(SecondClose, ")");
11312 }
11313
11314 // Returns true if E refers to a non-weak array.
checkForArray(const Expr * E)11315 static bool checkForArray(const Expr *E) {
11316 const ValueDecl *D = nullptr;
11317 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11318 D = DR->getDecl();
11319 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11320 if (Mem->isImplicitAccess())
11321 D = Mem->getMemberDecl();
11322 }
11323 if (!D)
11324 return false;
11325 return D->getType()->isArrayType() && !D->isWeak();
11326 }
11327
11328 /// Diagnose some forms of syntactically-obvious tautological comparison.
diagnoseTautologicalComparison(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS,BinaryOperatorKind Opc)11329 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11330 Expr *LHS, Expr *RHS,
11331 BinaryOperatorKind Opc) {
11332 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11333 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11334
11335 QualType LHSType = LHS->getType();
11336 QualType RHSType = RHS->getType();
11337 if (LHSType->hasFloatingRepresentation() ||
11338 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11339 S.inTemplateInstantiation())
11340 return;
11341
11342 // Comparisons between two array types are ill-formed for operator<=>, so
11343 // we shouldn't emit any additional warnings about it.
11344 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11345 return;
11346
11347 // For non-floating point types, check for self-comparisons of the form
11348 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11349 // often indicate logic errors in the program.
11350 //
11351 // NOTE: Don't warn about comparison expressions resulting from macro
11352 // expansion. Also don't warn about comparisons which are only self
11353 // comparisons within a template instantiation. The warnings should catch
11354 // obvious cases in the definition of the template anyways. The idea is to
11355 // warn when the typed comparison operator will always evaluate to the same
11356 // result.
11357
11358 // Used for indexing into %select in warn_comparison_always
11359 enum {
11360 AlwaysConstant,
11361 AlwaysTrue,
11362 AlwaysFalse,
11363 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11364 };
11365
11366 // C++2a [depr.array.comp]:
11367 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11368 // operands of array type are deprecated.
11369 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11370 RHSStripped->getType()->isArrayType()) {
11371 S.Diag(Loc, diag::warn_depr_array_comparison)
11372 << LHS->getSourceRange() << RHS->getSourceRange()
11373 << LHSStripped->getType() << RHSStripped->getType();
11374 // Carry on to produce the tautological comparison warning, if this
11375 // expression is potentially-evaluated, we can resolve the array to a
11376 // non-weak declaration, and so on.
11377 }
11378
11379 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11380 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11381 unsigned Result;
11382 switch (Opc) {
11383 case BO_EQ:
11384 case BO_LE:
11385 case BO_GE:
11386 Result = AlwaysTrue;
11387 break;
11388 case BO_NE:
11389 case BO_LT:
11390 case BO_GT:
11391 Result = AlwaysFalse;
11392 break;
11393 case BO_Cmp:
11394 Result = AlwaysEqual;
11395 break;
11396 default:
11397 Result = AlwaysConstant;
11398 break;
11399 }
11400 S.DiagRuntimeBehavior(Loc, nullptr,
11401 S.PDiag(diag::warn_comparison_always)
11402 << 0 /*self-comparison*/
11403 << Result);
11404 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11405 // What is it always going to evaluate to?
11406 unsigned Result;
11407 switch (Opc) {
11408 case BO_EQ: // e.g. array1 == array2
11409 Result = AlwaysFalse;
11410 break;
11411 case BO_NE: // e.g. array1 != array2
11412 Result = AlwaysTrue;
11413 break;
11414 default: // e.g. array1 <= array2
11415 // The best we can say is 'a constant'
11416 Result = AlwaysConstant;
11417 break;
11418 }
11419 S.DiagRuntimeBehavior(Loc, nullptr,
11420 S.PDiag(diag::warn_comparison_always)
11421 << 1 /*array comparison*/
11422 << Result);
11423 }
11424 }
11425
11426 if (isa<CastExpr>(LHSStripped))
11427 LHSStripped = LHSStripped->IgnoreParenCasts();
11428 if (isa<CastExpr>(RHSStripped))
11429 RHSStripped = RHSStripped->IgnoreParenCasts();
11430
11431 // Warn about comparisons against a string constant (unless the other
11432 // operand is null); the user probably wants string comparison function.
11433 Expr *LiteralString = nullptr;
11434 Expr *LiteralStringStripped = nullptr;
11435 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11436 !RHSStripped->isNullPointerConstant(S.Context,
11437 Expr::NPC_ValueDependentIsNull)) {
11438 LiteralString = LHS;
11439 LiteralStringStripped = LHSStripped;
11440 } else if ((isa<StringLiteral>(RHSStripped) ||
11441 isa<ObjCEncodeExpr>(RHSStripped)) &&
11442 !LHSStripped->isNullPointerConstant(S.Context,
11443 Expr::NPC_ValueDependentIsNull)) {
11444 LiteralString = RHS;
11445 LiteralStringStripped = RHSStripped;
11446 }
11447
11448 if (LiteralString) {
11449 S.DiagRuntimeBehavior(Loc, nullptr,
11450 S.PDiag(diag::warn_stringcompare)
11451 << isa<ObjCEncodeExpr>(LiteralStringStripped)
11452 << LiteralString->getSourceRange());
11453 }
11454 }
11455
castKindToImplicitConversionKind(CastKind CK)11456 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11457 switch (CK) {
11458 default: {
11459 #ifndef NDEBUG
11460 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11461 << "\n";
11462 #endif
11463 llvm_unreachable("unhandled cast kind");
11464 }
11465 case CK_UserDefinedConversion:
11466 return ICK_Identity;
11467 case CK_LValueToRValue:
11468 return ICK_Lvalue_To_Rvalue;
11469 case CK_ArrayToPointerDecay:
11470 return ICK_Array_To_Pointer;
11471 case CK_FunctionToPointerDecay:
11472 return ICK_Function_To_Pointer;
11473 case CK_IntegralCast:
11474 return ICK_Integral_Conversion;
11475 case CK_FloatingCast:
11476 return ICK_Floating_Conversion;
11477 case CK_IntegralToFloating:
11478 case CK_FloatingToIntegral:
11479 return ICK_Floating_Integral;
11480 case CK_IntegralComplexCast:
11481 case CK_FloatingComplexCast:
11482 case CK_FloatingComplexToIntegralComplex:
11483 case CK_IntegralComplexToFloatingComplex:
11484 return ICK_Complex_Conversion;
11485 case CK_FloatingComplexToReal:
11486 case CK_FloatingRealToComplex:
11487 case CK_IntegralComplexToReal:
11488 case CK_IntegralRealToComplex:
11489 return ICK_Complex_Real;
11490 }
11491 }
11492
checkThreeWayNarrowingConversion(Sema & S,QualType ToType,Expr * E,QualType FromType,SourceLocation Loc)11493 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11494 QualType FromType,
11495 SourceLocation Loc) {
11496 // Check for a narrowing implicit conversion.
11497 StandardConversionSequence SCS;
11498 SCS.setAsIdentityConversion();
11499 SCS.setToType(0, FromType);
11500 SCS.setToType(1, ToType);
11501 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11502 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11503
11504 APValue PreNarrowingValue;
11505 QualType PreNarrowingType;
11506 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11507 PreNarrowingType,
11508 /*IgnoreFloatToIntegralConversion*/ true)) {
11509 case NK_Dependent_Narrowing:
11510 // Implicit conversion to a narrower type, but the expression is
11511 // value-dependent so we can't tell whether it's actually narrowing.
11512 case NK_Not_Narrowing:
11513 return false;
11514
11515 case NK_Constant_Narrowing:
11516 // Implicit conversion to a narrower type, and the value is not a constant
11517 // expression.
11518 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11519 << /*Constant*/ 1
11520 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11521 return true;
11522
11523 case NK_Variable_Narrowing:
11524 // Implicit conversion to a narrower type, and the value is not a constant
11525 // expression.
11526 case NK_Type_Narrowing:
11527 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11528 << /*Constant*/ 0 << FromType << ToType;
11529 // TODO: It's not a constant expression, but what if the user intended it
11530 // to be? Can we produce notes to help them figure out why it isn't?
11531 return true;
11532 }
11533 llvm_unreachable("unhandled case in switch");
11534 }
11535
checkArithmeticOrEnumeralThreeWayCompare(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)11536 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11537 ExprResult &LHS,
11538 ExprResult &RHS,
11539 SourceLocation Loc) {
11540 QualType LHSType = LHS.get()->getType();
11541 QualType RHSType = RHS.get()->getType();
11542 // Dig out the original argument type and expression before implicit casts
11543 // were applied. These are the types/expressions we need to check the
11544 // [expr.spaceship] requirements against.
11545 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11546 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11547 QualType LHSStrippedType = LHSStripped.get()->getType();
11548 QualType RHSStrippedType = RHSStripped.get()->getType();
11549
11550 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11551 // other is not, the program is ill-formed.
11552 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11553 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11554 return QualType();
11555 }
11556
11557 // FIXME: Consider combining this with checkEnumArithmeticConversions.
11558 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11559 RHSStrippedType->isEnumeralType();
11560 if (NumEnumArgs == 1) {
11561 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11562 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11563 if (OtherTy->hasFloatingRepresentation()) {
11564 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11565 return QualType();
11566 }
11567 }
11568 if (NumEnumArgs == 2) {
11569 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11570 // type E, the operator yields the result of converting the operands
11571 // to the underlying type of E and applying <=> to the converted operands.
11572 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11573 S.InvalidOperands(Loc, LHS, RHS);
11574 return QualType();
11575 }
11576 QualType IntType =
11577 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11578 assert(IntType->isArithmeticType());
11579
11580 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11581 // promote the boolean type, and all other promotable integer types, to
11582 // avoid this.
11583 if (IntType->isPromotableIntegerType())
11584 IntType = S.Context.getPromotedIntegerType(IntType);
11585
11586 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11587 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11588 LHSType = RHSType = IntType;
11589 }
11590
11591 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11592 // usual arithmetic conversions are applied to the operands.
11593 QualType Type =
11594 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11595 if (LHS.isInvalid() || RHS.isInvalid())
11596 return QualType();
11597 if (Type.isNull())
11598 return S.InvalidOperands(Loc, LHS, RHS);
11599
11600 Optional<ComparisonCategoryType> CCT =
11601 getComparisonCategoryForBuiltinCmp(Type);
11602 if (!CCT)
11603 return S.InvalidOperands(Loc, LHS, RHS);
11604
11605 bool HasNarrowing = checkThreeWayNarrowingConversion(
11606 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11607 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11608 RHS.get()->getBeginLoc());
11609 if (HasNarrowing)
11610 return QualType();
11611
11612 assert(!Type.isNull() && "composite type for <=> has not been set");
11613
11614 return S.CheckComparisonCategoryType(
11615 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11616 }
11617
checkArithmeticOrEnumeralCompare(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)11618 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11619 ExprResult &RHS,
11620 SourceLocation Loc,
11621 BinaryOperatorKind Opc) {
11622 if (Opc == BO_Cmp)
11623 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11624
11625 // C99 6.5.8p3 / C99 6.5.9p4
11626 QualType Type =
11627 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11628 if (LHS.isInvalid() || RHS.isInvalid())
11629 return QualType();
11630 if (Type.isNull())
11631 return S.InvalidOperands(Loc, LHS, RHS);
11632 assert(Type->isArithmeticType() || Type->isEnumeralType());
11633
11634 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11635 return S.InvalidOperands(Loc, LHS, RHS);
11636
11637 // Check for comparisons of floating point operands using != and ==.
11638 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11639 S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11640
11641 // The result of comparisons is 'bool' in C++, 'int' in C.
11642 return S.Context.getLogicalOperationType();
11643 }
11644
CheckPtrComparisonWithNullChar(ExprResult & E,ExprResult & NullE)11645 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11646 if (!NullE.get()->getType()->isAnyPointerType())
11647 return;
11648 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11649 if (!E.get()->getType()->isAnyPointerType() &&
11650 E.get()->isNullPointerConstant(Context,
11651 Expr::NPC_ValueDependentIsNotNull) ==
11652 Expr::NPCK_ZeroExpression) {
11653 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11654 if (CL->getValue() == 0)
11655 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11656 << NullValue
11657 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11658 NullValue ? "NULL" : "(void *)0");
11659 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11660 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11661 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11662 if (T == Context.CharTy)
11663 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11664 << NullValue
11665 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11666 NullValue ? "NULL" : "(void *)0");
11667 }
11668 }
11669 }
11670
11671 // C99 6.5.8, C++ [expr.rel]
CheckCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)11672 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11673 SourceLocation Loc,
11674 BinaryOperatorKind Opc) {
11675 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11676 bool IsThreeWay = Opc == BO_Cmp;
11677 bool IsOrdered = IsRelational || IsThreeWay;
11678 auto IsAnyPointerType = [](ExprResult E) {
11679 QualType Ty = E.get()->getType();
11680 return Ty->isPointerType() || Ty->isMemberPointerType();
11681 };
11682
11683 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11684 // type, array-to-pointer, ..., conversions are performed on both operands to
11685 // bring them to their composite type.
11686 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11687 // any type-related checks.
11688 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11689 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11690 if (LHS.isInvalid())
11691 return QualType();
11692 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11693 if (RHS.isInvalid())
11694 return QualType();
11695 } else {
11696 LHS = DefaultLvalueConversion(LHS.get());
11697 if (LHS.isInvalid())
11698 return QualType();
11699 RHS = DefaultLvalueConversion(RHS.get());
11700 if (RHS.isInvalid())
11701 return QualType();
11702 }
11703
11704 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11705 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11706 CheckPtrComparisonWithNullChar(LHS, RHS);
11707 CheckPtrComparisonWithNullChar(RHS, LHS);
11708 }
11709
11710 // Handle vector comparisons separately.
11711 if (LHS.get()->getType()->isVectorType() ||
11712 RHS.get()->getType()->isVectorType())
11713 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11714
11715 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11716 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11717
11718 QualType LHSType = LHS.get()->getType();
11719 QualType RHSType = RHS.get()->getType();
11720 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11721 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11722 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11723
11724 const Expr::NullPointerConstantKind LHSNullKind =
11725 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11726 const Expr::NullPointerConstantKind RHSNullKind =
11727 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11728 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11729 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11730
11731 auto computeResultTy = [&]() {
11732 if (Opc != BO_Cmp)
11733 return Context.getLogicalOperationType();
11734 assert(getLangOpts().CPlusPlus);
11735 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11736
11737 QualType CompositeTy = LHS.get()->getType();
11738 assert(!CompositeTy->isReferenceType());
11739
11740 Optional<ComparisonCategoryType> CCT =
11741 getComparisonCategoryForBuiltinCmp(CompositeTy);
11742 if (!CCT)
11743 return InvalidOperands(Loc, LHS, RHS);
11744
11745 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11746 // P0946R0: Comparisons between a null pointer constant and an object
11747 // pointer result in std::strong_equality, which is ill-formed under
11748 // P1959R0.
11749 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11750 << (LHSIsNull ? LHS.get()->getSourceRange()
11751 : RHS.get()->getSourceRange());
11752 return QualType();
11753 }
11754
11755 return CheckComparisonCategoryType(
11756 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11757 };
11758
11759 if (!IsOrdered && LHSIsNull != RHSIsNull) {
11760 bool IsEquality = Opc == BO_EQ;
11761 if (RHSIsNull)
11762 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11763 RHS.get()->getSourceRange());
11764 else
11765 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11766 LHS.get()->getSourceRange());
11767 }
11768
11769 if ((LHSType->isIntegerType() && !LHSIsNull) ||
11770 (RHSType->isIntegerType() && !RHSIsNull)) {
11771 // Skip normal pointer conversion checks in this case; we have better
11772 // diagnostics for this below.
11773 } else if (getLangOpts().CPlusPlus) {
11774 // Equality comparison of a function pointer to a void pointer is invalid,
11775 // but we allow it as an extension.
11776 // FIXME: If we really want to allow this, should it be part of composite
11777 // pointer type computation so it works in conditionals too?
11778 if (!IsOrdered &&
11779 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11780 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11781 // This is a gcc extension compatibility comparison.
11782 // In a SFINAE context, we treat this as a hard error to maintain
11783 // conformance with the C++ standard.
11784 diagnoseFunctionPointerToVoidComparison(
11785 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11786
11787 if (isSFINAEContext())
11788 return QualType();
11789
11790 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11791 return computeResultTy();
11792 }
11793
11794 // C++ [expr.eq]p2:
11795 // If at least one operand is a pointer [...] bring them to their
11796 // composite pointer type.
11797 // C++ [expr.spaceship]p6
11798 // If at least one of the operands is of pointer type, [...] bring them
11799 // to their composite pointer type.
11800 // C++ [expr.rel]p2:
11801 // If both operands are pointers, [...] bring them to their composite
11802 // pointer type.
11803 // For <=>, the only valid non-pointer types are arrays and functions, and
11804 // we already decayed those, so this is really the same as the relational
11805 // comparison rule.
11806 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11807 (IsOrdered ? 2 : 1) &&
11808 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11809 RHSType->isObjCObjectPointerType()))) {
11810 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11811 return QualType();
11812 return computeResultTy();
11813 }
11814 } else if (LHSType->isPointerType() &&
11815 RHSType->isPointerType()) { // C99 6.5.8p2
11816 // All of the following pointer-related warnings are GCC extensions, except
11817 // when handling null pointer constants.
11818 QualType LCanPointeeTy =
11819 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11820 QualType RCanPointeeTy =
11821 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11822
11823 // C99 6.5.9p2 and C99 6.5.8p2
11824 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11825 RCanPointeeTy.getUnqualifiedType())) {
11826 if (IsRelational) {
11827 // Pointers both need to point to complete or incomplete types
11828 if ((LCanPointeeTy->isIncompleteType() !=
11829 RCanPointeeTy->isIncompleteType()) &&
11830 !getLangOpts().C11) {
11831 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11832 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11833 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11834 << RCanPointeeTy->isIncompleteType();
11835 }
11836 if (LCanPointeeTy->isFunctionType()) {
11837 // Valid unless a relational comparison of function pointers
11838 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11839 << LHSType << RHSType << LHS.get()->getSourceRange()
11840 << RHS.get()->getSourceRange();
11841 }
11842 }
11843 } else if (!IsRelational &&
11844 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11845 // Valid unless comparison between non-null pointer and function pointer
11846 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11847 && !LHSIsNull && !RHSIsNull)
11848 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11849 /*isError*/false);
11850 } else {
11851 // Invalid
11852 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11853 }
11854 if (LCanPointeeTy != RCanPointeeTy) {
11855 // Treat NULL constant as a special case in OpenCL.
11856 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11857 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11858 Diag(Loc,
11859 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11860 << LHSType << RHSType << 0 /* comparison */
11861 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11862 }
11863 }
11864 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11865 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11866 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11867 : CK_BitCast;
11868 if (LHSIsNull && !RHSIsNull)
11869 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11870 else
11871 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11872 }
11873 return computeResultTy();
11874 }
11875
11876 if (getLangOpts().CPlusPlus) {
11877 // C++ [expr.eq]p4:
11878 // Two operands of type std::nullptr_t or one operand of type
11879 // std::nullptr_t and the other a null pointer constant compare equal.
11880 if (!IsOrdered && LHSIsNull && RHSIsNull) {
11881 if (LHSType->isNullPtrType()) {
11882 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11883 return computeResultTy();
11884 }
11885 if (RHSType->isNullPtrType()) {
11886 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11887 return computeResultTy();
11888 }
11889 }
11890
11891 // Comparison of Objective-C pointers and block pointers against nullptr_t.
11892 // These aren't covered by the composite pointer type rules.
11893 if (!IsOrdered && RHSType->isNullPtrType() &&
11894 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11895 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11896 return computeResultTy();
11897 }
11898 if (!IsOrdered && LHSType->isNullPtrType() &&
11899 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11900 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11901 return computeResultTy();
11902 }
11903
11904 if (IsRelational &&
11905 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11906 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11907 // HACK: Relational comparison of nullptr_t against a pointer type is
11908 // invalid per DR583, but we allow it within std::less<> and friends,
11909 // since otherwise common uses of it break.
11910 // FIXME: Consider removing this hack once LWG fixes std::less<> and
11911 // friends to have std::nullptr_t overload candidates.
11912 DeclContext *DC = CurContext;
11913 if (isa<FunctionDecl>(DC))
11914 DC = DC->getParent();
11915 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11916 if (CTSD->isInStdNamespace() &&
11917 llvm::StringSwitch<bool>(CTSD->getName())
11918 .Cases("less", "less_equal", "greater", "greater_equal", true)
11919 .Default(false)) {
11920 if (RHSType->isNullPtrType())
11921 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11922 else
11923 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11924 return computeResultTy();
11925 }
11926 }
11927 }
11928
11929 // C++ [expr.eq]p2:
11930 // If at least one operand is a pointer to member, [...] bring them to
11931 // their composite pointer type.
11932 if (!IsOrdered &&
11933 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11934 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11935 return QualType();
11936 else
11937 return computeResultTy();
11938 }
11939 }
11940
11941 // Handle block pointer types.
11942 if (!IsOrdered && LHSType->isBlockPointerType() &&
11943 RHSType->isBlockPointerType()) {
11944 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11945 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11946
11947 if (!LHSIsNull && !RHSIsNull &&
11948 !Context.typesAreCompatible(lpointee, rpointee)) {
11949 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11950 << LHSType << RHSType << LHS.get()->getSourceRange()
11951 << RHS.get()->getSourceRange();
11952 }
11953 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11954 return computeResultTy();
11955 }
11956
11957 // Allow block pointers to be compared with null pointer constants.
11958 if (!IsOrdered
11959 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11960 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11961 if (!LHSIsNull && !RHSIsNull) {
11962 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11963 ->getPointeeType()->isVoidType())
11964 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11965 ->getPointeeType()->isVoidType())))
11966 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11967 << LHSType << RHSType << LHS.get()->getSourceRange()
11968 << RHS.get()->getSourceRange();
11969 }
11970 if (LHSIsNull && !RHSIsNull)
11971 LHS = ImpCastExprToType(LHS.get(), RHSType,
11972 RHSType->isPointerType() ? CK_BitCast
11973 : CK_AnyPointerToBlockPointerCast);
11974 else
11975 RHS = ImpCastExprToType(RHS.get(), LHSType,
11976 LHSType->isPointerType() ? CK_BitCast
11977 : CK_AnyPointerToBlockPointerCast);
11978 return computeResultTy();
11979 }
11980
11981 if (LHSType->isObjCObjectPointerType() ||
11982 RHSType->isObjCObjectPointerType()) {
11983 const PointerType *LPT = LHSType->getAs<PointerType>();
11984 const PointerType *RPT = RHSType->getAs<PointerType>();
11985 if (LPT || RPT) {
11986 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11987 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11988
11989 if (!LPtrToVoid && !RPtrToVoid &&
11990 !Context.typesAreCompatible(LHSType, RHSType)) {
11991 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11992 /*isError*/false);
11993 }
11994 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11995 // the RHS, but we have test coverage for this behavior.
11996 // FIXME: Consider using convertPointersToCompositeType in C++.
11997 if (LHSIsNull && !RHSIsNull) {
11998 Expr *E = LHS.get();
11999 if (getLangOpts().ObjCAutoRefCount)
12000 CheckObjCConversion(SourceRange(), RHSType, E,
12001 CCK_ImplicitConversion);
12002 LHS = ImpCastExprToType(E, RHSType,
12003 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12004 }
12005 else {
12006 Expr *E = RHS.get();
12007 if (getLangOpts().ObjCAutoRefCount)
12008 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
12009 /*Diagnose=*/true,
12010 /*DiagnoseCFAudited=*/false, Opc);
12011 RHS = ImpCastExprToType(E, LHSType,
12012 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12013 }
12014 return computeResultTy();
12015 }
12016 if (LHSType->isObjCObjectPointerType() &&
12017 RHSType->isObjCObjectPointerType()) {
12018 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12019 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12020 /*isError*/false);
12021 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
12022 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12023
12024 if (LHSIsNull && !RHSIsNull)
12025 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12026 else
12027 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12028 return computeResultTy();
12029 }
12030
12031 if (!IsOrdered && LHSType->isBlockPointerType() &&
12032 RHSType->isBlockCompatibleObjCPointerType(Context)) {
12033 LHS = ImpCastExprToType(LHS.get(), RHSType,
12034 CK_BlockPointerToObjCPointerCast);
12035 return computeResultTy();
12036 } else if (!IsOrdered &&
12037 LHSType->isBlockCompatibleObjCPointerType(Context) &&
12038 RHSType->isBlockPointerType()) {
12039 RHS = ImpCastExprToType(RHS.get(), LHSType,
12040 CK_BlockPointerToObjCPointerCast);
12041 return computeResultTy();
12042 }
12043 }
12044 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12045 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12046 unsigned DiagID = 0;
12047 bool isError = false;
12048 if (LangOpts.DebuggerSupport) {
12049 // Under a debugger, allow the comparison of pointers to integers,
12050 // since users tend to want to compare addresses.
12051 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12052 (RHSIsNull && RHSType->isIntegerType())) {
12053 if (IsOrdered) {
12054 isError = getLangOpts().CPlusPlus;
12055 DiagID =
12056 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12057 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12058 }
12059 } else if (getLangOpts().CPlusPlus) {
12060 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12061 isError = true;
12062 } else if (IsOrdered)
12063 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12064 else
12065 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12066
12067 if (DiagID) {
12068 Diag(Loc, DiagID)
12069 << LHSType << RHSType << LHS.get()->getSourceRange()
12070 << RHS.get()->getSourceRange();
12071 if (isError)
12072 return QualType();
12073 }
12074
12075 if (LHSType->isIntegerType())
12076 LHS = ImpCastExprToType(LHS.get(), RHSType,
12077 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12078 else
12079 RHS = ImpCastExprToType(RHS.get(), LHSType,
12080 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12081 return computeResultTy();
12082 }
12083
12084 // Handle block pointers.
12085 if (!IsOrdered && RHSIsNull
12086 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12087 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12088 return computeResultTy();
12089 }
12090 if (!IsOrdered && LHSIsNull
12091 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12092 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12093 return computeResultTy();
12094 }
12095
12096 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
12097 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12098 return computeResultTy();
12099 }
12100
12101 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12102 return computeResultTy();
12103 }
12104
12105 if (LHSIsNull && RHSType->isQueueT()) {
12106 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12107 return computeResultTy();
12108 }
12109
12110 if (LHSType->isQueueT() && RHSIsNull) {
12111 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12112 return computeResultTy();
12113 }
12114 }
12115
12116 return InvalidOperands(Loc, LHS, RHS);
12117 }
12118
12119 // Return a signed ext_vector_type that is of identical size and number of
12120 // elements. For floating point vectors, return an integer type of identical
12121 // size and number of elements. In the non ext_vector_type case, search from
12122 // the largest type to the smallest type to avoid cases where long long == long,
12123 // where long gets picked over long long.
GetSignedVectorType(QualType V)12124 QualType Sema::GetSignedVectorType(QualType V) {
12125 const VectorType *VTy = V->castAs<VectorType>();
12126 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12127
12128 if (isa<ExtVectorType>(VTy)) {
12129 if (TypeSize == Context.getTypeSize(Context.CharTy))
12130 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12131 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12132 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12133 else if (TypeSize == Context.getTypeSize(Context.IntTy))
12134 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12135 else if (TypeSize == Context.getTypeSize(Context.LongTy))
12136 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12137 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12138 "Unhandled vector element size in vector compare");
12139 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12140 }
12141
12142 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12143 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12144 VectorType::GenericVector);
12145 else if (TypeSize == Context.getTypeSize(Context.LongTy))
12146 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12147 VectorType::GenericVector);
12148 else if (TypeSize == Context.getTypeSize(Context.IntTy))
12149 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12150 VectorType::GenericVector);
12151 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12152 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12153 VectorType::GenericVector);
12154 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12155 "Unhandled vector element size in vector compare");
12156 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12157 VectorType::GenericVector);
12158 }
12159
12160 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12161 /// operates on extended vector types. Instead of producing an IntTy result,
12162 /// like a scalar comparison, a vector comparison produces a vector of integer
12163 /// types.
CheckVectorCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)12164 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12165 SourceLocation Loc,
12166 BinaryOperatorKind Opc) {
12167 if (Opc == BO_Cmp) {
12168 Diag(Loc, diag::err_three_way_vector_comparison);
12169 return QualType();
12170 }
12171
12172 // Check to make sure we're operating on vectors of the same type and width,
12173 // Allowing one side to be a scalar of element type.
12174 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
12175 /*AllowBothBool*/true,
12176 /*AllowBoolConversions*/getLangOpts().ZVector);
12177 if (vType.isNull())
12178 return vType;
12179
12180 QualType LHSType = LHS.get()->getType();
12181
12182 // If AltiVec, the comparison results in a numeric type, i.e.
12183 // bool for C++, int for C
12184 if (getLangOpts().AltiVec &&
12185 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
12186 return Context.getLogicalOperationType();
12187
12188 // For non-floating point types, check for self-comparisons of the form
12189 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12190 // often indicate logic errors in the program.
12191 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12192
12193 // Check for comparisons of floating point operands using != and ==.
12194 if (BinaryOperator::isEqualityOp(Opc) &&
12195 LHSType->hasFloatingRepresentation()) {
12196 assert(RHS.get()->getType()->hasFloatingRepresentation());
12197 CheckFloatComparison(Loc, LHS.get(), RHS.get());
12198 }
12199
12200 // Return a signed type for the vector.
12201 return GetSignedVectorType(vType);
12202 }
12203
diagnoseXorMisusedAsPow(Sema & S,const ExprResult & XorLHS,const ExprResult & XorRHS,const SourceLocation Loc)12204 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12205 const ExprResult &XorRHS,
12206 const SourceLocation Loc) {
12207 // Do not diagnose macros.
12208 if (Loc.isMacroID())
12209 return;
12210
12211 // Do not diagnose if both LHS and RHS are macros.
12212 if (XorLHS.get()->getExprLoc().isMacroID() &&
12213 XorRHS.get()->getExprLoc().isMacroID())
12214 return;
12215
12216 bool Negative = false;
12217 bool ExplicitPlus = false;
12218 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12219 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12220
12221 if (!LHSInt)
12222 return;
12223 if (!RHSInt) {
12224 // Check negative literals.
12225 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12226 UnaryOperatorKind Opc = UO->getOpcode();
12227 if (Opc != UO_Minus && Opc != UO_Plus)
12228 return;
12229 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12230 if (!RHSInt)
12231 return;
12232 Negative = (Opc == UO_Minus);
12233 ExplicitPlus = !Negative;
12234 } else {
12235 return;
12236 }
12237 }
12238
12239 const llvm::APInt &LeftSideValue = LHSInt->getValue();
12240 llvm::APInt RightSideValue = RHSInt->getValue();
12241 if (LeftSideValue != 2 && LeftSideValue != 10)
12242 return;
12243
12244 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12245 return;
12246
12247 CharSourceRange ExprRange = CharSourceRange::getCharRange(
12248 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12249 llvm::StringRef ExprStr =
12250 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12251
12252 CharSourceRange XorRange =
12253 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12254 llvm::StringRef XorStr =
12255 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12256 // Do not diagnose if xor keyword/macro is used.
12257 if (XorStr == "xor")
12258 return;
12259
12260 std::string LHSStr = std::string(Lexer::getSourceText(
12261 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12262 S.getSourceManager(), S.getLangOpts()));
12263 std::string RHSStr = std::string(Lexer::getSourceText(
12264 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12265 S.getSourceManager(), S.getLangOpts()));
12266
12267 if (Negative) {
12268 RightSideValue = -RightSideValue;
12269 RHSStr = "-" + RHSStr;
12270 } else if (ExplicitPlus) {
12271 RHSStr = "+" + RHSStr;
12272 }
12273
12274 StringRef LHSStrRef = LHSStr;
12275 StringRef RHSStrRef = RHSStr;
12276 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12277 // literals.
12278 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12279 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12280 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12281 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12282 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12283 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12284 LHSStrRef.find('\'') != StringRef::npos ||
12285 RHSStrRef.find('\'') != StringRef::npos)
12286 return;
12287
12288 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12289 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12290 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12291 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12292 std::string SuggestedExpr = "1 << " + RHSStr;
12293 bool Overflow = false;
12294 llvm::APInt One = (LeftSideValue - 1);
12295 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12296 if (Overflow) {
12297 if (RightSideIntValue < 64)
12298 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12299 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12300 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12301 else if (RightSideIntValue == 64)
12302 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12303 else
12304 return;
12305 } else {
12306 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12307 << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12308 << PowValue.toString(10, true)
12309 << FixItHint::CreateReplacement(
12310 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12311 }
12312
12313 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12314 } else if (LeftSideValue == 10) {
12315 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12316 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12317 << ExprStr << XorValue.toString(10, true) << SuggestedValue
12318 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12319 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12320 }
12321 }
12322
CheckVectorLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)12323 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12324 SourceLocation Loc) {
12325 // Ensure that either both operands are of the same vector type, or
12326 // one operand is of a vector type and the other is of its element type.
12327 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12328 /*AllowBothBool*/true,
12329 /*AllowBoolConversions*/false);
12330 if (vType.isNull())
12331 return InvalidOperands(Loc, LHS, RHS);
12332 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12333 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12334 return InvalidOperands(Loc, LHS, RHS);
12335 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12336 // usage of the logical operators && and || with vectors in C. This
12337 // check could be notionally dropped.
12338 if (!getLangOpts().CPlusPlus &&
12339 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12340 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12341
12342 return GetSignedVectorType(LHS.get()->getType());
12343 }
12344
CheckMatrixElementwiseOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)12345 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12346 SourceLocation Loc,
12347 bool IsCompAssign) {
12348 if (!IsCompAssign) {
12349 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12350 if (LHS.isInvalid())
12351 return QualType();
12352 }
12353 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12354 if (RHS.isInvalid())
12355 return QualType();
12356
12357 // For conversion purposes, we ignore any qualifiers.
12358 // For example, "const float" and "float" are equivalent.
12359 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12360 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12361
12362 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12363 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12364 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12365
12366 if (Context.hasSameType(LHSType, RHSType))
12367 return LHSType;
12368
12369 // Type conversion may change LHS/RHS. Keep copies to the original results, in
12370 // case we have to return InvalidOperands.
12371 ExprResult OriginalLHS = LHS;
12372 ExprResult OriginalRHS = RHS;
12373 if (LHSMatType && !RHSMatType) {
12374 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12375 if (!RHS.isInvalid())
12376 return LHSType;
12377
12378 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12379 }
12380
12381 if (!LHSMatType && RHSMatType) {
12382 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12383 if (!LHS.isInvalid())
12384 return RHSType;
12385 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12386 }
12387
12388 return InvalidOperands(Loc, LHS, RHS);
12389 }
12390
CheckMatrixMultiplyOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)12391 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12392 SourceLocation Loc,
12393 bool IsCompAssign) {
12394 if (!IsCompAssign) {
12395 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12396 if (LHS.isInvalid())
12397 return QualType();
12398 }
12399 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12400 if (RHS.isInvalid())
12401 return QualType();
12402
12403 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12404 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12405 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12406
12407 if (LHSMatType && RHSMatType) {
12408 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12409 return InvalidOperands(Loc, LHS, RHS);
12410
12411 if (!Context.hasSameType(LHSMatType->getElementType(),
12412 RHSMatType->getElementType()))
12413 return InvalidOperands(Loc, LHS, RHS);
12414
12415 return Context.getConstantMatrixType(LHSMatType->getElementType(),
12416 LHSMatType->getNumRows(),
12417 RHSMatType->getNumColumns());
12418 }
12419 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12420 }
12421
CheckBitwiseOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)12422 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12423 SourceLocation Loc,
12424 BinaryOperatorKind Opc) {
12425 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12426
12427 bool IsCompAssign =
12428 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12429
12430 if (LHS.get()->getType()->isVectorType() ||
12431 RHS.get()->getType()->isVectorType()) {
12432 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12433 RHS.get()->getType()->hasIntegerRepresentation())
12434 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12435 /*AllowBothBool*/true,
12436 /*AllowBoolConversions*/getLangOpts().ZVector);
12437 return InvalidOperands(Loc, LHS, RHS);
12438 }
12439
12440 if (Opc == BO_And)
12441 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12442
12443 if (LHS.get()->getType()->hasFloatingRepresentation() ||
12444 RHS.get()->getType()->hasFloatingRepresentation())
12445 return InvalidOperands(Loc, LHS, RHS);
12446
12447 ExprResult LHSResult = LHS, RHSResult = RHS;
12448 QualType compType = UsualArithmeticConversions(
12449 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12450 if (LHSResult.isInvalid() || RHSResult.isInvalid())
12451 return QualType();
12452 LHS = LHSResult.get();
12453 RHS = RHSResult.get();
12454
12455 if (Opc == BO_Xor)
12456 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12457
12458 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12459 return compType;
12460 return InvalidOperands(Loc, LHS, RHS);
12461 }
12462
12463 // C99 6.5.[13,14]
CheckLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)12464 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12465 SourceLocation Loc,
12466 BinaryOperatorKind Opc) {
12467 // Check vector operands differently.
12468 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12469 return CheckVectorLogicalOperands(LHS, RHS, Loc);
12470
12471 bool EnumConstantInBoolContext = false;
12472 for (const ExprResult &HS : {LHS, RHS}) {
12473 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12474 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12475 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12476 EnumConstantInBoolContext = true;
12477 }
12478 }
12479
12480 if (EnumConstantInBoolContext)
12481 Diag(Loc, diag::warn_enum_constant_in_bool_context);
12482
12483 // Diagnose cases where the user write a logical and/or but probably meant a
12484 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
12485 // is a constant.
12486 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12487 !LHS.get()->getType()->isBooleanType() &&
12488 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12489 // Don't warn in macros or template instantiations.
12490 !Loc.isMacroID() && !inTemplateInstantiation()) {
12491 // If the RHS can be constant folded, and if it constant folds to something
12492 // that isn't 0 or 1 (which indicate a potential logical operation that
12493 // happened to fold to true/false) then warn.
12494 // Parens on the RHS are ignored.
12495 Expr::EvalResult EVResult;
12496 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12497 llvm::APSInt Result = EVResult.Val.getInt();
12498 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12499 !RHS.get()->getExprLoc().isMacroID()) ||
12500 (Result != 0 && Result != 1)) {
12501 Diag(Loc, diag::warn_logical_instead_of_bitwise)
12502 << RHS.get()->getSourceRange()
12503 << (Opc == BO_LAnd ? "&&" : "||");
12504 // Suggest replacing the logical operator with the bitwise version
12505 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12506 << (Opc == BO_LAnd ? "&" : "|")
12507 << FixItHint::CreateReplacement(SourceRange(
12508 Loc, getLocForEndOfToken(Loc)),
12509 Opc == BO_LAnd ? "&" : "|");
12510 if (Opc == BO_LAnd)
12511 // Suggest replacing "Foo() && kNonZero" with "Foo()"
12512 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12513 << FixItHint::CreateRemoval(
12514 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12515 RHS.get()->getEndLoc()));
12516 }
12517 }
12518 }
12519
12520 if (!Context.getLangOpts().CPlusPlus) {
12521 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12522 // not operate on the built-in scalar and vector float types.
12523 if (Context.getLangOpts().OpenCL &&
12524 Context.getLangOpts().OpenCLVersion < 120) {
12525 if (LHS.get()->getType()->isFloatingType() ||
12526 RHS.get()->getType()->isFloatingType())
12527 return InvalidOperands(Loc, LHS, RHS);
12528 }
12529
12530 LHS = UsualUnaryConversions(LHS.get());
12531 if (LHS.isInvalid())
12532 return QualType();
12533
12534 RHS = UsualUnaryConversions(RHS.get());
12535 if (RHS.isInvalid())
12536 return QualType();
12537
12538 if (!LHS.get()->getType()->isScalarType() ||
12539 !RHS.get()->getType()->isScalarType())
12540 return InvalidOperands(Loc, LHS, RHS);
12541
12542 return Context.IntTy;
12543 }
12544
12545 // The following is safe because we only use this method for
12546 // non-overloadable operands.
12547
12548 // C++ [expr.log.and]p1
12549 // C++ [expr.log.or]p1
12550 // The operands are both contextually converted to type bool.
12551 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12552 if (LHSRes.isInvalid())
12553 return InvalidOperands(Loc, LHS, RHS);
12554 LHS = LHSRes;
12555
12556 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12557 if (RHSRes.isInvalid())
12558 return InvalidOperands(Loc, LHS, RHS);
12559 RHS = RHSRes;
12560
12561 // C++ [expr.log.and]p2
12562 // C++ [expr.log.or]p2
12563 // The result is a bool.
12564 return Context.BoolTy;
12565 }
12566
IsReadonlyMessage(Expr * E,Sema & S)12567 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12568 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12569 if (!ME) return false;
12570 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12571 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12572 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12573 if (!Base) return false;
12574 return Base->getMethodDecl() != nullptr;
12575 }
12576
12577 /// Is the given expression (which must be 'const') a reference to a
12578 /// variable which was originally non-const, but which has become
12579 /// 'const' due to being captured within a block?
12580 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
isReferenceToNonConstCapture(Sema & S,Expr * E)12581 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12582 assert(E->isLValue() && E->getType().isConstQualified());
12583 E = E->IgnoreParens();
12584
12585 // Must be a reference to a declaration from an enclosing scope.
12586 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12587 if (!DRE) return NCCK_None;
12588 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12589
12590 // The declaration must be a variable which is not declared 'const'.
12591 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12592 if (!var) return NCCK_None;
12593 if (var->getType().isConstQualified()) return NCCK_None;
12594 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12595
12596 // Decide whether the first capture was for a block or a lambda.
12597 DeclContext *DC = S.CurContext, *Prev = nullptr;
12598 // Decide whether the first capture was for a block or a lambda.
12599 while (DC) {
12600 // For init-capture, it is possible that the variable belongs to the
12601 // template pattern of the current context.
12602 if (auto *FD = dyn_cast<FunctionDecl>(DC))
12603 if (var->isInitCapture() &&
12604 FD->getTemplateInstantiationPattern() == var->getDeclContext())
12605 break;
12606 if (DC == var->getDeclContext())
12607 break;
12608 Prev = DC;
12609 DC = DC->getParent();
12610 }
12611 // Unless we have an init-capture, we've gone one step too far.
12612 if (!var->isInitCapture())
12613 DC = Prev;
12614 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12615 }
12616
IsTypeModifiable(QualType Ty,bool IsDereference)12617 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12618 Ty = Ty.getNonReferenceType();
12619 if (IsDereference && Ty->isPointerType())
12620 Ty = Ty->getPointeeType();
12621 return !Ty.isConstQualified();
12622 }
12623
12624 // Update err_typecheck_assign_const and note_typecheck_assign_const
12625 // when this enum is changed.
12626 enum {
12627 ConstFunction,
12628 ConstVariable,
12629 ConstMember,
12630 ConstMethod,
12631 NestedConstMember,
12632 ConstUnknown, // Keep as last element
12633 };
12634
12635 /// Emit the "read-only variable not assignable" error and print notes to give
12636 /// more information about why the variable is not assignable, such as pointing
12637 /// to the declaration of a const variable, showing that a method is const, or
12638 /// that the function is returning a const reference.
DiagnoseConstAssignment(Sema & S,const Expr * E,SourceLocation Loc)12639 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12640 SourceLocation Loc) {
12641 SourceRange ExprRange = E->getSourceRange();
12642
12643 // Only emit one error on the first const found. All other consts will emit
12644 // a note to the error.
12645 bool DiagnosticEmitted = false;
12646
12647 // Track if the current expression is the result of a dereference, and if the
12648 // next checked expression is the result of a dereference.
12649 bool IsDereference = false;
12650 bool NextIsDereference = false;
12651
12652 // Loop to process MemberExpr chains.
12653 while (true) {
12654 IsDereference = NextIsDereference;
12655
12656 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12657 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12658 NextIsDereference = ME->isArrow();
12659 const ValueDecl *VD = ME->getMemberDecl();
12660 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12661 // Mutable fields can be modified even if the class is const.
12662 if (Field->isMutable()) {
12663 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12664 break;
12665 }
12666
12667 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12668 if (!DiagnosticEmitted) {
12669 S.Diag(Loc, diag::err_typecheck_assign_const)
12670 << ExprRange << ConstMember << false /*static*/ << Field
12671 << Field->getType();
12672 DiagnosticEmitted = true;
12673 }
12674 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12675 << ConstMember << false /*static*/ << Field << Field->getType()
12676 << Field->getSourceRange();
12677 }
12678 E = ME->getBase();
12679 continue;
12680 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12681 if (VDecl->getType().isConstQualified()) {
12682 if (!DiagnosticEmitted) {
12683 S.Diag(Loc, diag::err_typecheck_assign_const)
12684 << ExprRange << ConstMember << true /*static*/ << VDecl
12685 << VDecl->getType();
12686 DiagnosticEmitted = true;
12687 }
12688 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12689 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12690 << VDecl->getSourceRange();
12691 }
12692 // Static fields do not inherit constness from parents.
12693 break;
12694 }
12695 break; // End MemberExpr
12696 } else if (const ArraySubscriptExpr *ASE =
12697 dyn_cast<ArraySubscriptExpr>(E)) {
12698 E = ASE->getBase()->IgnoreParenImpCasts();
12699 continue;
12700 } else if (const ExtVectorElementExpr *EVE =
12701 dyn_cast<ExtVectorElementExpr>(E)) {
12702 E = EVE->getBase()->IgnoreParenImpCasts();
12703 continue;
12704 }
12705 break;
12706 }
12707
12708 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12709 // Function calls
12710 const FunctionDecl *FD = CE->getDirectCallee();
12711 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12712 if (!DiagnosticEmitted) {
12713 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12714 << ConstFunction << FD;
12715 DiagnosticEmitted = true;
12716 }
12717 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12718 diag::note_typecheck_assign_const)
12719 << ConstFunction << FD << FD->getReturnType()
12720 << FD->getReturnTypeSourceRange();
12721 }
12722 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12723 // Point to variable declaration.
12724 if (const ValueDecl *VD = DRE->getDecl()) {
12725 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12726 if (!DiagnosticEmitted) {
12727 S.Diag(Loc, diag::err_typecheck_assign_const)
12728 << ExprRange << ConstVariable << VD << VD->getType();
12729 DiagnosticEmitted = true;
12730 }
12731 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12732 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12733 }
12734 }
12735 } else if (isa<CXXThisExpr>(E)) {
12736 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12737 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12738 if (MD->isConst()) {
12739 if (!DiagnosticEmitted) {
12740 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12741 << ConstMethod << MD;
12742 DiagnosticEmitted = true;
12743 }
12744 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12745 << ConstMethod << MD << MD->getSourceRange();
12746 }
12747 }
12748 }
12749 }
12750
12751 if (DiagnosticEmitted)
12752 return;
12753
12754 // Can't determine a more specific message, so display the generic error.
12755 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12756 }
12757
12758 enum OriginalExprKind {
12759 OEK_Variable,
12760 OEK_Member,
12761 OEK_LValue
12762 };
12763
DiagnoseRecursiveConstFields(Sema & S,const ValueDecl * VD,const RecordType * Ty,SourceLocation Loc,SourceRange Range,OriginalExprKind OEK,bool & DiagnosticEmitted)12764 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12765 const RecordType *Ty,
12766 SourceLocation Loc, SourceRange Range,
12767 OriginalExprKind OEK,
12768 bool &DiagnosticEmitted) {
12769 std::vector<const RecordType *> RecordTypeList;
12770 RecordTypeList.push_back(Ty);
12771 unsigned NextToCheckIndex = 0;
12772 // We walk the record hierarchy breadth-first to ensure that we print
12773 // diagnostics in field nesting order.
12774 while (RecordTypeList.size() > NextToCheckIndex) {
12775 bool IsNested = NextToCheckIndex > 0;
12776 for (const FieldDecl *Field :
12777 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12778 // First, check every field for constness.
12779 QualType FieldTy = Field->getType();
12780 if (FieldTy.isConstQualified()) {
12781 if (!DiagnosticEmitted) {
12782 S.Diag(Loc, diag::err_typecheck_assign_const)
12783 << Range << NestedConstMember << OEK << VD
12784 << IsNested << Field;
12785 DiagnosticEmitted = true;
12786 }
12787 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12788 << NestedConstMember << IsNested << Field
12789 << FieldTy << Field->getSourceRange();
12790 }
12791
12792 // Then we append it to the list to check next in order.
12793 FieldTy = FieldTy.getCanonicalType();
12794 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12795 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12796 RecordTypeList.push_back(FieldRecTy);
12797 }
12798 }
12799 ++NextToCheckIndex;
12800 }
12801 }
12802
12803 /// Emit an error for the case where a record we are trying to assign to has a
12804 /// const-qualified field somewhere in its hierarchy.
DiagnoseRecursiveConstFields(Sema & S,const Expr * E,SourceLocation Loc)12805 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12806 SourceLocation Loc) {
12807 QualType Ty = E->getType();
12808 assert(Ty->isRecordType() && "lvalue was not record?");
12809 SourceRange Range = E->getSourceRange();
12810 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12811 bool DiagEmitted = false;
12812
12813 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12814 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12815 Range, OEK_Member, DiagEmitted);
12816 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12817 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12818 Range, OEK_Variable, DiagEmitted);
12819 else
12820 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12821 Range, OEK_LValue, DiagEmitted);
12822 if (!DiagEmitted)
12823 DiagnoseConstAssignment(S, E, Loc);
12824 }
12825
12826 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
12827 /// emit an error and return true. If so, return false.
CheckForModifiableLvalue(Expr * E,SourceLocation Loc,Sema & S)12828 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12829 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12830
12831 S.CheckShadowingDeclModification(E, Loc);
12832
12833 SourceLocation OrigLoc = Loc;
12834 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12835 &Loc);
12836 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12837 IsLV = Expr::MLV_InvalidMessageExpression;
12838 if (IsLV == Expr::MLV_Valid)
12839 return false;
12840
12841 unsigned DiagID = 0;
12842 bool NeedType = false;
12843 switch (IsLV) { // C99 6.5.16p2
12844 case Expr::MLV_ConstQualified:
12845 // Use a specialized diagnostic when we're assigning to an object
12846 // from an enclosing function or block.
12847 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12848 if (NCCK == NCCK_Block)
12849 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12850 else
12851 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12852 break;
12853 }
12854
12855 // In ARC, use some specialized diagnostics for occasions where we
12856 // infer 'const'. These are always pseudo-strong variables.
12857 if (S.getLangOpts().ObjCAutoRefCount) {
12858 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12859 if (declRef && isa<VarDecl>(declRef->getDecl())) {
12860 VarDecl *var = cast<VarDecl>(declRef->getDecl());
12861
12862 // Use the normal diagnostic if it's pseudo-__strong but the
12863 // user actually wrote 'const'.
12864 if (var->isARCPseudoStrong() &&
12865 (!var->getTypeSourceInfo() ||
12866 !var->getTypeSourceInfo()->getType().isConstQualified())) {
12867 // There are three pseudo-strong cases:
12868 // - self
12869 ObjCMethodDecl *method = S.getCurMethodDecl();
12870 if (method && var == method->getSelfDecl()) {
12871 DiagID = method->isClassMethod()
12872 ? diag::err_typecheck_arc_assign_self_class_method
12873 : diag::err_typecheck_arc_assign_self;
12874
12875 // - Objective-C externally_retained attribute.
12876 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12877 isa<ParmVarDecl>(var)) {
12878 DiagID = diag::err_typecheck_arc_assign_externally_retained;
12879
12880 // - fast enumeration variables
12881 } else {
12882 DiagID = diag::err_typecheck_arr_assign_enumeration;
12883 }
12884
12885 SourceRange Assign;
12886 if (Loc != OrigLoc)
12887 Assign = SourceRange(OrigLoc, OrigLoc);
12888 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12889 // We need to preserve the AST regardless, so migration tool
12890 // can do its job.
12891 return false;
12892 }
12893 }
12894 }
12895
12896 // If none of the special cases above are triggered, then this is a
12897 // simple const assignment.
12898 if (DiagID == 0) {
12899 DiagnoseConstAssignment(S, E, Loc);
12900 return true;
12901 }
12902
12903 break;
12904 case Expr::MLV_ConstAddrSpace:
12905 DiagnoseConstAssignment(S, E, Loc);
12906 return true;
12907 case Expr::MLV_ConstQualifiedField:
12908 DiagnoseRecursiveConstFields(S, E, Loc);
12909 return true;
12910 case Expr::MLV_ArrayType:
12911 case Expr::MLV_ArrayTemporary:
12912 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12913 NeedType = true;
12914 break;
12915 case Expr::MLV_NotObjectType:
12916 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12917 NeedType = true;
12918 break;
12919 case Expr::MLV_LValueCast:
12920 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12921 break;
12922 case Expr::MLV_Valid:
12923 llvm_unreachable("did not take early return for MLV_Valid");
12924 case Expr::MLV_InvalidExpression:
12925 case Expr::MLV_MemberFunction:
12926 case Expr::MLV_ClassTemporary:
12927 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12928 break;
12929 case Expr::MLV_IncompleteType:
12930 case Expr::MLV_IncompleteVoidType:
12931 return S.RequireCompleteType(Loc, E->getType(),
12932 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12933 case Expr::MLV_DuplicateVectorComponents:
12934 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12935 break;
12936 case Expr::MLV_NoSetterProperty:
12937 llvm_unreachable("readonly properties should be processed differently");
12938 case Expr::MLV_InvalidMessageExpression:
12939 DiagID = diag::err_readonly_message_assignment;
12940 break;
12941 case Expr::MLV_SubObjCPropertySetting:
12942 DiagID = diag::err_no_subobject_property_setting;
12943 break;
12944 }
12945
12946 SourceRange Assign;
12947 if (Loc != OrigLoc)
12948 Assign = SourceRange(OrigLoc, OrigLoc);
12949 if (NeedType)
12950 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12951 else
12952 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12953 return true;
12954 }
12955
CheckIdentityFieldAssignment(Expr * LHSExpr,Expr * RHSExpr,SourceLocation Loc,Sema & Sema)12956 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12957 SourceLocation Loc,
12958 Sema &Sema) {
12959 if (Sema.inTemplateInstantiation())
12960 return;
12961 if (Sema.isUnevaluatedContext())
12962 return;
12963 if (Loc.isInvalid() || Loc.isMacroID())
12964 return;
12965 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12966 return;
12967
12968 // C / C++ fields
12969 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12970 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12971 if (ML && MR) {
12972 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12973 return;
12974 const ValueDecl *LHSDecl =
12975 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12976 const ValueDecl *RHSDecl =
12977 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12978 if (LHSDecl != RHSDecl)
12979 return;
12980 if (LHSDecl->getType().isVolatileQualified())
12981 return;
12982 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12983 if (RefTy->getPointeeType().isVolatileQualified())
12984 return;
12985
12986 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12987 }
12988
12989 // Objective-C instance variables
12990 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12991 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12992 if (OL && OR && OL->getDecl() == OR->getDecl()) {
12993 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12994 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12995 if (RL && RR && RL->getDecl() == RR->getDecl())
12996 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12997 }
12998 }
12999
13000 // C99 6.5.16.1
CheckAssignmentOperands(Expr * LHSExpr,ExprResult & RHS,SourceLocation Loc,QualType CompoundType)13001 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
13002 SourceLocation Loc,
13003 QualType CompoundType) {
13004 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13005
13006 // Verify that LHS is a modifiable lvalue, and emit error if not.
13007 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13008 return QualType();
13009
13010 QualType LHSType = LHSExpr->getType();
13011 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13012 CompoundType;
13013 // OpenCL v1.2 s6.1.1.1 p2:
13014 // The half data type can only be used to declare a pointer to a buffer that
13015 // contains half values
13016 if (getLangOpts().OpenCL &&
13017 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13018 LHSType->isHalfType()) {
13019 Diag(Loc, diag::err_opencl_half_load_store) << 1
13020 << LHSType.getUnqualifiedType();
13021 return QualType();
13022 }
13023
13024 AssignConvertType ConvTy;
13025 if (CompoundType.isNull()) {
13026 Expr *RHSCheck = RHS.get();
13027
13028 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13029
13030 QualType LHSTy(LHSType);
13031 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13032 if (RHS.isInvalid())
13033 return QualType();
13034 // Special case of NSObject attributes on c-style pointer types.
13035 if (ConvTy == IncompatiblePointer &&
13036 ((Context.isObjCNSObjectType(LHSType) &&
13037 RHSType->isObjCObjectPointerType()) ||
13038 (Context.isObjCNSObjectType(RHSType) &&
13039 LHSType->isObjCObjectPointerType())))
13040 ConvTy = Compatible;
13041
13042 if (ConvTy == Compatible &&
13043 LHSType->isObjCObjectType())
13044 Diag(Loc, diag::err_objc_object_assignment)
13045 << LHSType;
13046
13047 // If the RHS is a unary plus or minus, check to see if they = and + are
13048 // right next to each other. If so, the user may have typo'd "x =+ 4"
13049 // instead of "x += 4".
13050 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13051 RHSCheck = ICE->getSubExpr();
13052 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13053 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13054 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13055 // Only if the two operators are exactly adjacent.
13056 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13057 // And there is a space or other character before the subexpr of the
13058 // unary +/-. We don't want to warn on "x=-1".
13059 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13060 UO->getSubExpr()->getBeginLoc().isFileID()) {
13061 Diag(Loc, diag::warn_not_compound_assign)
13062 << (UO->getOpcode() == UO_Plus ? "+" : "-")
13063 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13064 }
13065 }
13066
13067 if (ConvTy == Compatible) {
13068 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13069 // Warn about retain cycles where a block captures the LHS, but
13070 // not if the LHS is a simple variable into which the block is
13071 // being stored...unless that variable can be captured by reference!
13072 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13073 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13074 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13075 checkRetainCycles(LHSExpr, RHS.get());
13076 }
13077
13078 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13079 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
13080 // It is safe to assign a weak reference into a strong variable.
13081 // Although this code can still have problems:
13082 // id x = self.weakProp;
13083 // id y = self.weakProp;
13084 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13085 // paths through the function. This should be revisited if
13086 // -Wrepeated-use-of-weak is made flow-sensitive.
13087 // For ObjCWeak only, we do not warn if the assign is to a non-weak
13088 // variable, which will be valid for the current autorelease scope.
13089 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13090 RHS.get()->getBeginLoc()))
13091 getCurFunction()->markSafeWeakUse(RHS.get());
13092
13093 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13094 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13095 }
13096 }
13097 } else {
13098 // Compound assignment "x += y"
13099 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13100 }
13101
13102 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13103 RHS.get(), AA_Assigning))
13104 return QualType();
13105
13106 CheckForNullPointerDereference(*this, LHSExpr);
13107
13108 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13109 if (CompoundType.isNull()) {
13110 // C++2a [expr.ass]p5:
13111 // A simple-assignment whose left operand is of a volatile-qualified
13112 // type is deprecated unless the assignment is either a discarded-value
13113 // expression or an unevaluated operand
13114 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13115 } else {
13116 // C++2a [expr.ass]p6:
13117 // [Compound-assignment] expressions are deprecated if E1 has
13118 // volatile-qualified type
13119 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13120 }
13121 }
13122
13123 // C99 6.5.16p3: The type of an assignment expression is the type of the
13124 // left operand unless the left operand has qualified type, in which case
13125 // it is the unqualified version of the type of the left operand.
13126 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
13127 // is converted to the type of the assignment expression (above).
13128 // C++ 5.17p1: the type of the assignment expression is that of its left
13129 // operand.
13130 return (getLangOpts().CPlusPlus
13131 ? LHSType : LHSType.getUnqualifiedType());
13132 }
13133
13134 // Only ignore explicit casts to void.
IgnoreCommaOperand(const Expr * E)13135 static bool IgnoreCommaOperand(const Expr *E) {
13136 E = E->IgnoreParens();
13137
13138 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13139 if (CE->getCastKind() == CK_ToVoid) {
13140 return true;
13141 }
13142
13143 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13144 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13145 CE->getSubExpr()->getType()->isDependentType()) {
13146 return true;
13147 }
13148 }
13149
13150 return false;
13151 }
13152
13153 // Look for instances where it is likely the comma operator is confused with
13154 // another operator. There is an explicit list of acceptable expressions for
13155 // the left hand side of the comma operator, otherwise emit a warning.
DiagnoseCommaOperator(const Expr * LHS,SourceLocation Loc)13156 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13157 // No warnings in macros
13158 if (Loc.isMacroID())
13159 return;
13160
13161 // Don't warn in template instantiations.
13162 if (inTemplateInstantiation())
13163 return;
13164
13165 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13166 // instead, skip more than needed, then call back into here with the
13167 // CommaVisitor in SemaStmt.cpp.
13168 // The listed locations are the initialization and increment portions
13169 // of a for loop. The additional checks are on the condition of
13170 // if statements, do/while loops, and for loops.
13171 // Differences in scope flags for C89 mode requires the extra logic.
13172 const unsigned ForIncrementFlags =
13173 getLangOpts().C99 || getLangOpts().CPlusPlus
13174 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13175 : Scope::ContinueScope | Scope::BreakScope;
13176 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13177 const unsigned ScopeFlags = getCurScope()->getFlags();
13178 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13179 (ScopeFlags & ForInitFlags) == ForInitFlags)
13180 return;
13181
13182 // If there are multiple comma operators used together, get the RHS of the
13183 // of the comma operator as the LHS.
13184 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13185 if (BO->getOpcode() != BO_Comma)
13186 break;
13187 LHS = BO->getRHS();
13188 }
13189
13190 // Only allow some expressions on LHS to not warn.
13191 if (IgnoreCommaOperand(LHS))
13192 return;
13193
13194 Diag(Loc, diag::warn_comma_operator);
13195 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13196 << LHS->getSourceRange()
13197 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13198 LangOpts.CPlusPlus ? "static_cast<void>("
13199 : "(void)(")
13200 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13201 ")");
13202 }
13203
13204 // C99 6.5.17
CheckCommaOperands(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)13205 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13206 SourceLocation Loc) {
13207 LHS = S.CheckPlaceholderExpr(LHS.get());
13208 RHS = S.CheckPlaceholderExpr(RHS.get());
13209 if (LHS.isInvalid() || RHS.isInvalid())
13210 return QualType();
13211
13212 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13213 // operands, but not unary promotions.
13214 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13215
13216 // So we treat the LHS as a ignored value, and in C++ we allow the
13217 // containing site to determine what should be done with the RHS.
13218 LHS = S.IgnoredValueConversions(LHS.get());
13219 if (LHS.isInvalid())
13220 return QualType();
13221
13222 S.DiagnoseUnusedExprResult(LHS.get());
13223
13224 if (!S.getLangOpts().CPlusPlus) {
13225 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13226 if (RHS.isInvalid())
13227 return QualType();
13228 if (!RHS.get()->getType()->isVoidType())
13229 S.RequireCompleteType(Loc, RHS.get()->getType(),
13230 diag::err_incomplete_type);
13231 }
13232
13233 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13234 S.DiagnoseCommaOperator(LHS.get(), Loc);
13235
13236 return RHS.get()->getType();
13237 }
13238
13239 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13240 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
CheckIncrementDecrementOperand(Sema & S,Expr * Op,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation OpLoc,bool IsInc,bool IsPrefix)13241 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13242 ExprValueKind &VK,
13243 ExprObjectKind &OK,
13244 SourceLocation OpLoc,
13245 bool IsInc, bool IsPrefix) {
13246 if (Op->isTypeDependent())
13247 return S.Context.DependentTy;
13248
13249 QualType ResType = Op->getType();
13250 // Atomic types can be used for increment / decrement where the non-atomic
13251 // versions can, so ignore the _Atomic() specifier for the purpose of
13252 // checking.
13253 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13254 ResType = ResAtomicType->getValueType();
13255
13256 assert(!ResType.isNull() && "no type for increment/decrement expression");
13257
13258 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13259 // Decrement of bool is not allowed.
13260 if (!IsInc) {
13261 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13262 return QualType();
13263 }
13264 // Increment of bool sets it to true, but is deprecated.
13265 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13266 : diag::warn_increment_bool)
13267 << Op->getSourceRange();
13268 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13269 // Error on enum increments and decrements in C++ mode
13270 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13271 return QualType();
13272 } else if (ResType->isRealType()) {
13273 // OK!
13274 } else if (ResType->isPointerType()) {
13275 // C99 6.5.2.4p2, 6.5.6p2
13276 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13277 return QualType();
13278 } else if (ResType->isObjCObjectPointerType()) {
13279 // On modern runtimes, ObjC pointer arithmetic is forbidden.
13280 // Otherwise, we just need a complete type.
13281 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13282 checkArithmeticOnObjCPointer(S, OpLoc, Op))
13283 return QualType();
13284 } else if (ResType->isAnyComplexType()) {
13285 // C99 does not support ++/-- on complex types, we allow as an extension.
13286 S.Diag(OpLoc, diag::ext_integer_increment_complex)
13287 << ResType << Op->getSourceRange();
13288 } else if (ResType->isPlaceholderType()) {
13289 ExprResult PR = S.CheckPlaceholderExpr(Op);
13290 if (PR.isInvalid()) return QualType();
13291 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13292 IsInc, IsPrefix);
13293 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13294 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13295 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13296 (ResType->castAs<VectorType>()->getVectorKind() !=
13297 VectorType::AltiVecBool)) {
13298 // The z vector extensions allow ++ and -- for non-bool vectors.
13299 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13300 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13301 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13302 } else {
13303 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13304 << ResType << int(IsInc) << Op->getSourceRange();
13305 return QualType();
13306 }
13307 // At this point, we know we have a real, complex or pointer type.
13308 // Now make sure the operand is a modifiable lvalue.
13309 if (CheckForModifiableLvalue(Op, OpLoc, S))
13310 return QualType();
13311 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13312 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13313 // An operand with volatile-qualified type is deprecated
13314 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13315 << IsInc << ResType;
13316 }
13317 // In C++, a prefix increment is the same type as the operand. Otherwise
13318 // (in C or with postfix), the increment is the unqualified type of the
13319 // operand.
13320 if (IsPrefix && S.getLangOpts().CPlusPlus) {
13321 VK = VK_LValue;
13322 OK = Op->getObjectKind();
13323 return ResType;
13324 } else {
13325 VK = VK_RValue;
13326 return ResType.getUnqualifiedType();
13327 }
13328 }
13329
13330
13331 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13332 /// This routine allows us to typecheck complex/recursive expressions
13333 /// where the declaration is needed for type checking. We only need to
13334 /// handle cases when the expression references a function designator
13335 /// or is an lvalue. Here are some examples:
13336 /// - &(x) => x
13337 /// - &*****f => f for f a function designator.
13338 /// - &s.xx => s
13339 /// - &s.zz[1].yy -> s, if zz is an array
13340 /// - *(x + 1) -> x, if x is an array
13341 /// - &"123"[2] -> 0
13342 /// - & __real__ x -> x
13343 ///
13344 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13345 /// members.
getPrimaryDecl(Expr * E)13346 static ValueDecl *getPrimaryDecl(Expr *E) {
13347 switch (E->getStmtClass()) {
13348 case Stmt::DeclRefExprClass:
13349 return cast<DeclRefExpr>(E)->getDecl();
13350 case Stmt::MemberExprClass:
13351 // If this is an arrow operator, the address is an offset from
13352 // the base's value, so the object the base refers to is
13353 // irrelevant.
13354 if (cast<MemberExpr>(E)->isArrow())
13355 return nullptr;
13356 // Otherwise, the expression refers to a part of the base
13357 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13358 case Stmt::ArraySubscriptExprClass: {
13359 // FIXME: This code shouldn't be necessary! We should catch the implicit
13360 // promotion of register arrays earlier.
13361 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13362 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13363 if (ICE->getSubExpr()->getType()->isArrayType())
13364 return getPrimaryDecl(ICE->getSubExpr());
13365 }
13366 return nullptr;
13367 }
13368 case Stmt::UnaryOperatorClass: {
13369 UnaryOperator *UO = cast<UnaryOperator>(E);
13370
13371 switch(UO->getOpcode()) {
13372 case UO_Real:
13373 case UO_Imag:
13374 case UO_Extension:
13375 return getPrimaryDecl(UO->getSubExpr());
13376 default:
13377 return nullptr;
13378 }
13379 }
13380 case Stmt::ParenExprClass:
13381 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13382 case Stmt::ImplicitCastExprClass:
13383 // If the result of an implicit cast is an l-value, we care about
13384 // the sub-expression; otherwise, the result here doesn't matter.
13385 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13386 case Stmt::CXXUuidofExprClass:
13387 return cast<CXXUuidofExpr>(E)->getGuidDecl();
13388 default:
13389 return nullptr;
13390 }
13391 }
13392
13393 namespace {
13394 enum {
13395 AO_Bit_Field = 0,
13396 AO_Vector_Element = 1,
13397 AO_Property_Expansion = 2,
13398 AO_Register_Variable = 3,
13399 AO_Matrix_Element = 4,
13400 AO_No_Error = 5
13401 };
13402 }
13403 /// Diagnose invalid operand for address of operations.
13404 ///
13405 /// \param Type The type of operand which cannot have its address taken.
diagnoseAddressOfInvalidType(Sema & S,SourceLocation Loc,Expr * E,unsigned Type)13406 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13407 Expr *E, unsigned Type) {
13408 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13409 }
13410
13411 /// CheckAddressOfOperand - The operand of & must be either a function
13412 /// designator or an lvalue designating an object. If it is an lvalue, the
13413 /// object cannot be declared with storage class register or be a bit field.
13414 /// Note: The usual conversions are *not* applied to the operand of the &
13415 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13416 /// In C++, the operand might be an overloaded function name, in which case
13417 /// we allow the '&' but retain the overloaded-function type.
CheckAddressOfOperand(ExprResult & OrigOp,SourceLocation OpLoc)13418 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13419 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13420 if (PTy->getKind() == BuiltinType::Overload) {
13421 Expr *E = OrigOp.get()->IgnoreParens();
13422 if (!isa<OverloadExpr>(E)) {
13423 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13424 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13425 << OrigOp.get()->getSourceRange();
13426 return QualType();
13427 }
13428
13429 OverloadExpr *Ovl = cast<OverloadExpr>(E);
13430 if (isa<UnresolvedMemberExpr>(Ovl))
13431 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13432 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13433 << OrigOp.get()->getSourceRange();
13434 return QualType();
13435 }
13436
13437 return Context.OverloadTy;
13438 }
13439
13440 if (PTy->getKind() == BuiltinType::UnknownAny)
13441 return Context.UnknownAnyTy;
13442
13443 if (PTy->getKind() == BuiltinType::BoundMember) {
13444 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13445 << OrigOp.get()->getSourceRange();
13446 return QualType();
13447 }
13448
13449 OrigOp = CheckPlaceholderExpr(OrigOp.get());
13450 if (OrigOp.isInvalid()) return QualType();
13451 }
13452
13453 if (OrigOp.get()->isTypeDependent())
13454 return Context.DependentTy;
13455
13456 assert(!OrigOp.get()->getType()->isPlaceholderType());
13457
13458 // Make sure to ignore parentheses in subsequent checks
13459 Expr *op = OrigOp.get()->IgnoreParens();
13460
13461 // In OpenCL captures for blocks called as lambda functions
13462 // are located in the private address space. Blocks used in
13463 // enqueue_kernel can be located in a different address space
13464 // depending on a vendor implementation. Thus preventing
13465 // taking an address of the capture to avoid invalid AS casts.
13466 if (LangOpts.OpenCL) {
13467 auto* VarRef = dyn_cast<DeclRefExpr>(op);
13468 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13469 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13470 return QualType();
13471 }
13472 }
13473
13474 if (getLangOpts().C99) {
13475 // Implement C99-only parts of addressof rules.
13476 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13477 if (uOp->getOpcode() == UO_Deref)
13478 // Per C99 6.5.3.2, the address of a deref always returns a valid result
13479 // (assuming the deref expression is valid).
13480 return uOp->getSubExpr()->getType();
13481 }
13482 // Technically, there should be a check for array subscript
13483 // expressions here, but the result of one is always an lvalue anyway.
13484 }
13485 ValueDecl *dcl = getPrimaryDecl(op);
13486
13487 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13488 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13489 op->getBeginLoc()))
13490 return QualType();
13491
13492 Expr::LValueClassification lval = op->ClassifyLValue(Context);
13493 unsigned AddressOfError = AO_No_Error;
13494
13495 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13496 bool sfinae = (bool)isSFINAEContext();
13497 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13498 : diag::ext_typecheck_addrof_temporary)
13499 << op->getType() << op->getSourceRange();
13500 if (sfinae)
13501 return QualType();
13502 // Materialize the temporary as an lvalue so that we can take its address.
13503 OrigOp = op =
13504 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13505 } else if (isa<ObjCSelectorExpr>(op)) {
13506 return Context.getPointerType(op->getType());
13507 } else if (lval == Expr::LV_MemberFunction) {
13508 // If it's an instance method, make a member pointer.
13509 // The expression must have exactly the form &A::foo.
13510
13511 // If the underlying expression isn't a decl ref, give up.
13512 if (!isa<DeclRefExpr>(op)) {
13513 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13514 << OrigOp.get()->getSourceRange();
13515 return QualType();
13516 }
13517 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13518 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13519
13520 // The id-expression was parenthesized.
13521 if (OrigOp.get() != DRE) {
13522 Diag(OpLoc, diag::err_parens_pointer_member_function)
13523 << OrigOp.get()->getSourceRange();
13524
13525 // The method was named without a qualifier.
13526 } else if (!DRE->getQualifier()) {
13527 if (MD->getParent()->getName().empty())
13528 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13529 << op->getSourceRange();
13530 else {
13531 SmallString<32> Str;
13532 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13533 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13534 << op->getSourceRange()
13535 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13536 }
13537 }
13538
13539 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13540 if (isa<CXXDestructorDecl>(MD))
13541 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13542
13543 QualType MPTy = Context.getMemberPointerType(
13544 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13545 // Under the MS ABI, lock down the inheritance model now.
13546 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13547 (void)isCompleteType(OpLoc, MPTy);
13548 return MPTy;
13549 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13550 // C99 6.5.3.2p1
13551 // The operand must be either an l-value or a function designator
13552 if (!op->getType()->isFunctionType()) {
13553 // Use a special diagnostic for loads from property references.
13554 if (isa<PseudoObjectExpr>(op)) {
13555 AddressOfError = AO_Property_Expansion;
13556 } else {
13557 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13558 << op->getType() << op->getSourceRange();
13559 return QualType();
13560 }
13561 }
13562 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13563 // The operand cannot be a bit-field
13564 AddressOfError = AO_Bit_Field;
13565 } else if (op->getObjectKind() == OK_VectorComponent) {
13566 // The operand cannot be an element of a vector
13567 AddressOfError = AO_Vector_Element;
13568 } else if (op->getObjectKind() == OK_MatrixComponent) {
13569 // The operand cannot be an element of a matrix.
13570 AddressOfError = AO_Matrix_Element;
13571 } else if (dcl) { // C99 6.5.3.2p1
13572 // We have an lvalue with a decl. Make sure the decl is not declared
13573 // with the register storage-class specifier.
13574 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13575 // in C++ it is not error to take address of a register
13576 // variable (c++03 7.1.1P3)
13577 if (vd->getStorageClass() == SC_Register &&
13578 !getLangOpts().CPlusPlus) {
13579 AddressOfError = AO_Register_Variable;
13580 }
13581 } else if (isa<MSPropertyDecl>(dcl)) {
13582 AddressOfError = AO_Property_Expansion;
13583 } else if (isa<FunctionTemplateDecl>(dcl)) {
13584 return Context.OverloadTy;
13585 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13586 // Okay: we can take the address of a field.
13587 // Could be a pointer to member, though, if there is an explicit
13588 // scope qualifier for the class.
13589 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13590 DeclContext *Ctx = dcl->getDeclContext();
13591 if (Ctx && Ctx->isRecord()) {
13592 if (dcl->getType()->isReferenceType()) {
13593 Diag(OpLoc,
13594 diag::err_cannot_form_pointer_to_member_of_reference_type)
13595 << dcl->getDeclName() << dcl->getType();
13596 return QualType();
13597 }
13598
13599 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13600 Ctx = Ctx->getParent();
13601
13602 QualType MPTy = Context.getMemberPointerType(
13603 op->getType(),
13604 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13605 // Under the MS ABI, lock down the inheritance model now.
13606 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13607 (void)isCompleteType(OpLoc, MPTy);
13608 return MPTy;
13609 }
13610 }
13611 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13612 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13613 llvm_unreachable("Unknown/unexpected decl type");
13614 }
13615
13616 if (AddressOfError != AO_No_Error) {
13617 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13618 return QualType();
13619 }
13620
13621 if (lval == Expr::LV_IncompleteVoidType) {
13622 // Taking the address of a void variable is technically illegal, but we
13623 // allow it in cases which are otherwise valid.
13624 // Example: "extern void x; void* y = &x;".
13625 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13626 }
13627
13628 // If the operand has type "type", the result has type "pointer to type".
13629 if (op->getType()->isObjCObjectType())
13630 return Context.getObjCObjectPointerType(op->getType());
13631
13632 CheckAddressOfPackedMember(op);
13633
13634 return Context.getPointerType(op->getType());
13635 }
13636
RecordModifiableNonNullParam(Sema & S,const Expr * Exp)13637 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13638 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13639 if (!DRE)
13640 return;
13641 const Decl *D = DRE->getDecl();
13642 if (!D)
13643 return;
13644 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13645 if (!Param)
13646 return;
13647 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13648 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13649 return;
13650 if (FunctionScopeInfo *FD = S.getCurFunction())
13651 if (!FD->ModifiedNonNullParams.count(Param))
13652 FD->ModifiedNonNullParams.insert(Param);
13653 }
13654
13655 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
CheckIndirectionOperand(Sema & S,Expr * Op,ExprValueKind & VK,SourceLocation OpLoc)13656 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13657 SourceLocation OpLoc) {
13658 if (Op->isTypeDependent())
13659 return S.Context.DependentTy;
13660
13661 ExprResult ConvResult = S.UsualUnaryConversions(Op);
13662 if (ConvResult.isInvalid())
13663 return QualType();
13664 Op = ConvResult.get();
13665 QualType OpTy = Op->getType();
13666 QualType Result;
13667
13668 if (isa<CXXReinterpretCastExpr>(Op)) {
13669 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13670 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13671 Op->getSourceRange());
13672 }
13673
13674 if (const PointerType *PT = OpTy->getAs<PointerType>())
13675 {
13676 Result = PT->getPointeeType();
13677 }
13678 else if (const ObjCObjectPointerType *OPT =
13679 OpTy->getAs<ObjCObjectPointerType>())
13680 Result = OPT->getPointeeType();
13681 else {
13682 ExprResult PR = S.CheckPlaceholderExpr(Op);
13683 if (PR.isInvalid()) return QualType();
13684 if (PR.get() != Op)
13685 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13686 }
13687
13688 if (Result.isNull()) {
13689 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13690 << OpTy << Op->getSourceRange();
13691 return QualType();
13692 }
13693
13694 // Note that per both C89 and C99, indirection is always legal, even if Result
13695 // is an incomplete type or void. It would be possible to warn about
13696 // dereferencing a void pointer, but it's completely well-defined, and such a
13697 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13698 // for pointers to 'void' but is fine for any other pointer type:
13699 //
13700 // C++ [expr.unary.op]p1:
13701 // [...] the expression to which [the unary * operator] is applied shall
13702 // be a pointer to an object type, or a pointer to a function type
13703 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13704 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13705 << OpTy << Op->getSourceRange();
13706
13707 // Dereferences are usually l-values...
13708 VK = VK_LValue;
13709
13710 // ...except that certain expressions are never l-values in C.
13711 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13712 VK = VK_RValue;
13713
13714 return Result;
13715 }
13716
ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind)13717 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13718 BinaryOperatorKind Opc;
13719 switch (Kind) {
13720 default: llvm_unreachable("Unknown binop!");
13721 case tok::periodstar: Opc = BO_PtrMemD; break;
13722 case tok::arrowstar: Opc = BO_PtrMemI; break;
13723 case tok::star: Opc = BO_Mul; break;
13724 case tok::slash: Opc = BO_Div; break;
13725 case tok::percent: Opc = BO_Rem; break;
13726 case tok::plus: Opc = BO_Add; break;
13727 case tok::minus: Opc = BO_Sub; break;
13728 case tok::lessless: Opc = BO_Shl; break;
13729 case tok::greatergreater: Opc = BO_Shr; break;
13730 case tok::lessequal: Opc = BO_LE; break;
13731 case tok::less: Opc = BO_LT; break;
13732 case tok::greaterequal: Opc = BO_GE; break;
13733 case tok::greater: Opc = BO_GT; break;
13734 case tok::exclaimequal: Opc = BO_NE; break;
13735 case tok::equalequal: Opc = BO_EQ; break;
13736 case tok::spaceship: Opc = BO_Cmp; break;
13737 case tok::amp: Opc = BO_And; break;
13738 case tok::caret: Opc = BO_Xor; break;
13739 case tok::pipe: Opc = BO_Or; break;
13740 case tok::ampamp: Opc = BO_LAnd; break;
13741 case tok::pipepipe: Opc = BO_LOr; break;
13742 case tok::equal: Opc = BO_Assign; break;
13743 case tok::starequal: Opc = BO_MulAssign; break;
13744 case tok::slashequal: Opc = BO_DivAssign; break;
13745 case tok::percentequal: Opc = BO_RemAssign; break;
13746 case tok::plusequal: Opc = BO_AddAssign; break;
13747 case tok::minusequal: Opc = BO_SubAssign; break;
13748 case tok::lesslessequal: Opc = BO_ShlAssign; break;
13749 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
13750 case tok::ampequal: Opc = BO_AndAssign; break;
13751 case tok::caretequal: Opc = BO_XorAssign; break;
13752 case tok::pipeequal: Opc = BO_OrAssign; break;
13753 case tok::comma: Opc = BO_Comma; break;
13754 }
13755 return Opc;
13756 }
13757
ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)13758 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13759 tok::TokenKind Kind) {
13760 UnaryOperatorKind Opc;
13761 switch (Kind) {
13762 default: llvm_unreachable("Unknown unary op!");
13763 case tok::plusplus: Opc = UO_PreInc; break;
13764 case tok::minusminus: Opc = UO_PreDec; break;
13765 case tok::amp: Opc = UO_AddrOf; break;
13766 case tok::star: Opc = UO_Deref; break;
13767 case tok::plus: Opc = UO_Plus; break;
13768 case tok::minus: Opc = UO_Minus; break;
13769 case tok::tilde: Opc = UO_Not; break;
13770 case tok::exclaim: Opc = UO_LNot; break;
13771 case tok::kw___real: Opc = UO_Real; break;
13772 case tok::kw___imag: Opc = UO_Imag; break;
13773 case tok::kw___extension__: Opc = UO_Extension; break;
13774 }
13775 return Opc;
13776 }
13777
13778 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13779 /// This warning suppressed in the event of macro expansions.
DiagnoseSelfAssignment(Sema & S,Expr * LHSExpr,Expr * RHSExpr,SourceLocation OpLoc,bool IsBuiltin)13780 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13781 SourceLocation OpLoc, bool IsBuiltin) {
13782 if (S.inTemplateInstantiation())
13783 return;
13784 if (S.isUnevaluatedContext())
13785 return;
13786 if (OpLoc.isInvalid() || OpLoc.isMacroID())
13787 return;
13788 LHSExpr = LHSExpr->IgnoreParenImpCasts();
13789 RHSExpr = RHSExpr->IgnoreParenImpCasts();
13790 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13791 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13792 if (!LHSDeclRef || !RHSDeclRef ||
13793 LHSDeclRef->getLocation().isMacroID() ||
13794 RHSDeclRef->getLocation().isMacroID())
13795 return;
13796 const ValueDecl *LHSDecl =
13797 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13798 const ValueDecl *RHSDecl =
13799 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13800 if (LHSDecl != RHSDecl)
13801 return;
13802 if (LHSDecl->getType().isVolatileQualified())
13803 return;
13804 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13805 if (RefTy->getPointeeType().isVolatileQualified())
13806 return;
13807
13808 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13809 : diag::warn_self_assignment_overloaded)
13810 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13811 << RHSExpr->getSourceRange();
13812 }
13813
13814 /// Check if a bitwise-& is performed on an Objective-C pointer. This
13815 /// is usually indicative of introspection within the Objective-C pointer.
checkObjCPointerIntrospection(Sema & S,ExprResult & L,ExprResult & R,SourceLocation OpLoc)13816 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13817 SourceLocation OpLoc) {
13818 if (!S.getLangOpts().ObjC)
13819 return;
13820
13821 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13822 const Expr *LHS = L.get();
13823 const Expr *RHS = R.get();
13824
13825 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13826 ObjCPointerExpr = LHS;
13827 OtherExpr = RHS;
13828 }
13829 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13830 ObjCPointerExpr = RHS;
13831 OtherExpr = LHS;
13832 }
13833
13834 // This warning is deliberately made very specific to reduce false
13835 // positives with logic that uses '&' for hashing. This logic mainly
13836 // looks for code trying to introspect into tagged pointers, which
13837 // code should generally never do.
13838 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13839 unsigned Diag = diag::warn_objc_pointer_masking;
13840 // Determine if we are introspecting the result of performSelectorXXX.
13841 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13842 // Special case messages to -performSelector and friends, which
13843 // can return non-pointer values boxed in a pointer value.
13844 // Some clients may wish to silence warnings in this subcase.
13845 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13846 Selector S = ME->getSelector();
13847 StringRef SelArg0 = S.getNameForSlot(0);
13848 if (SelArg0.startswith("performSelector"))
13849 Diag = diag::warn_objc_pointer_masking_performSelector;
13850 }
13851
13852 S.Diag(OpLoc, Diag)
13853 << ObjCPointerExpr->getSourceRange();
13854 }
13855 }
13856
getDeclFromExpr(Expr * E)13857 static NamedDecl *getDeclFromExpr(Expr *E) {
13858 if (!E)
13859 return nullptr;
13860 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13861 return DRE->getDecl();
13862 if (auto *ME = dyn_cast<MemberExpr>(E))
13863 return ME->getMemberDecl();
13864 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13865 return IRE->getDecl();
13866 return nullptr;
13867 }
13868
13869 // This helper function promotes a binary operator's operands (which are of a
13870 // half vector type) to a vector of floats and then truncates the result to
13871 // a vector of either half or short.
convertHalfVecBinOp(Sema & S,ExprResult LHS,ExprResult RHS,BinaryOperatorKind Opc,QualType ResultTy,ExprValueKind VK,ExprObjectKind OK,bool IsCompAssign,SourceLocation OpLoc,FPOptionsOverride FPFeatures)13872 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13873 BinaryOperatorKind Opc, QualType ResultTy,
13874 ExprValueKind VK, ExprObjectKind OK,
13875 bool IsCompAssign, SourceLocation OpLoc,
13876 FPOptionsOverride FPFeatures) {
13877 auto &Context = S.getASTContext();
13878 assert((isVector(ResultTy, Context.HalfTy) ||
13879 isVector(ResultTy, Context.ShortTy)) &&
13880 "Result must be a vector of half or short");
13881 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13882 isVector(RHS.get()->getType(), Context.HalfTy) &&
13883 "both operands expected to be a half vector");
13884
13885 RHS = convertVector(RHS.get(), Context.FloatTy, S);
13886 QualType BinOpResTy = RHS.get()->getType();
13887
13888 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13889 // change BinOpResTy to a vector of ints.
13890 if (isVector(ResultTy, Context.ShortTy))
13891 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13892
13893 if (IsCompAssign)
13894 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13895 ResultTy, VK, OK, OpLoc, FPFeatures,
13896 BinOpResTy, BinOpResTy);
13897
13898 LHS = convertVector(LHS.get(), Context.FloatTy, S);
13899 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13900 BinOpResTy, VK, OK, OpLoc, FPFeatures);
13901 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13902 }
13903
13904 static std::pair<ExprResult, ExprResult>
CorrectDelayedTyposInBinOp(Sema & S,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)13905 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13906 Expr *RHSExpr) {
13907 ExprResult LHS = LHSExpr, RHS = RHSExpr;
13908 if (!S.Context.isDependenceAllowed()) {
13909 // C cannot handle TypoExpr nodes on either side of a binop because it
13910 // doesn't handle dependent types properly, so make sure any TypoExprs have
13911 // been dealt with before checking the operands.
13912 LHS = S.CorrectDelayedTyposInExpr(LHS);
13913 RHS = S.CorrectDelayedTyposInExpr(
13914 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13915 [Opc, LHS](Expr *E) {
13916 if (Opc != BO_Assign)
13917 return ExprResult(E);
13918 // Avoid correcting the RHS to the same Expr as the LHS.
13919 Decl *D = getDeclFromExpr(E);
13920 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13921 });
13922 }
13923 return std::make_pair(LHS, RHS);
13924 }
13925
13926 /// Returns true if conversion between vectors of halfs and vectors of floats
13927 /// is needed.
needsConversionOfHalfVec(bool OpRequiresConversion,ASTContext & Ctx,Expr * E0,Expr * E1=nullptr)13928 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13929 Expr *E0, Expr *E1 = nullptr) {
13930 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13931 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13932 return false;
13933
13934 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13935 QualType Ty = E->IgnoreImplicit()->getType();
13936
13937 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13938 // to vectors of floats. Although the element type of the vectors is __fp16,
13939 // the vectors shouldn't be treated as storage-only types. See the
13940 // discussion here: https://reviews.llvm.org/rG825235c140e7
13941 if (const VectorType *VT = Ty->getAs<VectorType>()) {
13942 if (VT->getVectorKind() == VectorType::NeonVector)
13943 return false;
13944 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13945 }
13946 return false;
13947 };
13948
13949 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13950 }
13951
13952 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13953 /// operator @p Opc at location @c TokLoc. This routine only supports
13954 /// built-in operations; ActOnBinOp handles overloaded operators.
CreateBuiltinBinOp(SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)13955 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13956 BinaryOperatorKind Opc,
13957 Expr *LHSExpr, Expr *RHSExpr) {
13958 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13959 // The syntax only allows initializer lists on the RHS of assignment,
13960 // so we don't need to worry about accepting invalid code for
13961 // non-assignment operators.
13962 // C++11 5.17p9:
13963 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13964 // of x = {} is x = T().
13965 InitializationKind Kind = InitializationKind::CreateDirectList(
13966 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13967 InitializedEntity Entity =
13968 InitializedEntity::InitializeTemporary(LHSExpr->getType());
13969 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13970 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13971 if (Init.isInvalid())
13972 return Init;
13973 RHSExpr = Init.get();
13974 }
13975
13976 ExprResult LHS = LHSExpr, RHS = RHSExpr;
13977 QualType ResultTy; // Result type of the binary operator.
13978 // The following two variables are used for compound assignment operators
13979 QualType CompLHSTy; // Type of LHS after promotions for computation
13980 QualType CompResultTy; // Type of computation result
13981 ExprValueKind VK = VK_RValue;
13982 ExprObjectKind OK = OK_Ordinary;
13983 bool ConvertHalfVec = false;
13984
13985 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13986 if (!LHS.isUsable() || !RHS.isUsable())
13987 return ExprError();
13988
13989 if (getLangOpts().OpenCL) {
13990 QualType LHSTy = LHSExpr->getType();
13991 QualType RHSTy = RHSExpr->getType();
13992 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13993 // the ATOMIC_VAR_INIT macro.
13994 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13995 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13996 if (BO_Assign == Opc)
13997 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13998 else
13999 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14000 return ExprError();
14001 }
14002
14003 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14004 // only with a builtin functions and therefore should be disallowed here.
14005 if (LHSTy->isImageType() || RHSTy->isImageType() ||
14006 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14007 LHSTy->isPipeType() || RHSTy->isPipeType() ||
14008 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14009 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14010 return ExprError();
14011 }
14012 }
14013
14014 switch (Opc) {
14015 case BO_Assign:
14016 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
14017 if (getLangOpts().CPlusPlus &&
14018 LHS.get()->getObjectKind() != OK_ObjCProperty) {
14019 VK = LHS.get()->getValueKind();
14020 OK = LHS.get()->getObjectKind();
14021 }
14022 if (!ResultTy.isNull()) {
14023 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14024 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14025
14026 // Avoid copying a block to the heap if the block is assigned to a local
14027 // auto variable that is declared in the same scope as the block. This
14028 // optimization is unsafe if the local variable is declared in an outer
14029 // scope. For example:
14030 //
14031 // BlockTy b;
14032 // {
14033 // b = ^{...};
14034 // }
14035 // // It is unsafe to invoke the block here if it wasn't copied to the
14036 // // heap.
14037 // b();
14038
14039 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14040 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14041 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14042 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14043 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14044
14045 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
14046 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14047 NTCUC_Assignment, NTCUK_Copy);
14048 }
14049 RecordModifiableNonNullParam(*this, LHS.get());
14050 break;
14051 case BO_PtrMemD:
14052 case BO_PtrMemI:
14053 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14054 Opc == BO_PtrMemI);
14055 break;
14056 case BO_Mul:
14057 case BO_Div:
14058 ConvertHalfVec = true;
14059 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14060 Opc == BO_Div);
14061 break;
14062 case BO_Rem:
14063 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14064 break;
14065 case BO_Add:
14066 ConvertHalfVec = true;
14067 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14068 break;
14069 case BO_Sub:
14070 ConvertHalfVec = true;
14071 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14072 break;
14073 case BO_Shl:
14074 case BO_Shr:
14075 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14076 break;
14077 case BO_LE:
14078 case BO_LT:
14079 case BO_GE:
14080 case BO_GT:
14081 ConvertHalfVec = true;
14082 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14083 break;
14084 case BO_EQ:
14085 case BO_NE:
14086 ConvertHalfVec = true;
14087 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14088 break;
14089 case BO_Cmp:
14090 ConvertHalfVec = true;
14091 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14092 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14093 break;
14094 case BO_And:
14095 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14096 LLVM_FALLTHROUGH;
14097 case BO_Xor:
14098 case BO_Or:
14099 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14100 break;
14101 case BO_LAnd:
14102 case BO_LOr:
14103 ConvertHalfVec = true;
14104 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14105 break;
14106 case BO_MulAssign:
14107 case BO_DivAssign:
14108 ConvertHalfVec = true;
14109 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14110 Opc == BO_DivAssign);
14111 CompLHSTy = CompResultTy;
14112 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14113 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14114 break;
14115 case BO_RemAssign:
14116 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14117 CompLHSTy = CompResultTy;
14118 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14119 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14120 break;
14121 case BO_AddAssign:
14122 ConvertHalfVec = true;
14123 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14124 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14125 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14126 break;
14127 case BO_SubAssign:
14128 ConvertHalfVec = true;
14129 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14130 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14131 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14132 break;
14133 case BO_ShlAssign:
14134 case BO_ShrAssign:
14135 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14136 CompLHSTy = CompResultTy;
14137 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14138 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14139 break;
14140 case BO_AndAssign:
14141 case BO_OrAssign: // fallthrough
14142 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14143 LLVM_FALLTHROUGH;
14144 case BO_XorAssign:
14145 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14146 CompLHSTy = CompResultTy;
14147 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14148 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14149 break;
14150 case BO_Comma:
14151 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14152 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14153 VK = RHS.get()->getValueKind();
14154 OK = RHS.get()->getObjectKind();
14155 }
14156 break;
14157 }
14158 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14159 return ExprError();
14160
14161 // Some of the binary operations require promoting operands of half vector to
14162 // float vectors and truncating the result back to half vector. For now, we do
14163 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14164 // arm64).
14165 assert(
14166 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14167 isVector(LHS.get()->getType(), Context.HalfTy)) &&
14168 "both sides are half vectors or neither sides are");
14169 ConvertHalfVec =
14170 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14171
14172 // Check for array bounds violations for both sides of the BinaryOperator
14173 CheckArrayAccess(LHS.get());
14174 CheckArrayAccess(RHS.get());
14175
14176 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14177 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14178 &Context.Idents.get("object_setClass"),
14179 SourceLocation(), LookupOrdinaryName);
14180 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14181 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14182 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14183 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14184 "object_setClass(")
14185 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14186 ",")
14187 << FixItHint::CreateInsertion(RHSLocEnd, ")");
14188 }
14189 else
14190 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14191 }
14192 else if (const ObjCIvarRefExpr *OIRE =
14193 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14194 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14195
14196 // Opc is not a compound assignment if CompResultTy is null.
14197 if (CompResultTy.isNull()) {
14198 if (ConvertHalfVec)
14199 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14200 OpLoc, CurFPFeatureOverrides());
14201 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14202 VK, OK, OpLoc, CurFPFeatureOverrides());
14203 }
14204
14205 // Handle compound assignments.
14206 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14207 OK_ObjCProperty) {
14208 VK = VK_LValue;
14209 OK = LHS.get()->getObjectKind();
14210 }
14211
14212 // The LHS is not converted to the result type for fixed-point compound
14213 // assignment as the common type is computed on demand. Reset the CompLHSTy
14214 // to the LHS type we would have gotten after unary conversions.
14215 if (CompResultTy->isFixedPointType())
14216 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14217
14218 if (ConvertHalfVec)
14219 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14220 OpLoc, CurFPFeatureOverrides());
14221
14222 return CompoundAssignOperator::Create(
14223 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14224 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14225 }
14226
14227 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14228 /// operators are mixed in a way that suggests that the programmer forgot that
14229 /// comparison operators have higher precedence. The most typical example of
14230 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
DiagnoseBitwisePrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14231 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14232 SourceLocation OpLoc, Expr *LHSExpr,
14233 Expr *RHSExpr) {
14234 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14235 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14236
14237 // Check that one of the sides is a comparison operator and the other isn't.
14238 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14239 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14240 if (isLeftComp == isRightComp)
14241 return;
14242
14243 // Bitwise operations are sometimes used as eager logical ops.
14244 // Don't diagnose this.
14245 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14246 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14247 if (isLeftBitwise || isRightBitwise)
14248 return;
14249
14250 SourceRange DiagRange = isLeftComp
14251 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14252 : SourceRange(OpLoc, RHSExpr->getEndLoc());
14253 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14254 SourceRange ParensRange =
14255 isLeftComp
14256 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14257 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14258
14259 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14260 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14261 SuggestParentheses(Self, OpLoc,
14262 Self.PDiag(diag::note_precedence_silence) << OpStr,
14263 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14264 SuggestParentheses(Self, OpLoc,
14265 Self.PDiag(diag::note_precedence_bitwise_first)
14266 << BinaryOperator::getOpcodeStr(Opc),
14267 ParensRange);
14268 }
14269
14270 /// It accepts a '&&' expr that is inside a '||' one.
14271 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14272 /// in parentheses.
14273 static void
EmitDiagnosticForLogicalAndInLogicalOr(Sema & Self,SourceLocation OpLoc,BinaryOperator * Bop)14274 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14275 BinaryOperator *Bop) {
14276 assert(Bop->getOpcode() == BO_LAnd);
14277 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14278 << Bop->getSourceRange() << OpLoc;
14279 SuggestParentheses(Self, Bop->getOperatorLoc(),
14280 Self.PDiag(diag::note_precedence_silence)
14281 << Bop->getOpcodeStr(),
14282 Bop->getSourceRange());
14283 }
14284
14285 /// Returns true if the given expression can be evaluated as a constant
14286 /// 'true'.
EvaluatesAsTrue(Sema & S,Expr * E)14287 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14288 bool Res;
14289 return !E->isValueDependent() &&
14290 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14291 }
14292
14293 /// Returns true if the given expression can be evaluated as a constant
14294 /// 'false'.
EvaluatesAsFalse(Sema & S,Expr * E)14295 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14296 bool Res;
14297 return !E->isValueDependent() &&
14298 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14299 }
14300
14301 /// Look for '&&' in the left hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrLHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14302 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14303 Expr *LHSExpr, Expr *RHSExpr) {
14304 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14305 if (Bop->getOpcode() == BO_LAnd) {
14306 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14307 if (EvaluatesAsFalse(S, RHSExpr))
14308 return;
14309 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14310 if (!EvaluatesAsTrue(S, Bop->getLHS()))
14311 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14312 } else if (Bop->getOpcode() == BO_LOr) {
14313 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14314 // If it's "a || b && 1 || c" we didn't warn earlier for
14315 // "a || b && 1", but warn now.
14316 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14317 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14318 }
14319 }
14320 }
14321 }
14322
14323 /// Look for '&&' in the right hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrRHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14324 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14325 Expr *LHSExpr, Expr *RHSExpr) {
14326 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14327 if (Bop->getOpcode() == BO_LAnd) {
14328 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14329 if (EvaluatesAsFalse(S, LHSExpr))
14330 return;
14331 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14332 if (!EvaluatesAsTrue(S, Bop->getRHS()))
14333 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14334 }
14335 }
14336 }
14337
14338 /// Look for bitwise op in the left or right hand of a bitwise op with
14339 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14340 /// the '&' expression in parentheses.
DiagnoseBitwiseOpInBitwiseOp(Sema & S,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * SubExpr)14341 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14342 SourceLocation OpLoc, Expr *SubExpr) {
14343 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14344 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14345 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14346 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14347 << Bop->getSourceRange() << OpLoc;
14348 SuggestParentheses(S, Bop->getOperatorLoc(),
14349 S.PDiag(diag::note_precedence_silence)
14350 << Bop->getOpcodeStr(),
14351 Bop->getSourceRange());
14352 }
14353 }
14354 }
14355
DiagnoseAdditionInShift(Sema & S,SourceLocation OpLoc,Expr * SubExpr,StringRef Shift)14356 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14357 Expr *SubExpr, StringRef Shift) {
14358 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14359 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14360 StringRef Op = Bop->getOpcodeStr();
14361 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14362 << Bop->getSourceRange() << OpLoc << Shift << Op;
14363 SuggestParentheses(S, Bop->getOperatorLoc(),
14364 S.PDiag(diag::note_precedence_silence) << Op,
14365 Bop->getSourceRange());
14366 }
14367 }
14368 }
14369
DiagnoseShiftCompare(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14370 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14371 Expr *LHSExpr, Expr *RHSExpr) {
14372 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14373 if (!OCE)
14374 return;
14375
14376 FunctionDecl *FD = OCE->getDirectCallee();
14377 if (!FD || !FD->isOverloadedOperator())
14378 return;
14379
14380 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14381 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14382 return;
14383
14384 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14385 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14386 << (Kind == OO_LessLess);
14387 SuggestParentheses(S, OCE->getOperatorLoc(),
14388 S.PDiag(diag::note_precedence_silence)
14389 << (Kind == OO_LessLess ? "<<" : ">>"),
14390 OCE->getSourceRange());
14391 SuggestParentheses(
14392 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14393 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14394 }
14395
14396 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14397 /// precedence.
DiagnoseBinOpPrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14398 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14399 SourceLocation OpLoc, Expr *LHSExpr,
14400 Expr *RHSExpr){
14401 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14402 if (BinaryOperator::isBitwiseOp(Opc))
14403 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14404
14405 // Diagnose "arg1 & arg2 | arg3"
14406 if ((Opc == BO_Or || Opc == BO_Xor) &&
14407 !OpLoc.isMacroID()/* Don't warn in macros. */) {
14408 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14409 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14410 }
14411
14412 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14413 // We don't warn for 'assert(a || b && "bad")' since this is safe.
14414 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14415 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14416 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14417 }
14418
14419 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14420 || Opc == BO_Shr) {
14421 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14422 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14423 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14424 }
14425
14426 // Warn on overloaded shift operators and comparisons, such as:
14427 // cout << 5 == 4;
14428 if (BinaryOperator::isComparisonOp(Opc))
14429 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14430 }
14431
14432 // Binary Operators. 'Tok' is the token for the operator.
ActOnBinOp(Scope * S,SourceLocation TokLoc,tok::TokenKind Kind,Expr * LHSExpr,Expr * RHSExpr)14433 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14434 tok::TokenKind Kind,
14435 Expr *LHSExpr, Expr *RHSExpr) {
14436 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14437 assert(LHSExpr && "ActOnBinOp(): missing left expression");
14438 assert(RHSExpr && "ActOnBinOp(): missing right expression");
14439
14440 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14441 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14442
14443 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14444 }
14445
LookupBinOp(Scope * S,SourceLocation OpLoc,BinaryOperatorKind Opc,UnresolvedSetImpl & Functions)14446 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14447 UnresolvedSetImpl &Functions) {
14448 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14449 if (OverOp != OO_None && OverOp != OO_Equal)
14450 LookupOverloadedOperatorName(OverOp, S, Functions);
14451
14452 // In C++20 onwards, we may have a second operator to look up.
14453 if (getLangOpts().CPlusPlus20) {
14454 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14455 LookupOverloadedOperatorName(ExtraOp, S, Functions);
14456 }
14457 }
14458
14459 /// Build an overloaded binary operator expression in the given scope.
BuildOverloadedBinOp(Sema & S,Scope * Sc,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHS,Expr * RHS)14460 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14461 BinaryOperatorKind Opc,
14462 Expr *LHS, Expr *RHS) {
14463 switch (Opc) {
14464 case BO_Assign:
14465 case BO_DivAssign:
14466 case BO_RemAssign:
14467 case BO_SubAssign:
14468 case BO_AndAssign:
14469 case BO_OrAssign:
14470 case BO_XorAssign:
14471 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14472 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14473 break;
14474 default:
14475 break;
14476 }
14477
14478 // Find all of the overloaded operators visible from this point.
14479 UnresolvedSet<16> Functions;
14480 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14481
14482 // Build the (potentially-overloaded, potentially-dependent)
14483 // binary operation.
14484 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14485 }
14486
BuildBinOp(Scope * S,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)14487 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14488 BinaryOperatorKind Opc,
14489 Expr *LHSExpr, Expr *RHSExpr) {
14490 ExprResult LHS, RHS;
14491 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14492 if (!LHS.isUsable() || !RHS.isUsable())
14493 return ExprError();
14494 LHSExpr = LHS.get();
14495 RHSExpr = RHS.get();
14496
14497 // We want to end up calling one of checkPseudoObjectAssignment
14498 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14499 // both expressions are overloadable or either is type-dependent),
14500 // or CreateBuiltinBinOp (in any other case). We also want to get
14501 // any placeholder types out of the way.
14502
14503 // Handle pseudo-objects in the LHS.
14504 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14505 // Assignments with a pseudo-object l-value need special analysis.
14506 if (pty->getKind() == BuiltinType::PseudoObject &&
14507 BinaryOperator::isAssignmentOp(Opc))
14508 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14509
14510 // Don't resolve overloads if the other type is overloadable.
14511 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14512 // We can't actually test that if we still have a placeholder,
14513 // though. Fortunately, none of the exceptions we see in that
14514 // code below are valid when the LHS is an overload set. Note
14515 // that an overload set can be dependently-typed, but it never
14516 // instantiates to having an overloadable type.
14517 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14518 if (resolvedRHS.isInvalid()) return ExprError();
14519 RHSExpr = resolvedRHS.get();
14520
14521 if (RHSExpr->isTypeDependent() ||
14522 RHSExpr->getType()->isOverloadableType())
14523 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14524 }
14525
14526 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14527 // template, diagnose the missing 'template' keyword instead of diagnosing
14528 // an invalid use of a bound member function.
14529 //
14530 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14531 // to C++1z [over.over]/1.4, but we already checked for that case above.
14532 if (Opc == BO_LT && inTemplateInstantiation() &&
14533 (pty->getKind() == BuiltinType::BoundMember ||
14534 pty->getKind() == BuiltinType::Overload)) {
14535 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14536 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14537 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14538 return isa<FunctionTemplateDecl>(ND);
14539 })) {
14540 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14541 : OE->getNameLoc(),
14542 diag::err_template_kw_missing)
14543 << OE->getName().getAsString() << "";
14544 return ExprError();
14545 }
14546 }
14547
14548 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14549 if (LHS.isInvalid()) return ExprError();
14550 LHSExpr = LHS.get();
14551 }
14552
14553 // Handle pseudo-objects in the RHS.
14554 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14555 // An overload in the RHS can potentially be resolved by the type
14556 // being assigned to.
14557 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14558 if (getLangOpts().CPlusPlus &&
14559 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14560 LHSExpr->getType()->isOverloadableType()))
14561 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14562
14563 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14564 }
14565
14566 // Don't resolve overloads if the other type is overloadable.
14567 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14568 LHSExpr->getType()->isOverloadableType())
14569 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14570
14571 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14572 if (!resolvedRHS.isUsable()) return ExprError();
14573 RHSExpr = resolvedRHS.get();
14574 }
14575
14576 if (getLangOpts().CPlusPlus) {
14577 // If either expression is type-dependent, always build an
14578 // overloaded op.
14579 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14580 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14581
14582 // Otherwise, build an overloaded op if either expression has an
14583 // overloadable type.
14584 if (LHSExpr->getType()->isOverloadableType() ||
14585 RHSExpr->getType()->isOverloadableType())
14586 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14587 }
14588
14589 if (getLangOpts().RecoveryAST &&
14590 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
14591 assert(!getLangOpts().CPlusPlus);
14592 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
14593 "Should only occur in error-recovery path.");
14594 if (BinaryOperator::isCompoundAssignmentOp(Opc))
14595 // C [6.15.16] p3:
14596 // An assignment expression has the value of the left operand after the
14597 // assignment, but is not an lvalue.
14598 return CompoundAssignOperator::Create(
14599 Context, LHSExpr, RHSExpr, Opc,
14600 LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary,
14601 OpLoc, CurFPFeatureOverrides());
14602 QualType ResultType;
14603 switch (Opc) {
14604 case BO_Assign:
14605 ResultType = LHSExpr->getType().getUnqualifiedType();
14606 break;
14607 case BO_LT:
14608 case BO_GT:
14609 case BO_LE:
14610 case BO_GE:
14611 case BO_EQ:
14612 case BO_NE:
14613 case BO_LAnd:
14614 case BO_LOr:
14615 // These operators have a fixed result type regardless of operands.
14616 ResultType = Context.IntTy;
14617 break;
14618 case BO_Comma:
14619 ResultType = RHSExpr->getType();
14620 break;
14621 default:
14622 ResultType = Context.DependentTy;
14623 break;
14624 }
14625 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
14626 VK_RValue, OK_Ordinary, OpLoc,
14627 CurFPFeatureOverrides());
14628 }
14629
14630 // Build a built-in binary operation.
14631 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14632 }
14633
isOverflowingIntegerType(ASTContext & Ctx,QualType T)14634 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14635 if (T.isNull() || T->isDependentType())
14636 return false;
14637
14638 if (!T->isPromotableIntegerType())
14639 return true;
14640
14641 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14642 }
14643
CreateBuiltinUnaryOp(SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * InputExpr)14644 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14645 UnaryOperatorKind Opc,
14646 Expr *InputExpr) {
14647 ExprResult Input = InputExpr;
14648 ExprValueKind VK = VK_RValue;
14649 ExprObjectKind OK = OK_Ordinary;
14650 QualType resultType;
14651 bool CanOverflow = false;
14652
14653 bool ConvertHalfVec = false;
14654 if (getLangOpts().OpenCL) {
14655 QualType Ty = InputExpr->getType();
14656 // The only legal unary operation for atomics is '&'.
14657 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14658 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14659 // only with a builtin functions and therefore should be disallowed here.
14660 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14661 || Ty->isBlockPointerType())) {
14662 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14663 << InputExpr->getType()
14664 << Input.get()->getSourceRange());
14665 }
14666 }
14667
14668 switch (Opc) {
14669 case UO_PreInc:
14670 case UO_PreDec:
14671 case UO_PostInc:
14672 case UO_PostDec:
14673 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14674 OpLoc,
14675 Opc == UO_PreInc ||
14676 Opc == UO_PostInc,
14677 Opc == UO_PreInc ||
14678 Opc == UO_PreDec);
14679 CanOverflow = isOverflowingIntegerType(Context, resultType);
14680 break;
14681 case UO_AddrOf:
14682 resultType = CheckAddressOfOperand(Input, OpLoc);
14683 CheckAddressOfNoDeref(InputExpr);
14684 RecordModifiableNonNullParam(*this, InputExpr);
14685 break;
14686 case UO_Deref: {
14687 Input = DefaultFunctionArrayLvalueConversion(Input.get());
14688 if (Input.isInvalid()) return ExprError();
14689 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14690 break;
14691 }
14692 case UO_Plus:
14693 case UO_Minus:
14694 CanOverflow = Opc == UO_Minus &&
14695 isOverflowingIntegerType(Context, Input.get()->getType());
14696 Input = UsualUnaryConversions(Input.get());
14697 if (Input.isInvalid()) return ExprError();
14698 // Unary plus and minus require promoting an operand of half vector to a
14699 // float vector and truncating the result back to a half vector. For now, we
14700 // do this only when HalfArgsAndReturns is set (that is, when the target is
14701 // arm or arm64).
14702 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14703
14704 // If the operand is a half vector, promote it to a float vector.
14705 if (ConvertHalfVec)
14706 Input = convertVector(Input.get(), Context.FloatTy, *this);
14707 resultType = Input.get()->getType();
14708 if (resultType->isDependentType())
14709 break;
14710 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14711 break;
14712 else if (resultType->isVectorType() &&
14713 // The z vector extensions don't allow + or - with bool vectors.
14714 (!Context.getLangOpts().ZVector ||
14715 resultType->castAs<VectorType>()->getVectorKind() !=
14716 VectorType::AltiVecBool))
14717 break;
14718 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14719 Opc == UO_Plus &&
14720 resultType->isPointerType())
14721 break;
14722
14723 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14724 << resultType << Input.get()->getSourceRange());
14725
14726 case UO_Not: // bitwise complement
14727 Input = UsualUnaryConversions(Input.get());
14728 if (Input.isInvalid())
14729 return ExprError();
14730 resultType = Input.get()->getType();
14731 if (resultType->isDependentType())
14732 break;
14733 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14734 if (resultType->isComplexType() || resultType->isComplexIntegerType())
14735 // C99 does not support '~' for complex conjugation.
14736 Diag(OpLoc, diag::ext_integer_complement_complex)
14737 << resultType << Input.get()->getSourceRange();
14738 else if (resultType->hasIntegerRepresentation())
14739 break;
14740 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14741 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14742 // on vector float types.
14743 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14744 if (!T->isIntegerType())
14745 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14746 << resultType << Input.get()->getSourceRange());
14747 } else {
14748 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14749 << resultType << Input.get()->getSourceRange());
14750 }
14751 break;
14752
14753 case UO_LNot: // logical negation
14754 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14755 Input = DefaultFunctionArrayLvalueConversion(Input.get());
14756 if (Input.isInvalid()) return ExprError();
14757 resultType = Input.get()->getType();
14758
14759 // Though we still have to promote half FP to float...
14760 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14761 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14762 resultType = Context.FloatTy;
14763 }
14764
14765 if (resultType->isDependentType())
14766 break;
14767 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14768 // C99 6.5.3.3p1: ok, fallthrough;
14769 if (Context.getLangOpts().CPlusPlus) {
14770 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14771 // operand contextually converted to bool.
14772 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14773 ScalarTypeToBooleanCastKind(resultType));
14774 } else if (Context.getLangOpts().OpenCL &&
14775 Context.getLangOpts().OpenCLVersion < 120) {
14776 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14777 // operate on scalar float types.
14778 if (!resultType->isIntegerType() && !resultType->isPointerType())
14779 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14780 << resultType << Input.get()->getSourceRange());
14781 }
14782 } else if (resultType->isExtVectorType()) {
14783 if (Context.getLangOpts().OpenCL &&
14784 Context.getLangOpts().OpenCLVersion < 120 &&
14785 !Context.getLangOpts().OpenCLCPlusPlus) {
14786 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14787 // operate on vector float types.
14788 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14789 if (!T->isIntegerType())
14790 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14791 << resultType << Input.get()->getSourceRange());
14792 }
14793 // Vector logical not returns the signed variant of the operand type.
14794 resultType = GetSignedVectorType(resultType);
14795 break;
14796 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14797 const VectorType *VTy = resultType->castAs<VectorType>();
14798 if (VTy->getVectorKind() != VectorType::GenericVector)
14799 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14800 << resultType << Input.get()->getSourceRange());
14801
14802 // Vector logical not returns the signed variant of the operand type.
14803 resultType = GetSignedVectorType(resultType);
14804 break;
14805 } else {
14806 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14807 << resultType << Input.get()->getSourceRange());
14808 }
14809
14810 // LNot always has type int. C99 6.5.3.3p5.
14811 // In C++, it's bool. C++ 5.3.1p8
14812 resultType = Context.getLogicalOperationType();
14813 break;
14814 case UO_Real:
14815 case UO_Imag:
14816 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14817 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14818 // complex l-values to ordinary l-values and all other values to r-values.
14819 if (Input.isInvalid()) return ExprError();
14820 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14821 if (Input.get()->getValueKind() != VK_RValue &&
14822 Input.get()->getObjectKind() == OK_Ordinary)
14823 VK = Input.get()->getValueKind();
14824 } else if (!getLangOpts().CPlusPlus) {
14825 // In C, a volatile scalar is read by __imag. In C++, it is not.
14826 Input = DefaultLvalueConversion(Input.get());
14827 }
14828 break;
14829 case UO_Extension:
14830 resultType = Input.get()->getType();
14831 VK = Input.get()->getValueKind();
14832 OK = Input.get()->getObjectKind();
14833 break;
14834 case UO_Coawait:
14835 // It's unnecessary to represent the pass-through operator co_await in the
14836 // AST; just return the input expression instead.
14837 assert(!Input.get()->getType()->isDependentType() &&
14838 "the co_await expression must be non-dependant before "
14839 "building operator co_await");
14840 return Input;
14841 }
14842 if (resultType.isNull() || Input.isInvalid())
14843 return ExprError();
14844
14845 // Check for array bounds violations in the operand of the UnaryOperator,
14846 // except for the '*' and '&' operators that have to be handled specially
14847 // by CheckArrayAccess (as there are special cases like &array[arraysize]
14848 // that are explicitly defined as valid by the standard).
14849 if (Opc != UO_AddrOf && Opc != UO_Deref)
14850 CheckArrayAccess(Input.get());
14851
14852 auto *UO =
14853 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14854 OpLoc, CanOverflow, CurFPFeatureOverrides());
14855
14856 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14857 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
14858 !isUnevaluatedContext())
14859 ExprEvalContexts.back().PossibleDerefs.insert(UO);
14860
14861 // Convert the result back to a half vector.
14862 if (ConvertHalfVec)
14863 return convertVector(UO, Context.HalfTy, *this);
14864 return UO;
14865 }
14866
14867 /// Determine whether the given expression is a qualified member
14868 /// access expression, of a form that could be turned into a pointer to member
14869 /// with the address-of operator.
isQualifiedMemberAccess(Expr * E)14870 bool Sema::isQualifiedMemberAccess(Expr *E) {
14871 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14872 if (!DRE->getQualifier())
14873 return false;
14874
14875 ValueDecl *VD = DRE->getDecl();
14876 if (!VD->isCXXClassMember())
14877 return false;
14878
14879 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14880 return true;
14881 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14882 return Method->isInstance();
14883
14884 return false;
14885 }
14886
14887 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14888 if (!ULE->getQualifier())
14889 return false;
14890
14891 for (NamedDecl *D : ULE->decls()) {
14892 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14893 if (Method->isInstance())
14894 return true;
14895 } else {
14896 // Overload set does not contain methods.
14897 break;
14898 }
14899 }
14900
14901 return false;
14902 }
14903
14904 return false;
14905 }
14906
BuildUnaryOp(Scope * S,SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * Input)14907 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14908 UnaryOperatorKind Opc, Expr *Input) {
14909 // First things first: handle placeholders so that the
14910 // overloaded-operator check considers the right type.
14911 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14912 // Increment and decrement of pseudo-object references.
14913 if (pty->getKind() == BuiltinType::PseudoObject &&
14914 UnaryOperator::isIncrementDecrementOp(Opc))
14915 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14916
14917 // extension is always a builtin operator.
14918 if (Opc == UO_Extension)
14919 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14920
14921 // & gets special logic for several kinds of placeholder.
14922 // The builtin code knows what to do.
14923 if (Opc == UO_AddrOf &&
14924 (pty->getKind() == BuiltinType::Overload ||
14925 pty->getKind() == BuiltinType::UnknownAny ||
14926 pty->getKind() == BuiltinType::BoundMember))
14927 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14928
14929 // Anything else needs to be handled now.
14930 ExprResult Result = CheckPlaceholderExpr(Input);
14931 if (Result.isInvalid()) return ExprError();
14932 Input = Result.get();
14933 }
14934
14935 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14936 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14937 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14938 // Find all of the overloaded operators visible from this point.
14939 UnresolvedSet<16> Functions;
14940 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14941 if (S && OverOp != OO_None)
14942 LookupOverloadedOperatorName(OverOp, S, Functions);
14943
14944 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14945 }
14946
14947 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14948 }
14949
14950 // Unary Operators. 'Tok' is the token for the operator.
ActOnUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Op,Expr * Input)14951 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14952 tok::TokenKind Op, Expr *Input) {
14953 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14954 }
14955
14956 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ActOnAddrLabel(SourceLocation OpLoc,SourceLocation LabLoc,LabelDecl * TheDecl)14957 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14958 LabelDecl *TheDecl) {
14959 TheDecl->markUsed(Context);
14960 // Create the AST node. The address of a label always has type 'void*'.
14961 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14962 Context.getPointerType(Context.VoidTy));
14963 }
14964
ActOnStartStmtExpr()14965 void Sema::ActOnStartStmtExpr() {
14966 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14967 }
14968
ActOnStmtExprError()14969 void Sema::ActOnStmtExprError() {
14970 // Note that function is also called by TreeTransform when leaving a
14971 // StmtExpr scope without rebuilding anything.
14972
14973 DiscardCleanupsInEvaluationContext();
14974 PopExpressionEvaluationContext();
14975 }
14976
ActOnStmtExpr(Scope * S,SourceLocation LPLoc,Stmt * SubStmt,SourceLocation RPLoc)14977 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14978 SourceLocation RPLoc) {
14979 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14980 }
14981
BuildStmtExpr(SourceLocation LPLoc,Stmt * SubStmt,SourceLocation RPLoc,unsigned TemplateDepth)14982 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14983 SourceLocation RPLoc, unsigned TemplateDepth) {
14984 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14985 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14986
14987 if (hasAnyUnrecoverableErrorsInThisFunction())
14988 DiscardCleanupsInEvaluationContext();
14989 assert(!Cleanup.exprNeedsCleanups() &&
14990 "cleanups within StmtExpr not correctly bound!");
14991 PopExpressionEvaluationContext();
14992
14993 // FIXME: there are a variety of strange constraints to enforce here, for
14994 // example, it is not possible to goto into a stmt expression apparently.
14995 // More semantic analysis is needed.
14996
14997 // If there are sub-stmts in the compound stmt, take the type of the last one
14998 // as the type of the stmtexpr.
14999 QualType Ty = Context.VoidTy;
15000 bool StmtExprMayBindToTemp = false;
15001 if (!Compound->body_empty()) {
15002 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15003 if (const auto *LastStmt =
15004 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15005 if (const Expr *Value = LastStmt->getExprStmt()) {
15006 StmtExprMayBindToTemp = true;
15007 Ty = Value->getType();
15008 }
15009 }
15010 }
15011
15012 // FIXME: Check that expression type is complete/non-abstract; statement
15013 // expressions are not lvalues.
15014 Expr *ResStmtExpr =
15015 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15016 if (StmtExprMayBindToTemp)
15017 return MaybeBindToTemporary(ResStmtExpr);
15018 return ResStmtExpr;
15019 }
15020
ActOnStmtExprResult(ExprResult ER)15021 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
15022 if (ER.isInvalid())
15023 return ExprError();
15024
15025 // Do function/array conversion on the last expression, but not
15026 // lvalue-to-rvalue. However, initialize an unqualified type.
15027 ER = DefaultFunctionArrayConversion(ER.get());
15028 if (ER.isInvalid())
15029 return ExprError();
15030 Expr *E = ER.get();
15031
15032 if (E->isTypeDependent())
15033 return E;
15034
15035 // In ARC, if the final expression ends in a consume, splice
15036 // the consume out and bind it later. In the alternate case
15037 // (when dealing with a retainable type), the result
15038 // initialization will create a produce. In both cases the
15039 // result will be +1, and we'll need to balance that out with
15040 // a bind.
15041 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15042 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15043 return Cast->getSubExpr();
15044
15045 // FIXME: Provide a better location for the initialization.
15046 return PerformCopyInitialization(
15047 InitializedEntity::InitializeStmtExprResult(
15048 E->getBeginLoc(), E->getType().getUnqualifiedType()),
15049 SourceLocation(), E);
15050 }
15051
BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,TypeSourceInfo * TInfo,ArrayRef<OffsetOfComponent> Components,SourceLocation RParenLoc)15052 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
15053 TypeSourceInfo *TInfo,
15054 ArrayRef<OffsetOfComponent> Components,
15055 SourceLocation RParenLoc) {
15056 QualType ArgTy = TInfo->getType();
15057 bool Dependent = ArgTy->isDependentType();
15058 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15059
15060 // We must have at least one component that refers to the type, and the first
15061 // one is known to be a field designator. Verify that the ArgTy represents
15062 // a struct/union/class.
15063 if (!Dependent && !ArgTy->isRecordType())
15064 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15065 << ArgTy << TypeRange);
15066
15067 // Type must be complete per C99 7.17p3 because a declaring a variable
15068 // with an incomplete type would be ill-formed.
15069 if (!Dependent
15070 && RequireCompleteType(BuiltinLoc, ArgTy,
15071 diag::err_offsetof_incomplete_type, TypeRange))
15072 return ExprError();
15073
15074 bool DidWarnAboutNonPOD = false;
15075 QualType CurrentType = ArgTy;
15076 SmallVector<OffsetOfNode, 4> Comps;
15077 SmallVector<Expr*, 4> Exprs;
15078 for (const OffsetOfComponent &OC : Components) {
15079 if (OC.isBrackets) {
15080 // Offset of an array sub-field. TODO: Should we allow vector elements?
15081 if (!CurrentType->isDependentType()) {
15082 const ArrayType *AT = Context.getAsArrayType(CurrentType);
15083 if(!AT)
15084 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15085 << CurrentType);
15086 CurrentType = AT->getElementType();
15087 } else
15088 CurrentType = Context.DependentTy;
15089
15090 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15091 if (IdxRval.isInvalid())
15092 return ExprError();
15093 Expr *Idx = IdxRval.get();
15094
15095 // The expression must be an integral expression.
15096 // FIXME: An integral constant expression?
15097 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15098 !Idx->getType()->isIntegerType())
15099 return ExprError(
15100 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15101 << Idx->getSourceRange());
15102
15103 // Record this array index.
15104 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15105 Exprs.push_back(Idx);
15106 continue;
15107 }
15108
15109 // Offset of a field.
15110 if (CurrentType->isDependentType()) {
15111 // We have the offset of a field, but we can't look into the dependent
15112 // type. Just record the identifier of the field.
15113 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15114 CurrentType = Context.DependentTy;
15115 continue;
15116 }
15117
15118 // We need to have a complete type to look into.
15119 if (RequireCompleteType(OC.LocStart, CurrentType,
15120 diag::err_offsetof_incomplete_type))
15121 return ExprError();
15122
15123 // Look for the designated field.
15124 const RecordType *RC = CurrentType->getAs<RecordType>();
15125 if (!RC)
15126 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15127 << CurrentType);
15128 RecordDecl *RD = RC->getDecl();
15129
15130 // C++ [lib.support.types]p5:
15131 // The macro offsetof accepts a restricted set of type arguments in this
15132 // International Standard. type shall be a POD structure or a POD union
15133 // (clause 9).
15134 // C++11 [support.types]p4:
15135 // If type is not a standard-layout class (Clause 9), the results are
15136 // undefined.
15137 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15138 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15139 unsigned DiagID =
15140 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15141 : diag::ext_offsetof_non_pod_type;
15142
15143 if (!IsSafe && !DidWarnAboutNonPOD &&
15144 DiagRuntimeBehavior(BuiltinLoc, nullptr,
15145 PDiag(DiagID)
15146 << SourceRange(Components[0].LocStart, OC.LocEnd)
15147 << CurrentType))
15148 DidWarnAboutNonPOD = true;
15149 }
15150
15151 // Look for the field.
15152 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15153 LookupQualifiedName(R, RD);
15154 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15155 IndirectFieldDecl *IndirectMemberDecl = nullptr;
15156 if (!MemberDecl) {
15157 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15158 MemberDecl = IndirectMemberDecl->getAnonField();
15159 }
15160
15161 if (!MemberDecl)
15162 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15163 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15164 OC.LocEnd));
15165
15166 // C99 7.17p3:
15167 // (If the specified member is a bit-field, the behavior is undefined.)
15168 //
15169 // We diagnose this as an error.
15170 if (MemberDecl->isBitField()) {
15171 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15172 << MemberDecl->getDeclName()
15173 << SourceRange(BuiltinLoc, RParenLoc);
15174 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15175 return ExprError();
15176 }
15177
15178 RecordDecl *Parent = MemberDecl->getParent();
15179 if (IndirectMemberDecl)
15180 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15181
15182 // If the member was found in a base class, introduce OffsetOfNodes for
15183 // the base class indirections.
15184 CXXBasePaths Paths;
15185 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15186 Paths)) {
15187 if (Paths.getDetectedVirtual()) {
15188 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15189 << MemberDecl->getDeclName()
15190 << SourceRange(BuiltinLoc, RParenLoc);
15191 return ExprError();
15192 }
15193
15194 CXXBasePath &Path = Paths.front();
15195 for (const CXXBasePathElement &B : Path)
15196 Comps.push_back(OffsetOfNode(B.Base));
15197 }
15198
15199 if (IndirectMemberDecl) {
15200 for (auto *FI : IndirectMemberDecl->chain()) {
15201 assert(isa<FieldDecl>(FI));
15202 Comps.push_back(OffsetOfNode(OC.LocStart,
15203 cast<FieldDecl>(FI), OC.LocEnd));
15204 }
15205 } else
15206 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15207
15208 CurrentType = MemberDecl->getType().getNonReferenceType();
15209 }
15210
15211 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15212 Comps, Exprs, RParenLoc);
15213 }
15214
ActOnBuiltinOffsetOf(Scope * S,SourceLocation BuiltinLoc,SourceLocation TypeLoc,ParsedType ParsedArgTy,ArrayRef<OffsetOfComponent> Components,SourceLocation RParenLoc)15215 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15216 SourceLocation BuiltinLoc,
15217 SourceLocation TypeLoc,
15218 ParsedType ParsedArgTy,
15219 ArrayRef<OffsetOfComponent> Components,
15220 SourceLocation RParenLoc) {
15221
15222 TypeSourceInfo *ArgTInfo;
15223 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15224 if (ArgTy.isNull())
15225 return ExprError();
15226
15227 if (!ArgTInfo)
15228 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15229
15230 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15231 }
15232
15233
ActOnChooseExpr(SourceLocation BuiltinLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr,SourceLocation RPLoc)15234 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15235 Expr *CondExpr,
15236 Expr *LHSExpr, Expr *RHSExpr,
15237 SourceLocation RPLoc) {
15238 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15239
15240 ExprValueKind VK = VK_RValue;
15241 ExprObjectKind OK = OK_Ordinary;
15242 QualType resType;
15243 bool CondIsTrue = false;
15244 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15245 resType = Context.DependentTy;
15246 } else {
15247 // The conditional expression is required to be a constant expression.
15248 llvm::APSInt condEval(32);
15249 ExprResult CondICE = VerifyIntegerConstantExpression(
15250 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15251 if (CondICE.isInvalid())
15252 return ExprError();
15253 CondExpr = CondICE.get();
15254 CondIsTrue = condEval.getZExtValue();
15255
15256 // If the condition is > zero, then the AST type is the same as the LHSExpr.
15257 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15258
15259 resType = ActiveExpr->getType();
15260 VK = ActiveExpr->getValueKind();
15261 OK = ActiveExpr->getObjectKind();
15262 }
15263
15264 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15265 resType, VK, OK, RPLoc, CondIsTrue);
15266 }
15267
15268 //===----------------------------------------------------------------------===//
15269 // Clang Extensions.
15270 //===----------------------------------------------------------------------===//
15271
15272 /// ActOnBlockStart - This callback is invoked when a block literal is started.
ActOnBlockStart(SourceLocation CaretLoc,Scope * CurScope)15273 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15274 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15275
15276 if (LangOpts.CPlusPlus) {
15277 MangleNumberingContext *MCtx;
15278 Decl *ManglingContextDecl;
15279 std::tie(MCtx, ManglingContextDecl) =
15280 getCurrentMangleNumberContext(Block->getDeclContext());
15281 if (MCtx) {
15282 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15283 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15284 }
15285 }
15286
15287 PushBlockScope(CurScope, Block);
15288 CurContext->addDecl(Block);
15289 if (CurScope)
15290 PushDeclContext(CurScope, Block);
15291 else
15292 CurContext = Block;
15293
15294 getCurBlock()->HasImplicitReturnType = true;
15295
15296 // Enter a new evaluation context to insulate the block from any
15297 // cleanups from the enclosing full-expression.
15298 PushExpressionEvaluationContext(
15299 ExpressionEvaluationContext::PotentiallyEvaluated);
15300 }
15301
ActOnBlockArguments(SourceLocation CaretLoc,Declarator & ParamInfo,Scope * CurScope)15302 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15303 Scope *CurScope) {
15304 assert(ParamInfo.getIdentifier() == nullptr &&
15305 "block-id should have no identifier!");
15306 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15307 BlockScopeInfo *CurBlock = getCurBlock();
15308
15309 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15310 QualType T = Sig->getType();
15311
15312 // FIXME: We should allow unexpanded parameter packs here, but that would,
15313 // in turn, make the block expression contain unexpanded parameter packs.
15314 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15315 // Drop the parameters.
15316 FunctionProtoType::ExtProtoInfo EPI;
15317 EPI.HasTrailingReturn = false;
15318 EPI.TypeQuals.addConst();
15319 T = Context.getFunctionType(Context.DependentTy, None, EPI);
15320 Sig = Context.getTrivialTypeSourceInfo(T);
15321 }
15322
15323 // GetTypeForDeclarator always produces a function type for a block
15324 // literal signature. Furthermore, it is always a FunctionProtoType
15325 // unless the function was written with a typedef.
15326 assert(T->isFunctionType() &&
15327 "GetTypeForDeclarator made a non-function block signature");
15328
15329 // Look for an explicit signature in that function type.
15330 FunctionProtoTypeLoc ExplicitSignature;
15331
15332 if ((ExplicitSignature = Sig->getTypeLoc()
15333 .getAsAdjusted<FunctionProtoTypeLoc>())) {
15334
15335 // Check whether that explicit signature was synthesized by
15336 // GetTypeForDeclarator. If so, don't save that as part of the
15337 // written signature.
15338 if (ExplicitSignature.getLocalRangeBegin() ==
15339 ExplicitSignature.getLocalRangeEnd()) {
15340 // This would be much cheaper if we stored TypeLocs instead of
15341 // TypeSourceInfos.
15342 TypeLoc Result = ExplicitSignature.getReturnLoc();
15343 unsigned Size = Result.getFullDataSize();
15344 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15345 Sig->getTypeLoc().initializeFullCopy(Result, Size);
15346
15347 ExplicitSignature = FunctionProtoTypeLoc();
15348 }
15349 }
15350
15351 CurBlock->TheDecl->setSignatureAsWritten(Sig);
15352 CurBlock->FunctionType = T;
15353
15354 const auto *Fn = T->castAs<FunctionType>();
15355 QualType RetTy = Fn->getReturnType();
15356 bool isVariadic =
15357 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15358
15359 CurBlock->TheDecl->setIsVariadic(isVariadic);
15360
15361 // Context.DependentTy is used as a placeholder for a missing block
15362 // return type. TODO: what should we do with declarators like:
15363 // ^ * { ... }
15364 // If the answer is "apply template argument deduction"....
15365 if (RetTy != Context.DependentTy) {
15366 CurBlock->ReturnType = RetTy;
15367 CurBlock->TheDecl->setBlockMissingReturnType(false);
15368 CurBlock->HasImplicitReturnType = false;
15369 }
15370
15371 // Push block parameters from the declarator if we had them.
15372 SmallVector<ParmVarDecl*, 8> Params;
15373 if (ExplicitSignature) {
15374 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15375 ParmVarDecl *Param = ExplicitSignature.getParam(I);
15376 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15377 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15378 // Diagnose this as an extension in C17 and earlier.
15379 if (!getLangOpts().C2x)
15380 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15381 }
15382 Params.push_back(Param);
15383 }
15384
15385 // Fake up parameter variables if we have a typedef, like
15386 // ^ fntype { ... }
15387 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15388 for (const auto &I : Fn->param_types()) {
15389 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15390 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15391 Params.push_back(Param);
15392 }
15393 }
15394
15395 // Set the parameters on the block decl.
15396 if (!Params.empty()) {
15397 CurBlock->TheDecl->setParams(Params);
15398 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15399 /*CheckParameterNames=*/false);
15400 }
15401
15402 // Finally we can process decl attributes.
15403 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15404
15405 // Put the parameter variables in scope.
15406 for (auto AI : CurBlock->TheDecl->parameters()) {
15407 AI->setOwningFunction(CurBlock->TheDecl);
15408
15409 // If this has an identifier, add it to the scope stack.
15410 if (AI->getIdentifier()) {
15411 CheckShadow(CurBlock->TheScope, AI);
15412
15413 PushOnScopeChains(AI, CurBlock->TheScope);
15414 }
15415 }
15416 }
15417
15418 /// ActOnBlockError - If there is an error parsing a block, this callback
15419 /// is invoked to pop the information about the block from the action impl.
ActOnBlockError(SourceLocation CaretLoc,Scope * CurScope)15420 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15421 // Leave the expression-evaluation context.
15422 DiscardCleanupsInEvaluationContext();
15423 PopExpressionEvaluationContext();
15424
15425 // Pop off CurBlock, handle nested blocks.
15426 PopDeclContext();
15427 PopFunctionScopeInfo();
15428 }
15429
15430 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15431 /// literal was successfully completed. ^(int x){...}
ActOnBlockStmtExpr(SourceLocation CaretLoc,Stmt * Body,Scope * CurScope)15432 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15433 Stmt *Body, Scope *CurScope) {
15434 // If blocks are disabled, emit an error.
15435 if (!LangOpts.Blocks)
15436 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15437
15438 // Leave the expression-evaluation context.
15439 if (hasAnyUnrecoverableErrorsInThisFunction())
15440 DiscardCleanupsInEvaluationContext();
15441 assert(!Cleanup.exprNeedsCleanups() &&
15442 "cleanups within block not correctly bound!");
15443 PopExpressionEvaluationContext();
15444
15445 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15446 BlockDecl *BD = BSI->TheDecl;
15447
15448 if (BSI->HasImplicitReturnType)
15449 deduceClosureReturnType(*BSI);
15450
15451 QualType RetTy = Context.VoidTy;
15452 if (!BSI->ReturnType.isNull())
15453 RetTy = BSI->ReturnType;
15454
15455 bool NoReturn = BD->hasAttr<NoReturnAttr>();
15456 QualType BlockTy;
15457
15458 // If the user wrote a function type in some form, try to use that.
15459 if (!BSI->FunctionType.isNull()) {
15460 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15461
15462 FunctionType::ExtInfo Ext = FTy->getExtInfo();
15463 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15464
15465 // Turn protoless block types into nullary block types.
15466 if (isa<FunctionNoProtoType>(FTy)) {
15467 FunctionProtoType::ExtProtoInfo EPI;
15468 EPI.ExtInfo = Ext;
15469 BlockTy = Context.getFunctionType(RetTy, None, EPI);
15470
15471 // Otherwise, if we don't need to change anything about the function type,
15472 // preserve its sugar structure.
15473 } else if (FTy->getReturnType() == RetTy &&
15474 (!NoReturn || FTy->getNoReturnAttr())) {
15475 BlockTy = BSI->FunctionType;
15476
15477 // Otherwise, make the minimal modifications to the function type.
15478 } else {
15479 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15480 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15481 EPI.TypeQuals = Qualifiers();
15482 EPI.ExtInfo = Ext;
15483 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15484 }
15485
15486 // If we don't have a function type, just build one from nothing.
15487 } else {
15488 FunctionProtoType::ExtProtoInfo EPI;
15489 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15490 BlockTy = Context.getFunctionType(RetTy, None, EPI);
15491 }
15492
15493 DiagnoseUnusedParameters(BD->parameters());
15494 BlockTy = Context.getBlockPointerType(BlockTy);
15495
15496 // If needed, diagnose invalid gotos and switches in the block.
15497 if (getCurFunction()->NeedsScopeChecking() &&
15498 !PP.isCodeCompletionEnabled())
15499 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15500
15501 BD->setBody(cast<CompoundStmt>(Body));
15502
15503 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15504 DiagnoseUnguardedAvailabilityViolations(BD);
15505
15506 // Try to apply the named return value optimization. We have to check again
15507 // if we can do this, though, because blocks keep return statements around
15508 // to deduce an implicit return type.
15509 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15510 !BD->isDependentContext())
15511 computeNRVO(Body, BSI);
15512
15513 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15514 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15515 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15516 NTCUK_Destruct|NTCUK_Copy);
15517
15518 PopDeclContext();
15519
15520 // Set the captured variables on the block.
15521 SmallVector<BlockDecl::Capture, 4> Captures;
15522 for (Capture &Cap : BSI->Captures) {
15523 if (Cap.isInvalid() || Cap.isThisCapture())
15524 continue;
15525
15526 VarDecl *Var = Cap.getVariable();
15527 Expr *CopyExpr = nullptr;
15528 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15529 if (const RecordType *Record =
15530 Cap.getCaptureType()->getAs<RecordType>()) {
15531 // The capture logic needs the destructor, so make sure we mark it.
15532 // Usually this is unnecessary because most local variables have
15533 // their destructors marked at declaration time, but parameters are
15534 // an exception because it's technically only the call site that
15535 // actually requires the destructor.
15536 if (isa<ParmVarDecl>(Var))
15537 FinalizeVarWithDestructor(Var, Record);
15538
15539 // Enter a separate potentially-evaluated context while building block
15540 // initializers to isolate their cleanups from those of the block
15541 // itself.
15542 // FIXME: Is this appropriate even when the block itself occurs in an
15543 // unevaluated operand?
15544 EnterExpressionEvaluationContext EvalContext(
15545 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15546
15547 SourceLocation Loc = Cap.getLocation();
15548
15549 ExprResult Result = BuildDeclarationNameExpr(
15550 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15551
15552 // According to the blocks spec, the capture of a variable from
15553 // the stack requires a const copy constructor. This is not true
15554 // of the copy/move done to move a __block variable to the heap.
15555 if (!Result.isInvalid() &&
15556 !Result.get()->getType().isConstQualified()) {
15557 Result = ImpCastExprToType(Result.get(),
15558 Result.get()->getType().withConst(),
15559 CK_NoOp, VK_LValue);
15560 }
15561
15562 if (!Result.isInvalid()) {
15563 Result = PerformCopyInitialization(
15564 InitializedEntity::InitializeBlock(Var->getLocation(),
15565 Cap.getCaptureType(), false),
15566 Loc, Result.get());
15567 }
15568
15569 // Build a full-expression copy expression if initialization
15570 // succeeded and used a non-trivial constructor. Recover from
15571 // errors by pretending that the copy isn't necessary.
15572 if (!Result.isInvalid() &&
15573 !cast<CXXConstructExpr>(Result.get())->getConstructor()
15574 ->isTrivial()) {
15575 Result = MaybeCreateExprWithCleanups(Result);
15576 CopyExpr = Result.get();
15577 }
15578 }
15579 }
15580
15581 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15582 CopyExpr);
15583 Captures.push_back(NewCap);
15584 }
15585 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15586
15587 // Pop the block scope now but keep it alive to the end of this function.
15588 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15589 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15590
15591 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15592
15593 // If the block isn't obviously global, i.e. it captures anything at
15594 // all, then we need to do a few things in the surrounding context:
15595 if (Result->getBlockDecl()->hasCaptures()) {
15596 // First, this expression has a new cleanup object.
15597 ExprCleanupObjects.push_back(Result->getBlockDecl());
15598 Cleanup.setExprNeedsCleanups(true);
15599
15600 // It also gets a branch-protected scope if any of the captured
15601 // variables needs destruction.
15602 for (const auto &CI : Result->getBlockDecl()->captures()) {
15603 const VarDecl *var = CI.getVariable();
15604 if (var->getType().isDestructedType() != QualType::DK_none) {
15605 setFunctionHasBranchProtectedScope();
15606 break;
15607 }
15608 }
15609 }
15610
15611 if (getCurFunction())
15612 getCurFunction()->addBlock(BD);
15613
15614 return Result;
15615 }
15616
ActOnVAArg(SourceLocation BuiltinLoc,Expr * E,ParsedType Ty,SourceLocation RPLoc)15617 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15618 SourceLocation RPLoc) {
15619 TypeSourceInfo *TInfo;
15620 GetTypeFromParser(Ty, &TInfo);
15621 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15622 }
15623
BuildVAArgExpr(SourceLocation BuiltinLoc,Expr * E,TypeSourceInfo * TInfo,SourceLocation RPLoc)15624 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15625 Expr *E, TypeSourceInfo *TInfo,
15626 SourceLocation RPLoc) {
15627 Expr *OrigExpr = E;
15628 bool IsMS = false;
15629
15630 // CUDA device code does not support varargs.
15631 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15632 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15633 CUDAFunctionTarget T = IdentifyCUDATarget(F);
15634 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15635 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15636 }
15637 }
15638
15639 // NVPTX does not support va_arg expression.
15640 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15641 Context.getTargetInfo().getTriple().isNVPTX())
15642 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15643
15644 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15645 // as Microsoft ABI on an actual Microsoft platform, where
15646 // __builtin_ms_va_list and __builtin_va_list are the same.)
15647 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15648 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15649 QualType MSVaListType = Context.getBuiltinMSVaListType();
15650 if (Context.hasSameType(MSVaListType, E->getType())) {
15651 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15652 return ExprError();
15653 IsMS = true;
15654 }
15655 }
15656
15657 // Get the va_list type
15658 QualType VaListType = Context.getBuiltinVaListType();
15659 if (!IsMS) {
15660 if (VaListType->isArrayType()) {
15661 // Deal with implicit array decay; for example, on x86-64,
15662 // va_list is an array, but it's supposed to decay to
15663 // a pointer for va_arg.
15664 VaListType = Context.getArrayDecayedType(VaListType);
15665 // Make sure the input expression also decays appropriately.
15666 ExprResult Result = UsualUnaryConversions(E);
15667 if (Result.isInvalid())
15668 return ExprError();
15669 E = Result.get();
15670 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15671 // If va_list is a record type and we are compiling in C++ mode,
15672 // check the argument using reference binding.
15673 InitializedEntity Entity = InitializedEntity::InitializeParameter(
15674 Context, Context.getLValueReferenceType(VaListType), false);
15675 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15676 if (Init.isInvalid())
15677 return ExprError();
15678 E = Init.getAs<Expr>();
15679 } else {
15680 // Otherwise, the va_list argument must be an l-value because
15681 // it is modified by va_arg.
15682 if (!E->isTypeDependent() &&
15683 CheckForModifiableLvalue(E, BuiltinLoc, *this))
15684 return ExprError();
15685 }
15686 }
15687
15688 if (!IsMS && !E->isTypeDependent() &&
15689 !Context.hasSameType(VaListType, E->getType()))
15690 return ExprError(
15691 Diag(E->getBeginLoc(),
15692 diag::err_first_argument_to_va_arg_not_of_type_va_list)
15693 << OrigExpr->getType() << E->getSourceRange());
15694
15695 if (!TInfo->getType()->isDependentType()) {
15696 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15697 diag::err_second_parameter_to_va_arg_incomplete,
15698 TInfo->getTypeLoc()))
15699 return ExprError();
15700
15701 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15702 TInfo->getType(),
15703 diag::err_second_parameter_to_va_arg_abstract,
15704 TInfo->getTypeLoc()))
15705 return ExprError();
15706
15707 if (!TInfo->getType().isPODType(Context)) {
15708 Diag(TInfo->getTypeLoc().getBeginLoc(),
15709 TInfo->getType()->isObjCLifetimeType()
15710 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15711 : diag::warn_second_parameter_to_va_arg_not_pod)
15712 << TInfo->getType()
15713 << TInfo->getTypeLoc().getSourceRange();
15714 }
15715
15716 // Check for va_arg where arguments of the given type will be promoted
15717 // (i.e. this va_arg is guaranteed to have undefined behavior).
15718 QualType PromoteType;
15719 if (TInfo->getType()->isPromotableIntegerType()) {
15720 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15721 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15722 PromoteType = QualType();
15723 }
15724 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15725 PromoteType = Context.DoubleTy;
15726 if (!PromoteType.isNull())
15727 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15728 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15729 << TInfo->getType()
15730 << PromoteType
15731 << TInfo->getTypeLoc().getSourceRange());
15732 }
15733
15734 QualType T = TInfo->getType().getNonLValueExprType(Context);
15735 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15736 }
15737
ActOnGNUNullExpr(SourceLocation TokenLoc)15738 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15739 // The type of __null will be int or long, depending on the size of
15740 // pointers on the target.
15741 QualType Ty;
15742 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15743 if (pw == Context.getTargetInfo().getIntWidth())
15744 Ty = Context.IntTy;
15745 else if (pw == Context.getTargetInfo().getLongWidth())
15746 Ty = Context.LongTy;
15747 else if (pw == Context.getTargetInfo().getLongLongWidth())
15748 Ty = Context.LongLongTy;
15749 else {
15750 llvm_unreachable("I don't know size of pointer!");
15751 }
15752
15753 return new (Context) GNUNullExpr(Ty, TokenLoc);
15754 }
15755
ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,SourceLocation BuiltinLoc,SourceLocation RPLoc)15756 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15757 SourceLocation BuiltinLoc,
15758 SourceLocation RPLoc) {
15759 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15760 }
15761
BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,SourceLocation BuiltinLoc,SourceLocation RPLoc,DeclContext * ParentContext)15762 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15763 SourceLocation BuiltinLoc,
15764 SourceLocation RPLoc,
15765 DeclContext *ParentContext) {
15766 return new (Context)
15767 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15768 }
15769
CheckConversionToObjCLiteral(QualType DstType,Expr * & Exp,bool Diagnose)15770 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15771 bool Diagnose) {
15772 if (!getLangOpts().ObjC)
15773 return false;
15774
15775 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15776 if (!PT)
15777 return false;
15778 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15779
15780 // Ignore any parens, implicit casts (should only be
15781 // array-to-pointer decays), and not-so-opaque values. The last is
15782 // important for making this trigger for property assignments.
15783 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15784 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15785 if (OV->getSourceExpr())
15786 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15787
15788 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15789 if (!PT->isObjCIdType() &&
15790 !(ID && ID->getIdentifier()->isStr("NSString")))
15791 return false;
15792 if (!SL->isAscii())
15793 return false;
15794
15795 if (Diagnose) {
15796 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15797 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15798 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15799 }
15800 return true;
15801 }
15802
15803 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15804 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15805 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15806 !SrcExpr->isNullPointerConstant(
15807 getASTContext(), Expr::NPC_NeverValueDependent)) {
15808 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15809 return false;
15810 if (Diagnose) {
15811 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15812 << /*number*/1
15813 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15814 Expr *NumLit =
15815 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15816 if (NumLit)
15817 Exp = NumLit;
15818 }
15819 return true;
15820 }
15821
15822 return false;
15823 }
15824
maybeDiagnoseAssignmentToFunction(Sema & S,QualType DstType,const Expr * SrcExpr)15825 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15826 const Expr *SrcExpr) {
15827 if (!DstType->isFunctionPointerType() ||
15828 !SrcExpr->getType()->isFunctionType())
15829 return false;
15830
15831 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15832 if (!DRE)
15833 return false;
15834
15835 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15836 if (!FD)
15837 return false;
15838
15839 return !S.checkAddressOfFunctionIsAvailable(FD,
15840 /*Complain=*/true,
15841 SrcExpr->getBeginLoc());
15842 }
15843
DiagnoseAssignmentResult(AssignConvertType ConvTy,SourceLocation Loc,QualType DstType,QualType SrcType,Expr * SrcExpr,AssignmentAction Action,bool * Complained)15844 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15845 SourceLocation Loc,
15846 QualType DstType, QualType SrcType,
15847 Expr *SrcExpr, AssignmentAction Action,
15848 bool *Complained) {
15849 if (Complained)
15850 *Complained = false;
15851
15852 // Decode the result (notice that AST's are still created for extensions).
15853 bool CheckInferredResultType = false;
15854 bool isInvalid = false;
15855 unsigned DiagKind = 0;
15856 ConversionFixItGenerator ConvHints;
15857 bool MayHaveConvFixit = false;
15858 bool MayHaveFunctionDiff = false;
15859 const ObjCInterfaceDecl *IFace = nullptr;
15860 const ObjCProtocolDecl *PDecl = nullptr;
15861
15862 switch (ConvTy) {
15863 case Compatible:
15864 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15865 return false;
15866
15867 case PointerToInt:
15868 if (getLangOpts().CPlusPlus) {
15869 DiagKind = diag::err_typecheck_convert_pointer_int;
15870 isInvalid = true;
15871 } else {
15872 DiagKind = diag::ext_typecheck_convert_pointer_int;
15873 }
15874 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15875 MayHaveConvFixit = true;
15876 break;
15877 case IntToPointer:
15878 if (getLangOpts().CPlusPlus) {
15879 DiagKind = diag::err_typecheck_convert_int_pointer;
15880 isInvalid = true;
15881 } else {
15882 DiagKind = diag::ext_typecheck_convert_int_pointer;
15883 }
15884 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15885 MayHaveConvFixit = true;
15886 break;
15887 case IncompatibleFunctionPointer:
15888 if (getLangOpts().CPlusPlus) {
15889 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15890 isInvalid = true;
15891 } else {
15892 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15893 }
15894 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15895 MayHaveConvFixit = true;
15896 break;
15897 case IncompatiblePointer:
15898 if (Action == AA_Passing_CFAudited) {
15899 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15900 } else if (getLangOpts().CPlusPlus) {
15901 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15902 isInvalid = true;
15903 } else {
15904 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15905 }
15906 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15907 SrcType->isObjCObjectPointerType();
15908 if (!CheckInferredResultType) {
15909 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15910 } else if (CheckInferredResultType) {
15911 SrcType = SrcType.getUnqualifiedType();
15912 DstType = DstType.getUnqualifiedType();
15913 }
15914 MayHaveConvFixit = true;
15915 break;
15916 case IncompatiblePointerSign:
15917 if (getLangOpts().CPlusPlus) {
15918 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15919 isInvalid = true;
15920 } else {
15921 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15922 }
15923 break;
15924 case FunctionVoidPointer:
15925 if (getLangOpts().CPlusPlus) {
15926 DiagKind = diag::err_typecheck_convert_pointer_void_func;
15927 isInvalid = true;
15928 } else {
15929 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15930 }
15931 break;
15932 case IncompatiblePointerDiscardsQualifiers: {
15933 // Perform array-to-pointer decay if necessary.
15934 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15935
15936 isInvalid = true;
15937
15938 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15939 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15940 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15941 DiagKind = diag::err_typecheck_incompatible_address_space;
15942 break;
15943
15944 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15945 DiagKind = diag::err_typecheck_incompatible_ownership;
15946 break;
15947 }
15948
15949 llvm_unreachable("unknown error case for discarding qualifiers!");
15950 // fallthrough
15951 }
15952 case CompatiblePointerDiscardsQualifiers:
15953 // If the qualifiers lost were because we were applying the
15954 // (deprecated) C++ conversion from a string literal to a char*
15955 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
15956 // Ideally, this check would be performed in
15957 // checkPointerTypesForAssignment. However, that would require a
15958 // bit of refactoring (so that the second argument is an
15959 // expression, rather than a type), which should be done as part
15960 // of a larger effort to fix checkPointerTypesForAssignment for
15961 // C++ semantics.
15962 if (getLangOpts().CPlusPlus &&
15963 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15964 return false;
15965 if (getLangOpts().CPlusPlus) {
15966 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
15967 isInvalid = true;
15968 } else {
15969 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
15970 }
15971
15972 break;
15973 case IncompatibleNestedPointerQualifiers:
15974 if (getLangOpts().CPlusPlus) {
15975 isInvalid = true;
15976 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15977 } else {
15978 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15979 }
15980 break;
15981 case IncompatibleNestedPointerAddressSpaceMismatch:
15982 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15983 isInvalid = true;
15984 break;
15985 case IntToBlockPointer:
15986 DiagKind = diag::err_int_to_block_pointer;
15987 isInvalid = true;
15988 break;
15989 case IncompatibleBlockPointer:
15990 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15991 isInvalid = true;
15992 break;
15993 case IncompatibleObjCQualifiedId: {
15994 if (SrcType->isObjCQualifiedIdType()) {
15995 const ObjCObjectPointerType *srcOPT =
15996 SrcType->castAs<ObjCObjectPointerType>();
15997 for (auto *srcProto : srcOPT->quals()) {
15998 PDecl = srcProto;
15999 break;
16000 }
16001 if (const ObjCInterfaceType *IFaceT =
16002 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16003 IFace = IFaceT->getDecl();
16004 }
16005 else if (DstType->isObjCQualifiedIdType()) {
16006 const ObjCObjectPointerType *dstOPT =
16007 DstType->castAs<ObjCObjectPointerType>();
16008 for (auto *dstProto : dstOPT->quals()) {
16009 PDecl = dstProto;
16010 break;
16011 }
16012 if (const ObjCInterfaceType *IFaceT =
16013 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
16014 IFace = IFaceT->getDecl();
16015 }
16016 if (getLangOpts().CPlusPlus) {
16017 DiagKind = diag::err_incompatible_qualified_id;
16018 isInvalid = true;
16019 } else {
16020 DiagKind = diag::warn_incompatible_qualified_id;
16021 }
16022 break;
16023 }
16024 case IncompatibleVectors:
16025 if (getLangOpts().CPlusPlus) {
16026 DiagKind = diag::err_incompatible_vectors;
16027 isInvalid = true;
16028 } else {
16029 DiagKind = diag::warn_incompatible_vectors;
16030 }
16031 break;
16032 case IncompatibleObjCWeakRef:
16033 DiagKind = diag::err_arc_weak_unavailable_assign;
16034 isInvalid = true;
16035 break;
16036 case Incompatible:
16037 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16038 if (Complained)
16039 *Complained = true;
16040 return true;
16041 }
16042
16043 DiagKind = diag::err_typecheck_convert_incompatible;
16044 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16045 MayHaveConvFixit = true;
16046 isInvalid = true;
16047 MayHaveFunctionDiff = true;
16048 break;
16049 }
16050
16051 QualType FirstType, SecondType;
16052 switch (Action) {
16053 case AA_Assigning:
16054 case AA_Initializing:
16055 // The destination type comes first.
16056 FirstType = DstType;
16057 SecondType = SrcType;
16058 break;
16059
16060 case AA_Returning:
16061 case AA_Passing:
16062 case AA_Passing_CFAudited:
16063 case AA_Converting:
16064 case AA_Sending:
16065 case AA_Casting:
16066 // The source type comes first.
16067 FirstType = SrcType;
16068 SecondType = DstType;
16069 break;
16070 }
16071
16072 PartialDiagnostic FDiag = PDiag(DiagKind);
16073 if (Action == AA_Passing_CFAudited)
16074 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
16075 else
16076 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
16077
16078 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16079 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16080 auto isPlainChar = [](const clang::Type *Type) {
16081 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16082 Type->isSpecificBuiltinType(BuiltinType::Char_U);
16083 };
16084 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16085 isPlainChar(SecondType->getPointeeOrArrayElementType()));
16086 }
16087
16088 // If we can fix the conversion, suggest the FixIts.
16089 if (!ConvHints.isNull()) {
16090 for (FixItHint &H : ConvHints.Hints)
16091 FDiag << H;
16092 }
16093
16094 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16095
16096 if (MayHaveFunctionDiff)
16097 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16098
16099 Diag(Loc, FDiag);
16100 if ((DiagKind == diag::warn_incompatible_qualified_id ||
16101 DiagKind == diag::err_incompatible_qualified_id) &&
16102 PDecl && IFace && !IFace->hasDefinition())
16103 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16104 << IFace << PDecl;
16105
16106 if (SecondType == Context.OverloadTy)
16107 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
16108 FirstType, /*TakingAddress=*/true);
16109
16110 if (CheckInferredResultType)
16111 EmitRelatedResultTypeNote(SrcExpr);
16112
16113 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16114 EmitRelatedResultTypeNoteForReturn(DstType);
16115
16116 if (Complained)
16117 *Complained = true;
16118 return isInvalid;
16119 }
16120
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,AllowFoldKind CanFold)16121 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16122 llvm::APSInt *Result,
16123 AllowFoldKind CanFold) {
16124 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16125 public:
16126 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16127 QualType T) override {
16128 return S.Diag(Loc, diag::err_ice_not_integral)
16129 << T << S.LangOpts.CPlusPlus;
16130 }
16131 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16132 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16133 }
16134 } Diagnoser;
16135
16136 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16137 }
16138
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,unsigned DiagID,AllowFoldKind CanFold)16139 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16140 llvm::APSInt *Result,
16141 unsigned DiagID,
16142 AllowFoldKind CanFold) {
16143 class IDDiagnoser : public VerifyICEDiagnoser {
16144 unsigned DiagID;
16145
16146 public:
16147 IDDiagnoser(unsigned DiagID)
16148 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16149
16150 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16151 return S.Diag(Loc, DiagID);
16152 }
16153 } Diagnoser(DiagID);
16154
16155 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16156 }
16157
16158 Sema::SemaDiagnosticBuilder
diagnoseNotICEType(Sema & S,SourceLocation Loc,QualType T)16159 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16160 QualType T) {
16161 return diagnoseNotICE(S, Loc);
16162 }
16163
16164 Sema::SemaDiagnosticBuilder
diagnoseFold(Sema & S,SourceLocation Loc)16165 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16166 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16167 }
16168
16169 ExprResult
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,VerifyICEDiagnoser & Diagnoser,AllowFoldKind CanFold)16170 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16171 VerifyICEDiagnoser &Diagnoser,
16172 AllowFoldKind CanFold) {
16173 SourceLocation DiagLoc = E->getBeginLoc();
16174
16175 if (getLangOpts().CPlusPlus11) {
16176 // C++11 [expr.const]p5:
16177 // If an expression of literal class type is used in a context where an
16178 // integral constant expression is required, then that class type shall
16179 // have a single non-explicit conversion function to an integral or
16180 // unscoped enumeration type
16181 ExprResult Converted;
16182 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16183 VerifyICEDiagnoser &BaseDiagnoser;
16184 public:
16185 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16186 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16187 BaseDiagnoser.Suppress, true),
16188 BaseDiagnoser(BaseDiagnoser) {}
16189
16190 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16191 QualType T) override {
16192 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16193 }
16194
16195 SemaDiagnosticBuilder diagnoseIncomplete(
16196 Sema &S, SourceLocation Loc, QualType T) override {
16197 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16198 }
16199
16200 SemaDiagnosticBuilder diagnoseExplicitConv(
16201 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16202 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16203 }
16204
16205 SemaDiagnosticBuilder noteExplicitConv(
16206 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16207 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16208 << ConvTy->isEnumeralType() << ConvTy;
16209 }
16210
16211 SemaDiagnosticBuilder diagnoseAmbiguous(
16212 Sema &S, SourceLocation Loc, QualType T) override {
16213 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16214 }
16215
16216 SemaDiagnosticBuilder noteAmbiguous(
16217 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16218 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16219 << ConvTy->isEnumeralType() << ConvTy;
16220 }
16221
16222 SemaDiagnosticBuilder diagnoseConversion(
16223 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16224 llvm_unreachable("conversion functions are permitted");
16225 }
16226 } ConvertDiagnoser(Diagnoser);
16227
16228 Converted = PerformContextualImplicitConversion(DiagLoc, E,
16229 ConvertDiagnoser);
16230 if (Converted.isInvalid())
16231 return Converted;
16232 E = Converted.get();
16233 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16234 return ExprError();
16235 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16236 // An ICE must be of integral or unscoped enumeration type.
16237 if (!Diagnoser.Suppress)
16238 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16239 << E->getSourceRange();
16240 return ExprError();
16241 }
16242
16243 ExprResult RValueExpr = DefaultLvalueConversion(E);
16244 if (RValueExpr.isInvalid())
16245 return ExprError();
16246
16247 E = RValueExpr.get();
16248
16249 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16250 // in the non-ICE case.
16251 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16252 if (Result)
16253 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16254 if (!isa<ConstantExpr>(E))
16255 E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))
16256 : ConstantExpr::Create(Context, E);
16257 return E;
16258 }
16259
16260 Expr::EvalResult EvalResult;
16261 SmallVector<PartialDiagnosticAt, 8> Notes;
16262 EvalResult.Diag = &Notes;
16263
16264 // Try to evaluate the expression, and produce diagnostics explaining why it's
16265 // not a constant expression as a side-effect.
16266 bool Folded =
16267 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16268 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16269
16270 if (!isa<ConstantExpr>(E))
16271 E = ConstantExpr::Create(Context, E, EvalResult.Val);
16272
16273 // In C++11, we can rely on diagnostics being produced for any expression
16274 // which is not a constant expression. If no diagnostics were produced, then
16275 // this is a constant expression.
16276 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16277 if (Result)
16278 *Result = EvalResult.Val.getInt();
16279 return E;
16280 }
16281
16282 // If our only note is the usual "invalid subexpression" note, just point
16283 // the caret at its location rather than producing an essentially
16284 // redundant note.
16285 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16286 diag::note_invalid_subexpr_in_const_expr) {
16287 DiagLoc = Notes[0].first;
16288 Notes.clear();
16289 }
16290
16291 if (!Folded || !CanFold) {
16292 if (!Diagnoser.Suppress) {
16293 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16294 for (const PartialDiagnosticAt &Note : Notes)
16295 Diag(Note.first, Note.second);
16296 }
16297
16298 return ExprError();
16299 }
16300
16301 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16302 for (const PartialDiagnosticAt &Note : Notes)
16303 Diag(Note.first, Note.second);
16304
16305 if (Result)
16306 *Result = EvalResult.Val.getInt();
16307 return E;
16308 }
16309
16310 namespace {
16311 // Handle the case where we conclude a expression which we speculatively
16312 // considered to be unevaluated is actually evaluated.
16313 class TransformToPE : public TreeTransform<TransformToPE> {
16314 typedef TreeTransform<TransformToPE> BaseTransform;
16315
16316 public:
TransformToPE(Sema & SemaRef)16317 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16318
16319 // Make sure we redo semantic analysis
AlwaysRebuild()16320 bool AlwaysRebuild() { return true; }
ReplacingOriginal()16321 bool ReplacingOriginal() { return true; }
16322
16323 // We need to special-case DeclRefExprs referring to FieldDecls which
16324 // are not part of a member pointer formation; normal TreeTransforming
16325 // doesn't catch this case because of the way we represent them in the AST.
16326 // FIXME: This is a bit ugly; is it really the best way to handle this
16327 // case?
16328 //
16329 // Error on DeclRefExprs referring to FieldDecls.
TransformDeclRefExpr(DeclRefExpr * E)16330 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16331 if (isa<FieldDecl>(E->getDecl()) &&
16332 !SemaRef.isUnevaluatedContext())
16333 return SemaRef.Diag(E->getLocation(),
16334 diag::err_invalid_non_static_member_use)
16335 << E->getDecl() << E->getSourceRange();
16336
16337 return BaseTransform::TransformDeclRefExpr(E);
16338 }
16339
16340 // Exception: filter out member pointer formation
TransformUnaryOperator(UnaryOperator * E)16341 ExprResult TransformUnaryOperator(UnaryOperator *E) {
16342 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16343 return E;
16344
16345 return BaseTransform::TransformUnaryOperator(E);
16346 }
16347
16348 // The body of a lambda-expression is in a separate expression evaluation
16349 // context so never needs to be transformed.
16350 // FIXME: Ideally we wouldn't transform the closure type either, and would
16351 // just recreate the capture expressions and lambda expression.
TransformLambdaBody(LambdaExpr * E,Stmt * Body)16352 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16353 return SkipLambdaBody(E, Body);
16354 }
16355 };
16356 }
16357
TransformToPotentiallyEvaluated(Expr * E)16358 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16359 assert(isUnevaluatedContext() &&
16360 "Should only transform unevaluated expressions");
16361 ExprEvalContexts.back().Context =
16362 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16363 if (isUnevaluatedContext())
16364 return E;
16365 return TransformToPE(*this).TransformExpr(E);
16366 }
16367
16368 void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,Decl * LambdaContextDecl,ExpressionEvaluationContextRecord::ExpressionKind ExprContext)16369 Sema::PushExpressionEvaluationContext(
16370 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16371 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16372 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16373 LambdaContextDecl, ExprContext);
16374 Cleanup.reset();
16375 if (!MaybeODRUseExprs.empty())
16376 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16377 }
16378
16379 void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,ReuseLambdaContextDecl_t,ExpressionEvaluationContextRecord::ExpressionKind ExprContext)16380 Sema::PushExpressionEvaluationContext(
16381 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16382 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16383 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16384 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16385 }
16386
16387 namespace {
16388
CheckPossibleDeref(Sema & S,const Expr * PossibleDeref)16389 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16390 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16391 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16392 if (E->getOpcode() == UO_Deref)
16393 return CheckPossibleDeref(S, E->getSubExpr());
16394 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16395 return CheckPossibleDeref(S, E->getBase());
16396 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16397 return CheckPossibleDeref(S, E->getBase());
16398 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16399 QualType Inner;
16400 QualType Ty = E->getType();
16401 if (const auto *Ptr = Ty->getAs<PointerType>())
16402 Inner = Ptr->getPointeeType();
16403 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16404 Inner = Arr->getElementType();
16405 else
16406 return nullptr;
16407
16408 if (Inner->hasAttr(attr::NoDeref))
16409 return E;
16410 }
16411 return nullptr;
16412 }
16413
16414 } // namespace
16415
WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord & Rec)16416 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16417 for (const Expr *E : Rec.PossibleDerefs) {
16418 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16419 if (DeclRef) {
16420 const ValueDecl *Decl = DeclRef->getDecl();
16421 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16422 << Decl->getName() << E->getSourceRange();
16423 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16424 } else {
16425 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16426 << E->getSourceRange();
16427 }
16428 }
16429 Rec.PossibleDerefs.clear();
16430 }
16431
16432 /// Check whether E, which is either a discarded-value expression or an
16433 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16434 /// and if so, remove it from the list of volatile-qualified assignments that
16435 /// we are going to warn are deprecated.
CheckUnusedVolatileAssignment(Expr * E)16436 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16437 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16438 return;
16439
16440 // Note: ignoring parens here is not justified by the standard rules, but
16441 // ignoring parentheses seems like a more reasonable approach, and this only
16442 // drives a deprecation warning so doesn't affect conformance.
16443 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16444 if (BO->getOpcode() == BO_Assign) {
16445 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16446 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16447 LHSs.end());
16448 }
16449 }
16450 }
16451
CheckForImmediateInvocation(ExprResult E,FunctionDecl * Decl)16452 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16453 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16454 RebuildingImmediateInvocation)
16455 return E;
16456
16457 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16458 /// It's OK if this fails; we'll also remove this in
16459 /// HandleImmediateInvocations, but catching it here allows us to avoid
16460 /// walking the AST looking for it in simple cases.
16461 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16462 if (auto *DeclRef =
16463 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16464 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16465
16466 E = MaybeCreateExprWithCleanups(E);
16467
16468 ConstantExpr *Res = ConstantExpr::Create(
16469 getASTContext(), E.get(),
16470 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16471 getASTContext()),
16472 /*IsImmediateInvocation*/ true);
16473 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16474 return Res;
16475 }
16476
EvaluateAndDiagnoseImmediateInvocation(Sema & SemaRef,Sema::ImmediateInvocationCandidate Candidate)16477 static void EvaluateAndDiagnoseImmediateInvocation(
16478 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16479 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16480 Expr::EvalResult Eval;
16481 Eval.Diag = &Notes;
16482 ConstantExpr *CE = Candidate.getPointer();
16483 bool Result = CE->EvaluateAsConstantExpr(
16484 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
16485 if (!Result || !Notes.empty()) {
16486 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16487 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16488 InnerExpr = FunctionalCast->getSubExpr();
16489 FunctionDecl *FD = nullptr;
16490 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16491 FD = cast<FunctionDecl>(Call->getCalleeDecl());
16492 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16493 FD = Call->getConstructor();
16494 else
16495 llvm_unreachable("unhandled decl kind");
16496 assert(FD->isConsteval());
16497 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16498 for (auto &Note : Notes)
16499 SemaRef.Diag(Note.first, Note.second);
16500 return;
16501 }
16502 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16503 }
16504
RemoveNestedImmediateInvocation(Sema & SemaRef,Sema::ExpressionEvaluationContextRecord & Rec,SmallVector<Sema::ImmediateInvocationCandidate,4>::reverse_iterator It)16505 static void RemoveNestedImmediateInvocation(
16506 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16507 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16508 struct ComplexRemove : TreeTransform<ComplexRemove> {
16509 using Base = TreeTransform<ComplexRemove>;
16510 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16511 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16512 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16513 CurrentII;
16514 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16515 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16516 SmallVector<Sema::ImmediateInvocationCandidate,
16517 4>::reverse_iterator Current)
16518 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16519 void RemoveImmediateInvocation(ConstantExpr* E) {
16520 auto It = std::find_if(CurrentII, IISet.rend(),
16521 [E](Sema::ImmediateInvocationCandidate Elem) {
16522 return Elem.getPointer() == E;
16523 });
16524 assert(It != IISet.rend() &&
16525 "ConstantExpr marked IsImmediateInvocation should "
16526 "be present");
16527 It->setInt(1); // Mark as deleted
16528 }
16529 ExprResult TransformConstantExpr(ConstantExpr *E) {
16530 if (!E->isImmediateInvocation())
16531 return Base::TransformConstantExpr(E);
16532 RemoveImmediateInvocation(E);
16533 return Base::TransformExpr(E->getSubExpr());
16534 }
16535 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16536 /// we need to remove its DeclRefExpr from the DRSet.
16537 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16538 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16539 return Base::TransformCXXOperatorCallExpr(E);
16540 }
16541 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16542 /// here.
16543 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16544 if (!Init)
16545 return Init;
16546 /// ConstantExpr are the first layer of implicit node to be removed so if
16547 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16548 if (auto *CE = dyn_cast<ConstantExpr>(Init))
16549 if (CE->isImmediateInvocation())
16550 RemoveImmediateInvocation(CE);
16551 return Base::TransformInitializer(Init, NotCopyInit);
16552 }
16553 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16554 DRSet.erase(E);
16555 return E;
16556 }
16557 bool AlwaysRebuild() { return false; }
16558 bool ReplacingOriginal() { return true; }
16559 bool AllowSkippingCXXConstructExpr() {
16560 bool Res = AllowSkippingFirstCXXConstructExpr;
16561 AllowSkippingFirstCXXConstructExpr = true;
16562 return Res;
16563 }
16564 bool AllowSkippingFirstCXXConstructExpr = true;
16565 } Transformer(SemaRef, Rec.ReferenceToConsteval,
16566 Rec.ImmediateInvocationCandidates, It);
16567
16568 /// CXXConstructExpr with a single argument are getting skipped by
16569 /// TreeTransform in some situtation because they could be implicit. This
16570 /// can only occur for the top-level CXXConstructExpr because it is used
16571 /// nowhere in the expression being transformed therefore will not be rebuilt.
16572 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16573 /// skipping the first CXXConstructExpr.
16574 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16575 Transformer.AllowSkippingFirstCXXConstructExpr = false;
16576
16577 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16578 assert(Res.isUsable());
16579 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16580 It->getPointer()->setSubExpr(Res.get());
16581 }
16582
16583 static void
HandleImmediateInvocations(Sema & SemaRef,Sema::ExpressionEvaluationContextRecord & Rec)16584 HandleImmediateInvocations(Sema &SemaRef,
16585 Sema::ExpressionEvaluationContextRecord &Rec) {
16586 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16587 Rec.ReferenceToConsteval.size() == 0) ||
16588 SemaRef.RebuildingImmediateInvocation)
16589 return;
16590
16591 /// When we have more then 1 ImmediateInvocationCandidates we need to check
16592 /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16593 /// need to remove ReferenceToConsteval in the immediate invocation.
16594 if (Rec.ImmediateInvocationCandidates.size() > 1) {
16595
16596 /// Prevent sema calls during the tree transform from adding pointers that
16597 /// are already in the sets.
16598 llvm::SaveAndRestore<bool> DisableIITracking(
16599 SemaRef.RebuildingImmediateInvocation, true);
16600
16601 /// Prevent diagnostic during tree transfrom as they are duplicates
16602 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16603
16604 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16605 It != Rec.ImmediateInvocationCandidates.rend(); It++)
16606 if (!It->getInt())
16607 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16608 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16609 Rec.ReferenceToConsteval.size()) {
16610 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16611 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16612 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16613 bool VisitDeclRefExpr(DeclRefExpr *E) {
16614 DRSet.erase(E);
16615 return DRSet.size();
16616 }
16617 } Visitor(Rec.ReferenceToConsteval);
16618 Visitor.TraverseStmt(
16619 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16620 }
16621 for (auto CE : Rec.ImmediateInvocationCandidates)
16622 if (!CE.getInt())
16623 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16624 for (auto DR : Rec.ReferenceToConsteval) {
16625 auto *FD = cast<FunctionDecl>(DR->getDecl());
16626 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16627 << FD;
16628 SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16629 }
16630 }
16631
PopExpressionEvaluationContext()16632 void Sema::PopExpressionEvaluationContext() {
16633 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16634 unsigned NumTypos = Rec.NumTypos;
16635
16636 if (!Rec.Lambdas.empty()) {
16637 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16638 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16639 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16640 unsigned D;
16641 if (Rec.isUnevaluated()) {
16642 // C++11 [expr.prim.lambda]p2:
16643 // A lambda-expression shall not appear in an unevaluated operand
16644 // (Clause 5).
16645 D = diag::err_lambda_unevaluated_operand;
16646 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16647 // C++1y [expr.const]p2:
16648 // A conditional-expression e is a core constant expression unless the
16649 // evaluation of e, following the rules of the abstract machine, would
16650 // evaluate [...] a lambda-expression.
16651 D = diag::err_lambda_in_constant_expression;
16652 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16653 // C++17 [expr.prim.lamda]p2:
16654 // A lambda-expression shall not appear [...] in a template-argument.
16655 D = diag::err_lambda_in_invalid_context;
16656 } else
16657 llvm_unreachable("Couldn't infer lambda error message.");
16658
16659 for (const auto *L : Rec.Lambdas)
16660 Diag(L->getBeginLoc(), D);
16661 }
16662 }
16663
16664 WarnOnPendingNoDerefs(Rec);
16665 HandleImmediateInvocations(*this, Rec);
16666
16667 // Warn on any volatile-qualified simple-assignments that are not discarded-
16668 // value expressions nor unevaluated operands (those cases get removed from
16669 // this list by CheckUnusedVolatileAssignment).
16670 for (auto *BO : Rec.VolatileAssignmentLHSs)
16671 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16672 << BO->getType();
16673
16674 // When are coming out of an unevaluated context, clear out any
16675 // temporaries that we may have created as part of the evaluation of
16676 // the expression in that context: they aren't relevant because they
16677 // will never be constructed.
16678 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16679 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16680 ExprCleanupObjects.end());
16681 Cleanup = Rec.ParentCleanup;
16682 CleanupVarDeclMarking();
16683 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16684 // Otherwise, merge the contexts together.
16685 } else {
16686 Cleanup.mergeFrom(Rec.ParentCleanup);
16687 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16688 Rec.SavedMaybeODRUseExprs.end());
16689 }
16690
16691 // Pop the current expression evaluation context off the stack.
16692 ExprEvalContexts.pop_back();
16693
16694 // The global expression evaluation context record is never popped.
16695 ExprEvalContexts.back().NumTypos += NumTypos;
16696 }
16697
DiscardCleanupsInEvaluationContext()16698 void Sema::DiscardCleanupsInEvaluationContext() {
16699 ExprCleanupObjects.erase(
16700 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16701 ExprCleanupObjects.end());
16702 Cleanup.reset();
16703 MaybeODRUseExprs.clear();
16704 }
16705
HandleExprEvaluationContextForTypeof(Expr * E)16706 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16707 ExprResult Result = CheckPlaceholderExpr(E);
16708 if (Result.isInvalid())
16709 return ExprError();
16710 E = Result.get();
16711 if (!E->getType()->isVariablyModifiedType())
16712 return E;
16713 return TransformToPotentiallyEvaluated(E);
16714 }
16715
16716 /// Are we in a context that is potentially constant evaluated per C++20
16717 /// [expr.const]p12?
isPotentiallyConstantEvaluatedContext(Sema & SemaRef)16718 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16719 /// C++2a [expr.const]p12:
16720 // An expression or conversion is potentially constant evaluated if it is
16721 switch (SemaRef.ExprEvalContexts.back().Context) {
16722 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16723 // -- a manifestly constant-evaluated expression,
16724 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16725 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16726 case Sema::ExpressionEvaluationContext::DiscardedStatement:
16727 // -- a potentially-evaluated expression,
16728 case Sema::ExpressionEvaluationContext::UnevaluatedList:
16729 // -- an immediate subexpression of a braced-init-list,
16730
16731 // -- [FIXME] an expression of the form & cast-expression that occurs
16732 // within a templated entity
16733 // -- a subexpression of one of the above that is not a subexpression of
16734 // a nested unevaluated operand.
16735 return true;
16736
16737 case Sema::ExpressionEvaluationContext::Unevaluated:
16738 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16739 // Expressions in this context are never evaluated.
16740 return false;
16741 }
16742 llvm_unreachable("Invalid context");
16743 }
16744
16745 /// Return true if this function has a calling convention that requires mangling
16746 /// in the size of the parameter pack.
funcHasParameterSizeMangling(Sema & S,FunctionDecl * FD)16747 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16748 // These manglings don't do anything on non-Windows or non-x86 platforms, so
16749 // we don't need parameter type sizes.
16750 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16751 if (!TT.isOSWindows() || !TT.isX86())
16752 return false;
16753
16754 // If this is C++ and this isn't an extern "C" function, parameters do not
16755 // need to be complete. In this case, C++ mangling will apply, which doesn't
16756 // use the size of the parameters.
16757 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16758 return false;
16759
16760 // Stdcall, fastcall, and vectorcall need this special treatment.
16761 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16762 switch (CC) {
16763 case CC_X86StdCall:
16764 case CC_X86FastCall:
16765 case CC_X86VectorCall:
16766 return true;
16767 default:
16768 break;
16769 }
16770 return false;
16771 }
16772
16773 /// Require that all of the parameter types of function be complete. Normally,
16774 /// parameter types are only required to be complete when a function is called
16775 /// or defined, but to mangle functions with certain calling conventions, the
16776 /// mangler needs to know the size of the parameter list. In this situation,
16777 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16778 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16779 /// result in a linker error. Clang doesn't implement this behavior, and instead
16780 /// attempts to error at compile time.
CheckCompleteParameterTypesForMangler(Sema & S,FunctionDecl * FD,SourceLocation Loc)16781 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16782 SourceLocation Loc) {
16783 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16784 FunctionDecl *FD;
16785 ParmVarDecl *Param;
16786
16787 public:
16788 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16789 : FD(FD), Param(Param) {}
16790
16791 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16792 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16793 StringRef CCName;
16794 switch (CC) {
16795 case CC_X86StdCall:
16796 CCName = "stdcall";
16797 break;
16798 case CC_X86FastCall:
16799 CCName = "fastcall";
16800 break;
16801 case CC_X86VectorCall:
16802 CCName = "vectorcall";
16803 break;
16804 default:
16805 llvm_unreachable("CC does not need mangling");
16806 }
16807
16808 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16809 << Param->getDeclName() << FD->getDeclName() << CCName;
16810 }
16811 };
16812
16813 for (ParmVarDecl *Param : FD->parameters()) {
16814 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16815 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16816 }
16817 }
16818
16819 namespace {
16820 enum class OdrUseContext {
16821 /// Declarations in this context are not odr-used.
16822 None,
16823 /// Declarations in this context are formally odr-used, but this is a
16824 /// dependent context.
16825 Dependent,
16826 /// Declarations in this context are odr-used but not actually used (yet).
16827 FormallyOdrUsed,
16828 /// Declarations in this context are used.
16829 Used
16830 };
16831 }
16832
16833 /// Are we within a context in which references to resolved functions or to
16834 /// variables result in odr-use?
isOdrUseContext(Sema & SemaRef)16835 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16836 OdrUseContext Result;
16837
16838 switch (SemaRef.ExprEvalContexts.back().Context) {
16839 case Sema::ExpressionEvaluationContext::Unevaluated:
16840 case Sema::ExpressionEvaluationContext::UnevaluatedList:
16841 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16842 return OdrUseContext::None;
16843
16844 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16845 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16846 Result = OdrUseContext::Used;
16847 break;
16848
16849 case Sema::ExpressionEvaluationContext::DiscardedStatement:
16850 Result = OdrUseContext::FormallyOdrUsed;
16851 break;
16852
16853 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16854 // A default argument formally results in odr-use, but doesn't actually
16855 // result in a use in any real sense until it itself is used.
16856 Result = OdrUseContext::FormallyOdrUsed;
16857 break;
16858 }
16859
16860 if (SemaRef.CurContext->isDependentContext())
16861 return OdrUseContext::Dependent;
16862
16863 return Result;
16864 }
16865
isImplicitlyDefinableConstexprFunction(FunctionDecl * Func)16866 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16867 if (!Func->isConstexpr())
16868 return false;
16869
16870 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
16871 return true;
16872 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
16873 return CCD && CCD->getInheritedConstructor();
16874 }
16875
16876 /// Mark a function referenced, and check whether it is odr-used
16877 /// (C++ [basic.def.odr]p2, C99 6.9p3)
MarkFunctionReferenced(SourceLocation Loc,FunctionDecl * Func,bool MightBeOdrUse)16878 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16879 bool MightBeOdrUse) {
16880 assert(Func && "No function?");
16881
16882 Func->setReferenced();
16883
16884 // Recursive functions aren't really used until they're used from some other
16885 // context.
16886 bool IsRecursiveCall = CurContext == Func;
16887
16888 // C++11 [basic.def.odr]p3:
16889 // A function whose name appears as a potentially-evaluated expression is
16890 // odr-used if it is the unique lookup result or the selected member of a
16891 // set of overloaded functions [...].
16892 //
16893 // We (incorrectly) mark overload resolution as an unevaluated context, so we
16894 // can just check that here.
16895 OdrUseContext OdrUse =
16896 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16897 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16898 OdrUse = OdrUseContext::FormallyOdrUsed;
16899
16900 // Trivial default constructors and destructors are never actually used.
16901 // FIXME: What about other special members?
16902 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16903 OdrUse == OdrUseContext::Used) {
16904 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16905 if (Constructor->isDefaultConstructor())
16906 OdrUse = OdrUseContext::FormallyOdrUsed;
16907 if (isa<CXXDestructorDecl>(Func))
16908 OdrUse = OdrUseContext::FormallyOdrUsed;
16909 }
16910
16911 // C++20 [expr.const]p12:
16912 // A function [...] is needed for constant evaluation if it is [...] a
16913 // constexpr function that is named by an expression that is potentially
16914 // constant evaluated
16915 bool NeededForConstantEvaluation =
16916 isPotentiallyConstantEvaluatedContext(*this) &&
16917 isImplicitlyDefinableConstexprFunction(Func);
16918
16919 // Determine whether we require a function definition to exist, per
16920 // C++11 [temp.inst]p3:
16921 // Unless a function template specialization has been explicitly
16922 // instantiated or explicitly specialized, the function template
16923 // specialization is implicitly instantiated when the specialization is
16924 // referenced in a context that requires a function definition to exist.
16925 // C++20 [temp.inst]p7:
16926 // The existence of a definition of a [...] function is considered to
16927 // affect the semantics of the program if the [...] function is needed for
16928 // constant evaluation by an expression
16929 // C++20 [basic.def.odr]p10:
16930 // Every program shall contain exactly one definition of every non-inline
16931 // function or variable that is odr-used in that program outside of a
16932 // discarded statement
16933 // C++20 [special]p1:
16934 // The implementation will implicitly define [defaulted special members]
16935 // if they are odr-used or needed for constant evaluation.
16936 //
16937 // Note that we skip the implicit instantiation of templates that are only
16938 // used in unused default arguments or by recursive calls to themselves.
16939 // This is formally non-conforming, but seems reasonable in practice.
16940 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16941 NeededForConstantEvaluation);
16942
16943 // C++14 [temp.expl.spec]p6:
16944 // If a template [...] is explicitly specialized then that specialization
16945 // shall be declared before the first use of that specialization that would
16946 // cause an implicit instantiation to take place, in every translation unit
16947 // in which such a use occurs
16948 if (NeedDefinition &&
16949 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16950 Func->getMemberSpecializationInfo()))
16951 checkSpecializationVisibility(Loc, Func);
16952
16953 if (getLangOpts().CUDA)
16954 CheckCUDACall(Loc, Func);
16955
16956 if (getLangOpts().SYCLIsDevice)
16957 checkSYCLDeviceFunction(Loc, Func);
16958
16959 // If we need a definition, try to create one.
16960 if (NeedDefinition && !Func->getBody()) {
16961 runWithSufficientStackSpace(Loc, [&] {
16962 if (CXXConstructorDecl *Constructor =
16963 dyn_cast<CXXConstructorDecl>(Func)) {
16964 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16965 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16966 if (Constructor->isDefaultConstructor()) {
16967 if (Constructor->isTrivial() &&
16968 !Constructor->hasAttr<DLLExportAttr>())
16969 return;
16970 DefineImplicitDefaultConstructor(Loc, Constructor);
16971 } else if (Constructor->isCopyConstructor()) {
16972 DefineImplicitCopyConstructor(Loc, Constructor);
16973 } else if (Constructor->isMoveConstructor()) {
16974 DefineImplicitMoveConstructor(Loc, Constructor);
16975 }
16976 } else if (Constructor->getInheritedConstructor()) {
16977 DefineInheritingConstructor(Loc, Constructor);
16978 }
16979 } else if (CXXDestructorDecl *Destructor =
16980 dyn_cast<CXXDestructorDecl>(Func)) {
16981 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16982 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16983 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16984 return;
16985 DefineImplicitDestructor(Loc, Destructor);
16986 }
16987 if (Destructor->isVirtual() && getLangOpts().AppleKext)
16988 MarkVTableUsed(Loc, Destructor->getParent());
16989 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16990 if (MethodDecl->isOverloadedOperator() &&
16991 MethodDecl->getOverloadedOperator() == OO_Equal) {
16992 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16993 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16994 if (MethodDecl->isCopyAssignmentOperator())
16995 DefineImplicitCopyAssignment(Loc, MethodDecl);
16996 else if (MethodDecl->isMoveAssignmentOperator())
16997 DefineImplicitMoveAssignment(Loc, MethodDecl);
16998 }
16999 } else if (isa<CXXConversionDecl>(MethodDecl) &&
17000 MethodDecl->getParent()->isLambda()) {
17001 CXXConversionDecl *Conversion =
17002 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17003 if (Conversion->isLambdaToBlockPointerConversion())
17004 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
17005 else
17006 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
17007 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17008 MarkVTableUsed(Loc, MethodDecl->getParent());
17009 }
17010
17011 if (Func->isDefaulted() && !Func->isDeleted()) {
17012 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
17013 if (DCK != DefaultedComparisonKind::None)
17014 DefineDefaultedComparison(Loc, Func, DCK);
17015 }
17016
17017 // Implicit instantiation of function templates and member functions of
17018 // class templates.
17019 if (Func->isImplicitlyInstantiable()) {
17020 TemplateSpecializationKind TSK =
17021 Func->getTemplateSpecializationKindForInstantiation();
17022 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17023 bool FirstInstantiation = PointOfInstantiation.isInvalid();
17024 if (FirstInstantiation) {
17025 PointOfInstantiation = Loc;
17026 if (auto *MSI = Func->getMemberSpecializationInfo())
17027 MSI->setPointOfInstantiation(Loc);
17028 // FIXME: Notify listener.
17029 else
17030 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17031 } else if (TSK != TSK_ImplicitInstantiation) {
17032 // Use the point of use as the point of instantiation, instead of the
17033 // point of explicit instantiation (which we track as the actual point
17034 // of instantiation). This gives better backtraces in diagnostics.
17035 PointOfInstantiation = Loc;
17036 }
17037
17038 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17039 Func->isConstexpr()) {
17040 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
17041 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
17042 CodeSynthesisContexts.size())
17043 PendingLocalImplicitInstantiations.push_back(
17044 std::make_pair(Func, PointOfInstantiation));
17045 else if (Func->isConstexpr())
17046 // Do not defer instantiations of constexpr functions, to avoid the
17047 // expression evaluator needing to call back into Sema if it sees a
17048 // call to such a function.
17049 InstantiateFunctionDefinition(PointOfInstantiation, Func);
17050 else {
17051 Func->setInstantiationIsPending(true);
17052 PendingInstantiations.push_back(
17053 std::make_pair(Func, PointOfInstantiation));
17054 // Notify the consumer that a function was implicitly instantiated.
17055 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
17056 }
17057 }
17058 } else {
17059 // Walk redefinitions, as some of them may be instantiable.
17060 for (auto i : Func->redecls()) {
17061 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
17062 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
17063 }
17064 }
17065 });
17066 }
17067
17068 // C++14 [except.spec]p17:
17069 // An exception-specification is considered to be needed when:
17070 // - the function is odr-used or, if it appears in an unevaluated operand,
17071 // would be odr-used if the expression were potentially-evaluated;
17072 //
17073 // Note, we do this even if MightBeOdrUse is false. That indicates that the
17074 // function is a pure virtual function we're calling, and in that case the
17075 // function was selected by overload resolution and we need to resolve its
17076 // exception specification for a different reason.
17077 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
17078 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
17079 ResolveExceptionSpec(Loc, FPT);
17080
17081 // If this is the first "real" use, act on that.
17082 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
17083 // Keep track of used but undefined functions.
17084 if (!Func->isDefined()) {
17085 if (mightHaveNonExternalLinkage(Func))
17086 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17087 else if (Func->getMostRecentDecl()->isInlined() &&
17088 !LangOpts.GNUInline &&
17089 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
17090 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17091 else if (isExternalWithNoLinkageType(Func))
17092 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
17093 }
17094
17095 // Some x86 Windows calling conventions mangle the size of the parameter
17096 // pack into the name. Computing the size of the parameters requires the
17097 // parameter types to be complete. Check that now.
17098 if (funcHasParameterSizeMangling(*this, Func))
17099 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
17100
17101 // In the MS C++ ABI, the compiler emits destructor variants where they are
17102 // used. If the destructor is used here but defined elsewhere, mark the
17103 // virtual base destructors referenced. If those virtual base destructors
17104 // are inline, this will ensure they are defined when emitting the complete
17105 // destructor variant. This checking may be redundant if the destructor is
17106 // provided later in this TU.
17107 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17108 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
17109 CXXRecordDecl *Parent = Dtor->getParent();
17110 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
17111 CheckCompleteDestructorVariant(Loc, Dtor);
17112 }
17113 }
17114
17115 Func->markUsed(Context);
17116 }
17117 }
17118
17119 /// Directly mark a variable odr-used. Given a choice, prefer to use
17120 /// MarkVariableReferenced since it does additional checks and then
17121 /// calls MarkVarDeclODRUsed.
17122 /// If the variable must be captured:
17123 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
17124 /// - else capture it in the DeclContext that maps to the
17125 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
17126 static void
MarkVarDeclODRUsed(VarDecl * Var,SourceLocation Loc,Sema & SemaRef,const unsigned * const FunctionScopeIndexToStopAt=nullptr)17127 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
17128 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
17129 // Keep track of used but undefined variables.
17130 // FIXME: We shouldn't suppress this warning for static data members.
17131 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17132 (!Var->isExternallyVisible() || Var->isInline() ||
17133 SemaRef.isExternalWithNoLinkageType(Var)) &&
17134 !(Var->isStaticDataMember() && Var->hasInit())) {
17135 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17136 if (old.isInvalid())
17137 old = Loc;
17138 }
17139 QualType CaptureType, DeclRefType;
17140 if (SemaRef.LangOpts.OpenMP)
17141 SemaRef.tryCaptureOpenMPLambdas(Var);
17142 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17143 /*EllipsisLoc*/ SourceLocation(),
17144 /*BuildAndDiagnose*/ true,
17145 CaptureType, DeclRefType,
17146 FunctionScopeIndexToStopAt);
17147
17148 if (SemaRef.LangOpts.CUDA && Var && Var->hasGlobalStorage()) {
17149 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
17150 auto VarTarget = SemaRef.IdentifyCUDATarget(Var);
17151 auto UserTarget = SemaRef.IdentifyCUDATarget(FD);
17152 if (VarTarget == Sema::CVT_Host &&
17153 (UserTarget == Sema::CFT_Device || UserTarget == Sema::CFT_HostDevice ||
17154 UserTarget == Sema::CFT_Global)) {
17155 // Diagnose ODR-use of host global variables in device functions.
17156 // Reference of device global variables in host functions is allowed
17157 // through shadow variables therefore it is not diagnosed.
17158 if (SemaRef.LangOpts.CUDAIsDevice)
17159 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
17160 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
17161 } else if (VarTarget == Sema::CVT_Device &&
17162 (UserTarget == Sema::CFT_Host ||
17163 UserTarget == Sema::CFT_HostDevice) &&
17164 !Var->hasExternalStorage()) {
17165 // Record a CUDA/HIP device side variable if it is ODR-used
17166 // by host code. This is done conservatively, when the variable is
17167 // referenced in any of the following contexts:
17168 // - a non-function context
17169 // - a host function
17170 // - a host device function
17171 // This makes the ODR-use of the device side variable by host code to
17172 // be visible in the device compilation for the compiler to be able to
17173 // emit template variables instantiated by host code only and to
17174 // externalize the static device side variable ODR-used by host code.
17175 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);
17176 }
17177 }
17178
17179 Var->markUsed(SemaRef.Context);
17180 }
17181
MarkCaptureUsedInEnclosingContext(VarDecl * Capture,SourceLocation Loc,unsigned CapturingScopeIndex)17182 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17183 SourceLocation Loc,
17184 unsigned CapturingScopeIndex) {
17185 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17186 }
17187
17188 static void
diagnoseUncapturableValueReference(Sema & S,SourceLocation loc,ValueDecl * var,DeclContext * DC)17189 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17190 ValueDecl *var, DeclContext *DC) {
17191 DeclContext *VarDC = var->getDeclContext();
17192
17193 // If the parameter still belongs to the translation unit, then
17194 // we're actually just using one parameter in the declaration of
17195 // the next.
17196 if (isa<ParmVarDecl>(var) &&
17197 isa<TranslationUnitDecl>(VarDC))
17198 return;
17199
17200 // For C code, don't diagnose about capture if we're not actually in code
17201 // right now; it's impossible to write a non-constant expression outside of
17202 // function context, so we'll get other (more useful) diagnostics later.
17203 //
17204 // For C++, things get a bit more nasty... it would be nice to suppress this
17205 // diagnostic for certain cases like using a local variable in an array bound
17206 // for a member of a local class, but the correct predicate is not obvious.
17207 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17208 return;
17209
17210 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17211 unsigned ContextKind = 3; // unknown
17212 if (isa<CXXMethodDecl>(VarDC) &&
17213 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17214 ContextKind = 2;
17215 } else if (isa<FunctionDecl>(VarDC)) {
17216 ContextKind = 0;
17217 } else if (isa<BlockDecl>(VarDC)) {
17218 ContextKind = 1;
17219 }
17220
17221 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17222 << var << ValueKind << ContextKind << VarDC;
17223 S.Diag(var->getLocation(), diag::note_entity_declared_at)
17224 << var;
17225
17226 // FIXME: Add additional diagnostic info about class etc. which prevents
17227 // capture.
17228 }
17229
17230
isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo * CSI,VarDecl * Var,bool & SubCapturesAreNested,QualType & CaptureType,QualType & DeclRefType)17231 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17232 bool &SubCapturesAreNested,
17233 QualType &CaptureType,
17234 QualType &DeclRefType) {
17235 // Check whether we've already captured it.
17236 if (CSI->CaptureMap.count(Var)) {
17237 // If we found a capture, any subcaptures are nested.
17238 SubCapturesAreNested = true;
17239
17240 // Retrieve the capture type for this variable.
17241 CaptureType = CSI->getCapture(Var).getCaptureType();
17242
17243 // Compute the type of an expression that refers to this variable.
17244 DeclRefType = CaptureType.getNonReferenceType();
17245
17246 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17247 // are mutable in the sense that user can change their value - they are
17248 // private instances of the captured declarations.
17249 const Capture &Cap = CSI->getCapture(Var);
17250 if (Cap.isCopyCapture() &&
17251 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17252 !(isa<CapturedRegionScopeInfo>(CSI) &&
17253 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17254 DeclRefType.addConst();
17255 return true;
17256 }
17257 return false;
17258 }
17259
17260 // Only block literals, captured statements, and lambda expressions can
17261 // capture; other scopes don't work.
getParentOfCapturingContextOrNull(DeclContext * DC,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)17262 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17263 SourceLocation Loc,
17264 const bool Diagnose, Sema &S) {
17265 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17266 return getLambdaAwareParentOfDeclContext(DC);
17267 else if (Var->hasLocalStorage()) {
17268 if (Diagnose)
17269 diagnoseUncapturableValueReference(S, Loc, Var, DC);
17270 }
17271 return nullptr;
17272 }
17273
17274 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17275 // certain types of variables (unnamed, variably modified types etc.)
17276 // so check for eligibility.
isVariableCapturable(CapturingScopeInfo * CSI,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)17277 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17278 SourceLocation Loc,
17279 const bool Diagnose, Sema &S) {
17280
17281 bool IsBlock = isa<BlockScopeInfo>(CSI);
17282 bool IsLambda = isa<LambdaScopeInfo>(CSI);
17283
17284 // Lambdas are not allowed to capture unnamed variables
17285 // (e.g. anonymous unions).
17286 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17287 // assuming that's the intent.
17288 if (IsLambda && !Var->getDeclName()) {
17289 if (Diagnose) {
17290 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17291 S.Diag(Var->getLocation(), diag::note_declared_at);
17292 }
17293 return false;
17294 }
17295
17296 // Prohibit variably-modified types in blocks; they're difficult to deal with.
17297 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17298 if (Diagnose) {
17299 S.Diag(Loc, diag::err_ref_vm_type);
17300 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17301 }
17302 return false;
17303 }
17304 // Prohibit structs with flexible array members too.
17305 // We cannot capture what is in the tail end of the struct.
17306 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17307 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17308 if (Diagnose) {
17309 if (IsBlock)
17310 S.Diag(Loc, diag::err_ref_flexarray_type);
17311 else
17312 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17313 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17314 }
17315 return false;
17316 }
17317 }
17318 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17319 // Lambdas and captured statements are not allowed to capture __block
17320 // variables; they don't support the expected semantics.
17321 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17322 if (Diagnose) {
17323 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17324 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17325 }
17326 return false;
17327 }
17328 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17329 if (S.getLangOpts().OpenCL && IsBlock &&
17330 Var->getType()->isBlockPointerType()) {
17331 if (Diagnose)
17332 S.Diag(Loc, diag::err_opencl_block_ref_block);
17333 return false;
17334 }
17335
17336 return true;
17337 }
17338
17339 // Returns true if the capture by block was successful.
captureInBlock(BlockScopeInfo * BSI,VarDecl * Var,SourceLocation Loc,const bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const bool Nested,Sema & S,bool Invalid)17340 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17341 SourceLocation Loc,
17342 const bool BuildAndDiagnose,
17343 QualType &CaptureType,
17344 QualType &DeclRefType,
17345 const bool Nested,
17346 Sema &S, bool Invalid) {
17347 bool ByRef = false;
17348
17349 // Blocks are not allowed to capture arrays, excepting OpenCL.
17350 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17351 // (decayed to pointers).
17352 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17353 if (BuildAndDiagnose) {
17354 S.Diag(Loc, diag::err_ref_array_type);
17355 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17356 Invalid = true;
17357 } else {
17358 return false;
17359 }
17360 }
17361
17362 // Forbid the block-capture of autoreleasing variables.
17363 if (!Invalid &&
17364 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17365 if (BuildAndDiagnose) {
17366 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17367 << /*block*/ 0;
17368 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17369 Invalid = true;
17370 } else {
17371 return false;
17372 }
17373 }
17374
17375 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17376 if (const auto *PT = CaptureType->getAs<PointerType>()) {
17377 QualType PointeeTy = PT->getPointeeType();
17378
17379 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17380 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17381 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17382 if (BuildAndDiagnose) {
17383 SourceLocation VarLoc = Var->getLocation();
17384 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17385 S.Diag(VarLoc, diag::note_declare_parameter_strong);
17386 }
17387 }
17388 }
17389
17390 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17391 if (HasBlocksAttr || CaptureType->isReferenceType() ||
17392 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17393 // Block capture by reference does not change the capture or
17394 // declaration reference types.
17395 ByRef = true;
17396 } else {
17397 // Block capture by copy introduces 'const'.
17398 CaptureType = CaptureType.getNonReferenceType().withConst();
17399 DeclRefType = CaptureType;
17400 }
17401
17402 // Actually capture the variable.
17403 if (BuildAndDiagnose)
17404 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17405 CaptureType, Invalid);
17406
17407 return !Invalid;
17408 }
17409
17410
17411 /// Capture the given variable in the captured region.
captureInCapturedRegion(CapturedRegionScopeInfo * RSI,VarDecl * Var,SourceLocation Loc,const bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const bool RefersToCapturedVariable,Sema::TryCaptureKind Kind,bool IsTopScope,Sema & S,bool Invalid)17412 static bool captureInCapturedRegion(
17413 CapturedRegionScopeInfo *RSI, VarDecl *Var, SourceLocation Loc,
17414 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
17415 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
17416 bool IsTopScope, Sema &S, bool Invalid) {
17417 // By default, capture variables by reference.
17418 bool ByRef = true;
17419 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17420 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17421 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17422 // Using an LValue reference type is consistent with Lambdas (see below).
17423 if (S.isOpenMPCapturedDecl(Var)) {
17424 bool HasConst = DeclRefType.isConstQualified();
17425 DeclRefType = DeclRefType.getUnqualifiedType();
17426 // Don't lose diagnostics about assignments to const.
17427 if (HasConst)
17428 DeclRefType.addConst();
17429 }
17430 // Do not capture firstprivates in tasks.
17431 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17432 OMPC_unknown)
17433 return true;
17434 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17435 RSI->OpenMPCaptureLevel);
17436 }
17437
17438 if (ByRef)
17439 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17440 else
17441 CaptureType = DeclRefType;
17442
17443 // Actually capture the variable.
17444 if (BuildAndDiagnose)
17445 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17446 Loc, SourceLocation(), CaptureType, Invalid);
17447
17448 return !Invalid;
17449 }
17450
17451 /// Capture the given variable in the lambda.
captureInLambda(LambdaScopeInfo * LSI,VarDecl * Var,SourceLocation Loc,const bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const bool RefersToCapturedVariable,const Sema::TryCaptureKind Kind,SourceLocation EllipsisLoc,const bool IsTopScope,Sema & S,bool Invalid)17452 static bool captureInLambda(LambdaScopeInfo *LSI,
17453 VarDecl *Var,
17454 SourceLocation Loc,
17455 const bool BuildAndDiagnose,
17456 QualType &CaptureType,
17457 QualType &DeclRefType,
17458 const bool RefersToCapturedVariable,
17459 const Sema::TryCaptureKind Kind,
17460 SourceLocation EllipsisLoc,
17461 const bool IsTopScope,
17462 Sema &S, bool Invalid) {
17463 // Determine whether we are capturing by reference or by value.
17464 bool ByRef = false;
17465 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17466 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17467 } else {
17468 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17469 }
17470
17471 // Compute the type of the field that will capture this variable.
17472 if (ByRef) {
17473 // C++11 [expr.prim.lambda]p15:
17474 // An entity is captured by reference if it is implicitly or
17475 // explicitly captured but not captured by copy. It is
17476 // unspecified whether additional unnamed non-static data
17477 // members are declared in the closure type for entities
17478 // captured by reference.
17479 //
17480 // FIXME: It is not clear whether we want to build an lvalue reference
17481 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17482 // to do the former, while EDG does the latter. Core issue 1249 will
17483 // clarify, but for now we follow GCC because it's a more permissive and
17484 // easily defensible position.
17485 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17486 } else {
17487 // C++11 [expr.prim.lambda]p14:
17488 // For each entity captured by copy, an unnamed non-static
17489 // data member is declared in the closure type. The
17490 // declaration order of these members is unspecified. The type
17491 // of such a data member is the type of the corresponding
17492 // captured entity if the entity is not a reference to an
17493 // object, or the referenced type otherwise. [Note: If the
17494 // captured entity is a reference to a function, the
17495 // corresponding data member is also a reference to a
17496 // function. - end note ]
17497 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17498 if (!RefType->getPointeeType()->isFunctionType())
17499 CaptureType = RefType->getPointeeType();
17500 }
17501
17502 // Forbid the lambda copy-capture of autoreleasing variables.
17503 if (!Invalid &&
17504 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17505 if (BuildAndDiagnose) {
17506 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17507 S.Diag(Var->getLocation(), diag::note_previous_decl)
17508 << Var->getDeclName();
17509 Invalid = true;
17510 } else {
17511 return false;
17512 }
17513 }
17514
17515 // Make sure that by-copy captures are of a complete and non-abstract type.
17516 if (!Invalid && BuildAndDiagnose) {
17517 if (!CaptureType->isDependentType() &&
17518 S.RequireCompleteSizedType(
17519 Loc, CaptureType,
17520 diag::err_capture_of_incomplete_or_sizeless_type,
17521 Var->getDeclName()))
17522 Invalid = true;
17523 else if (S.RequireNonAbstractType(Loc, CaptureType,
17524 diag::err_capture_of_abstract_type))
17525 Invalid = true;
17526 }
17527 }
17528
17529 // Compute the type of a reference to this captured variable.
17530 if (ByRef)
17531 DeclRefType = CaptureType.getNonReferenceType();
17532 else {
17533 // C++ [expr.prim.lambda]p5:
17534 // The closure type for a lambda-expression has a public inline
17535 // function call operator [...]. This function call operator is
17536 // declared const (9.3.1) if and only if the lambda-expression's
17537 // parameter-declaration-clause is not followed by mutable.
17538 DeclRefType = CaptureType.getNonReferenceType();
17539 if (!LSI->Mutable && !CaptureType->isReferenceType())
17540 DeclRefType.addConst();
17541 }
17542
17543 // Add the capture.
17544 if (BuildAndDiagnose)
17545 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17546 Loc, EllipsisLoc, CaptureType, Invalid);
17547
17548 return !Invalid;
17549 }
17550
canCaptureVariableByCopy(VarDecl * Var,const ASTContext & Context)17551 static bool canCaptureVariableByCopy(VarDecl *Var, const ASTContext &Context) {
17552 // Offer a Copy fix even if the type is dependent.
17553 if (Var->getType()->isDependentType())
17554 return true;
17555 QualType T = Var->getType().getNonReferenceType();
17556 if (T.isTriviallyCopyableType(Context))
17557 return true;
17558 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
17559
17560 if (!(RD = RD->getDefinition()))
17561 return false;
17562 if (RD->hasSimpleCopyConstructor())
17563 return true;
17564 if (RD->hasUserDeclaredCopyConstructor())
17565 for (CXXConstructorDecl *Ctor : RD->ctors())
17566 if (Ctor->isCopyConstructor())
17567 return !Ctor->isDeleted();
17568 }
17569 return false;
17570 }
17571
17572 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
17573 /// default capture. Fixes may be omitted if they aren't allowed by the
17574 /// standard, for example we can't emit a default copy capture fix-it if we
17575 /// already explicitly copy capture capture another variable.
buildLambdaCaptureFixit(Sema & Sema,LambdaScopeInfo * LSI,VarDecl * Var)17576 static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
17577 VarDecl *Var) {
17578 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
17579 // Don't offer Capture by copy of default capture by copy fixes if Var is
17580 // known not to be copy constructible.
17581 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
17582
17583 SmallString<32> FixBuffer;
17584 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
17585 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
17586 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
17587 if (ShouldOfferCopyFix) {
17588 // Offer fixes to insert an explicit capture for the variable.
17589 // [] -> [VarName]
17590 // [OtherCapture] -> [OtherCapture, VarName]
17591 FixBuffer.assign({Separator, Var->getName()});
17592 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17593 << Var << /*value*/ 0
17594 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17595 }
17596 // As above but capture by reference.
17597 FixBuffer.assign({Separator, "&", Var->getName()});
17598 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
17599 << Var << /*reference*/ 1
17600 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
17601 }
17602
17603 // Only try to offer default capture if there are no captures excluding this
17604 // and init captures.
17605 // [this]: OK.
17606 // [X = Y]: OK.
17607 // [&A, &B]: Don't offer.
17608 // [A, B]: Don't offer.
17609 if (llvm::any_of(LSI->Captures, [](Capture &C) {
17610 return !C.isThisCapture() && !C.isInitCapture();
17611 }))
17612 return;
17613
17614 // The default capture specifiers, '=' or '&', must appear first in the
17615 // capture body.
17616 SourceLocation DefaultInsertLoc =
17617 LSI->IntroducerRange.getBegin().getLocWithOffset(1);
17618
17619 if (ShouldOfferCopyFix) {
17620 bool CanDefaultCopyCapture = true;
17621 // [=, *this] OK since c++17
17622 // [=, this] OK since c++20
17623 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
17624 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
17625 ? LSI->getCXXThisCapture().isCopyCapture()
17626 : false;
17627 // We can't use default capture by copy if any captures already specified
17628 // capture by copy.
17629 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
17630 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
17631 })) {
17632 FixBuffer.assign({"=", Separator});
17633 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17634 << /*value*/ 0
17635 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17636 }
17637 }
17638
17639 // We can't use default capture by reference if any captures already specified
17640 // capture by reference.
17641 if (llvm::none_of(LSI->Captures, [](Capture &C) {
17642 return !C.isInitCapture() && C.isReferenceCapture() &&
17643 !C.isThisCapture();
17644 })) {
17645 FixBuffer.assign({"&", Separator});
17646 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
17647 << /*reference*/ 1
17648 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
17649 }
17650 }
17651
tryCaptureVariable(VarDecl * Var,SourceLocation ExprLoc,TryCaptureKind Kind,SourceLocation EllipsisLoc,bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const unsigned * const FunctionScopeIndexToStopAt)17652 bool Sema::tryCaptureVariable(
17653 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17654 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17655 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17656 // An init-capture is notionally from the context surrounding its
17657 // declaration, but its parent DC is the lambda class.
17658 DeclContext *VarDC = Var->getDeclContext();
17659 if (Var->isInitCapture())
17660 VarDC = VarDC->getParent();
17661
17662 DeclContext *DC = CurContext;
17663 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17664 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17665 // We need to sync up the Declaration Context with the
17666 // FunctionScopeIndexToStopAt
17667 if (FunctionScopeIndexToStopAt) {
17668 unsigned FSIndex = FunctionScopes.size() - 1;
17669 while (FSIndex != MaxFunctionScopesIndex) {
17670 DC = getLambdaAwareParentOfDeclContext(DC);
17671 --FSIndex;
17672 }
17673 }
17674
17675
17676 // If the variable is declared in the current context, there is no need to
17677 // capture it.
17678 if (VarDC == DC) return true;
17679
17680 // Capture global variables if it is required to use private copy of this
17681 // variable.
17682 bool IsGlobal = !Var->hasLocalStorage();
17683 if (IsGlobal &&
17684 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17685 MaxFunctionScopesIndex)))
17686 return true;
17687 Var = Var->getCanonicalDecl();
17688
17689 // Walk up the stack to determine whether we can capture the variable,
17690 // performing the "simple" checks that don't depend on type. We stop when
17691 // we've either hit the declared scope of the variable or find an existing
17692 // capture of that variable. We start from the innermost capturing-entity
17693 // (the DC) and ensure that all intervening capturing-entities
17694 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17695 // declcontext can either capture the variable or have already captured
17696 // the variable.
17697 CaptureType = Var->getType();
17698 DeclRefType = CaptureType.getNonReferenceType();
17699 bool Nested = false;
17700 bool Explicit = (Kind != TryCapture_Implicit);
17701 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17702 do {
17703 // Only block literals, captured statements, and lambda expressions can
17704 // capture; other scopes don't work.
17705 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17706 ExprLoc,
17707 BuildAndDiagnose,
17708 *this);
17709 // We need to check for the parent *first* because, if we *have*
17710 // private-captured a global variable, we need to recursively capture it in
17711 // intermediate blocks, lambdas, etc.
17712 if (!ParentDC) {
17713 if (IsGlobal) {
17714 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17715 break;
17716 }
17717 return true;
17718 }
17719
17720 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
17721 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17722
17723
17724 // Check whether we've already captured it.
17725 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17726 DeclRefType)) {
17727 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17728 break;
17729 }
17730 // If we are instantiating a generic lambda call operator body,
17731 // we do not want to capture new variables. What was captured
17732 // during either a lambdas transformation or initial parsing
17733 // should be used.
17734 if (isGenericLambdaCallOperatorSpecialization(DC)) {
17735 if (BuildAndDiagnose) {
17736 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17737 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17738 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17739 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17740 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17741 buildLambdaCaptureFixit(*this, LSI, Var);
17742 } else
17743 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17744 }
17745 return true;
17746 }
17747
17748 // Try to capture variable-length arrays types.
17749 if (Var->getType()->isVariablyModifiedType()) {
17750 // We're going to walk down into the type and look for VLA
17751 // expressions.
17752 QualType QTy = Var->getType();
17753 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17754 QTy = PVD->getOriginalType();
17755 captureVariablyModifiedType(Context, QTy, CSI);
17756 }
17757
17758 if (getLangOpts().OpenMP) {
17759 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17760 // OpenMP private variables should not be captured in outer scope, so
17761 // just break here. Similarly, global variables that are captured in a
17762 // target region should not be captured outside the scope of the region.
17763 if (RSI->CapRegionKind == CR_OpenMP) {
17764 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17765 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17766 // If the variable is private (i.e. not captured) and has variably
17767 // modified type, we still need to capture the type for correct
17768 // codegen in all regions, associated with the construct. Currently,
17769 // it is captured in the innermost captured region only.
17770 if (IsOpenMPPrivateDecl != OMPC_unknown &&
17771 Var->getType()->isVariablyModifiedType()) {
17772 QualType QTy = Var->getType();
17773 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17774 QTy = PVD->getOriginalType();
17775 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17776 I < E; ++I) {
17777 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17778 FunctionScopes[FunctionScopesIndex - I]);
17779 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17780 "Wrong number of captured regions associated with the "
17781 "OpenMP construct.");
17782 captureVariablyModifiedType(Context, QTy, OuterRSI);
17783 }
17784 }
17785 bool IsTargetCap =
17786 IsOpenMPPrivateDecl != OMPC_private &&
17787 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17788 RSI->OpenMPCaptureLevel);
17789 // Do not capture global if it is not privatized in outer regions.
17790 bool IsGlobalCap =
17791 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17792 RSI->OpenMPCaptureLevel);
17793
17794 // When we detect target captures we are looking from inside the
17795 // target region, therefore we need to propagate the capture from the
17796 // enclosing region. Therefore, the capture is not initially nested.
17797 if (IsTargetCap)
17798 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17799
17800 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17801 (IsGlobal && !IsGlobalCap)) {
17802 Nested = !IsTargetCap;
17803 bool HasConst = DeclRefType.isConstQualified();
17804 DeclRefType = DeclRefType.getUnqualifiedType();
17805 // Don't lose diagnostics about assignments to const.
17806 if (HasConst)
17807 DeclRefType.addConst();
17808 CaptureType = Context.getLValueReferenceType(DeclRefType);
17809 break;
17810 }
17811 }
17812 }
17813 }
17814 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17815 // No capture-default, and this is not an explicit capture
17816 // so cannot capture this variable.
17817 if (BuildAndDiagnose) {
17818 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17819 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17820 auto *LSI = cast<LambdaScopeInfo>(CSI);
17821 if (LSI->Lambda) {
17822 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17823 buildLambdaCaptureFixit(*this, LSI, Var);
17824 }
17825 // FIXME: If we error out because an outer lambda can not implicitly
17826 // capture a variable that an inner lambda explicitly captures, we
17827 // should have the inner lambda do the explicit capture - because
17828 // it makes for cleaner diagnostics later. This would purely be done
17829 // so that the diagnostic does not misleadingly claim that a variable
17830 // can not be captured by a lambda implicitly even though it is captured
17831 // explicitly. Suggestion:
17832 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17833 // at the function head
17834 // - cache the StartingDeclContext - this must be a lambda
17835 // - captureInLambda in the innermost lambda the variable.
17836 }
17837 return true;
17838 }
17839
17840 FunctionScopesIndex--;
17841 DC = ParentDC;
17842 Explicit = false;
17843 } while (!VarDC->Equals(DC));
17844
17845 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17846 // computing the type of the capture at each step, checking type-specific
17847 // requirements, and adding captures if requested.
17848 // If the variable had already been captured previously, we start capturing
17849 // at the lambda nested within that one.
17850 bool Invalid = false;
17851 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17852 ++I) {
17853 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17854
17855 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17856 // certain types of variables (unnamed, variably modified types etc.)
17857 // so check for eligibility.
17858 if (!Invalid)
17859 Invalid =
17860 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17861
17862 // After encountering an error, if we're actually supposed to capture, keep
17863 // capturing in nested contexts to suppress any follow-on diagnostics.
17864 if (Invalid && !BuildAndDiagnose)
17865 return true;
17866
17867 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17868 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17869 DeclRefType, Nested, *this, Invalid);
17870 Nested = true;
17871 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17872 Invalid = !captureInCapturedRegion(
17873 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
17874 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
17875 Nested = true;
17876 } else {
17877 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17878 Invalid =
17879 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17880 DeclRefType, Nested, Kind, EllipsisLoc,
17881 /*IsTopScope*/ I == N - 1, *this, Invalid);
17882 Nested = true;
17883 }
17884
17885 if (Invalid && !BuildAndDiagnose)
17886 return true;
17887 }
17888 return Invalid;
17889 }
17890
tryCaptureVariable(VarDecl * Var,SourceLocation Loc,TryCaptureKind Kind,SourceLocation EllipsisLoc)17891 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17892 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17893 QualType CaptureType;
17894 QualType DeclRefType;
17895 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17896 /*BuildAndDiagnose=*/true, CaptureType,
17897 DeclRefType, nullptr);
17898 }
17899
NeedToCaptureVariable(VarDecl * Var,SourceLocation Loc)17900 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17901 QualType CaptureType;
17902 QualType DeclRefType;
17903 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17904 /*BuildAndDiagnose=*/false, CaptureType,
17905 DeclRefType, nullptr);
17906 }
17907
getCapturedDeclRefType(VarDecl * Var,SourceLocation Loc)17908 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17909 QualType CaptureType;
17910 QualType DeclRefType;
17911
17912 // Determine whether we can capture this variable.
17913 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17914 /*BuildAndDiagnose=*/false, CaptureType,
17915 DeclRefType, nullptr))
17916 return QualType();
17917
17918 return DeclRefType;
17919 }
17920
17921 namespace {
17922 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17923 // The produced TemplateArgumentListInfo* points to data stored within this
17924 // object, so should only be used in contexts where the pointer will not be
17925 // used after the CopiedTemplateArgs object is destroyed.
17926 class CopiedTemplateArgs {
17927 bool HasArgs;
17928 TemplateArgumentListInfo TemplateArgStorage;
17929 public:
17930 template<typename RefExpr>
CopiedTemplateArgs(RefExpr * E)17931 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17932 if (HasArgs)
17933 E->copyTemplateArgumentsInto(TemplateArgStorage);
17934 }
operator TemplateArgumentListInfo*()17935 operator TemplateArgumentListInfo*()
17936 #ifdef __has_cpp_attribute
17937 #if __has_cpp_attribute(clang::lifetimebound)
17938 [[clang::lifetimebound]]
17939 #endif
17940 #endif
17941 {
17942 return HasArgs ? &TemplateArgStorage : nullptr;
17943 }
17944 };
17945 }
17946
17947 /// Walk the set of potential results of an expression and mark them all as
17948 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17949 ///
17950 /// \return A new expression if we found any potential results, ExprEmpty() if
17951 /// not, and ExprError() if we diagnosed an error.
rebuildPotentialResultsAsNonOdrUsed(Sema & S,Expr * E,NonOdrUseReason NOUR)17952 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17953 NonOdrUseReason NOUR) {
17954 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17955 // an object that satisfies the requirements for appearing in a
17956 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17957 // is immediately applied." This function handles the lvalue-to-rvalue
17958 // conversion part.
17959 //
17960 // If we encounter a node that claims to be an odr-use but shouldn't be, we
17961 // transform it into the relevant kind of non-odr-use node and rebuild the
17962 // tree of nodes leading to it.
17963 //
17964 // This is a mini-TreeTransform that only transforms a restricted subset of
17965 // nodes (and only certain operands of them).
17966
17967 // Rebuild a subexpression.
17968 auto Rebuild = [&](Expr *Sub) {
17969 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17970 };
17971
17972 // Check whether a potential result satisfies the requirements of NOUR.
17973 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17974 // Any entity other than a VarDecl is always odr-used whenever it's named
17975 // in a potentially-evaluated expression.
17976 auto *VD = dyn_cast<VarDecl>(D);
17977 if (!VD)
17978 return true;
17979
17980 // C++2a [basic.def.odr]p4:
17981 // A variable x whose name appears as a potentially-evalauted expression
17982 // e is odr-used by e unless
17983 // -- x is a reference that is usable in constant expressions, or
17984 // -- x is a variable of non-reference type that is usable in constant
17985 // expressions and has no mutable subobjects, and e is an element of
17986 // the set of potential results of an expression of
17987 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
17988 // conversion is applied, or
17989 // -- x is a variable of non-reference type, and e is an element of the
17990 // set of potential results of a discarded-value expression to which
17991 // the lvalue-to-rvalue conversion is not applied
17992 //
17993 // We check the first bullet and the "potentially-evaluated" condition in
17994 // BuildDeclRefExpr. We check the type requirements in the second bullet
17995 // in CheckLValueToRValueConversionOperand below.
17996 switch (NOUR) {
17997 case NOUR_None:
17998 case NOUR_Unevaluated:
17999 llvm_unreachable("unexpected non-odr-use-reason");
18000
18001 case NOUR_Constant:
18002 // Constant references were handled when they were built.
18003 if (VD->getType()->isReferenceType())
18004 return true;
18005 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
18006 if (RD->hasMutableFields())
18007 return true;
18008 if (!VD->isUsableInConstantExpressions(S.Context))
18009 return true;
18010 break;
18011
18012 case NOUR_Discarded:
18013 if (VD->getType()->isReferenceType())
18014 return true;
18015 break;
18016 }
18017 return false;
18018 };
18019
18020 // Mark that this expression does not constitute an odr-use.
18021 auto MarkNotOdrUsed = [&] {
18022 S.MaybeODRUseExprs.remove(E);
18023 if (LambdaScopeInfo *LSI = S.getCurLambda())
18024 LSI->markVariableExprAsNonODRUsed(E);
18025 };
18026
18027 // C++2a [basic.def.odr]p2:
18028 // The set of potential results of an expression e is defined as follows:
18029 switch (E->getStmtClass()) {
18030 // -- If e is an id-expression, ...
18031 case Expr::DeclRefExprClass: {
18032 auto *DRE = cast<DeclRefExpr>(E);
18033 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
18034 break;
18035
18036 // Rebuild as a non-odr-use DeclRefExpr.
18037 MarkNotOdrUsed();
18038 return DeclRefExpr::Create(
18039 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
18040 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
18041 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
18042 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
18043 }
18044
18045 case Expr::FunctionParmPackExprClass: {
18046 auto *FPPE = cast<FunctionParmPackExpr>(E);
18047 // If any of the declarations in the pack is odr-used, then the expression
18048 // as a whole constitutes an odr-use.
18049 for (VarDecl *D : *FPPE)
18050 if (IsPotentialResultOdrUsed(D))
18051 return ExprEmpty();
18052
18053 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
18054 // nothing cares about whether we marked this as an odr-use, but it might
18055 // be useful for non-compiler tools.
18056 MarkNotOdrUsed();
18057 break;
18058 }
18059
18060 // -- If e is a subscripting operation with an array operand...
18061 case Expr::ArraySubscriptExprClass: {
18062 auto *ASE = cast<ArraySubscriptExpr>(E);
18063 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
18064 if (!OldBase->getType()->isArrayType())
18065 break;
18066 ExprResult Base = Rebuild(OldBase);
18067 if (!Base.isUsable())
18068 return Base;
18069 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
18070 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
18071 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
18072 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
18073 ASE->getRBracketLoc());
18074 }
18075
18076 case Expr::MemberExprClass: {
18077 auto *ME = cast<MemberExpr>(E);
18078 // -- If e is a class member access expression [...] naming a non-static
18079 // data member...
18080 if (isa<FieldDecl>(ME->getMemberDecl())) {
18081 ExprResult Base = Rebuild(ME->getBase());
18082 if (!Base.isUsable())
18083 return Base;
18084 return MemberExpr::Create(
18085 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
18086 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
18087 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
18088 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
18089 ME->getObjectKind(), ME->isNonOdrUse());
18090 }
18091
18092 if (ME->getMemberDecl()->isCXXInstanceMember())
18093 break;
18094
18095 // -- If e is a class member access expression naming a static data member,
18096 // ...
18097 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
18098 break;
18099
18100 // Rebuild as a non-odr-use MemberExpr.
18101 MarkNotOdrUsed();
18102 return MemberExpr::Create(
18103 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
18104 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
18105 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
18106 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
18107 return ExprEmpty();
18108 }
18109
18110 case Expr::BinaryOperatorClass: {
18111 auto *BO = cast<BinaryOperator>(E);
18112 Expr *LHS = BO->getLHS();
18113 Expr *RHS = BO->getRHS();
18114 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
18115 if (BO->getOpcode() == BO_PtrMemD) {
18116 ExprResult Sub = Rebuild(LHS);
18117 if (!Sub.isUsable())
18118 return Sub;
18119 LHS = Sub.get();
18120 // -- If e is a comma expression, ...
18121 } else if (BO->getOpcode() == BO_Comma) {
18122 ExprResult Sub = Rebuild(RHS);
18123 if (!Sub.isUsable())
18124 return Sub;
18125 RHS = Sub.get();
18126 } else {
18127 break;
18128 }
18129 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
18130 LHS, RHS);
18131 }
18132
18133 // -- If e has the form (e1)...
18134 case Expr::ParenExprClass: {
18135 auto *PE = cast<ParenExpr>(E);
18136 ExprResult Sub = Rebuild(PE->getSubExpr());
18137 if (!Sub.isUsable())
18138 return Sub;
18139 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
18140 }
18141
18142 // -- If e is a glvalue conditional expression, ...
18143 // We don't apply this to a binary conditional operator. FIXME: Should we?
18144 case Expr::ConditionalOperatorClass: {
18145 auto *CO = cast<ConditionalOperator>(E);
18146 ExprResult LHS = Rebuild(CO->getLHS());
18147 if (LHS.isInvalid())
18148 return ExprError();
18149 ExprResult RHS = Rebuild(CO->getRHS());
18150 if (RHS.isInvalid())
18151 return ExprError();
18152 if (!LHS.isUsable() && !RHS.isUsable())
18153 return ExprEmpty();
18154 if (!LHS.isUsable())
18155 LHS = CO->getLHS();
18156 if (!RHS.isUsable())
18157 RHS = CO->getRHS();
18158 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
18159 CO->getCond(), LHS.get(), RHS.get());
18160 }
18161
18162 // [Clang extension]
18163 // -- If e has the form __extension__ e1...
18164 case Expr::UnaryOperatorClass: {
18165 auto *UO = cast<UnaryOperator>(E);
18166 if (UO->getOpcode() != UO_Extension)
18167 break;
18168 ExprResult Sub = Rebuild(UO->getSubExpr());
18169 if (!Sub.isUsable())
18170 return Sub;
18171 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
18172 Sub.get());
18173 }
18174
18175 // [Clang extension]
18176 // -- If e has the form _Generic(...), the set of potential results is the
18177 // union of the sets of potential results of the associated expressions.
18178 case Expr::GenericSelectionExprClass: {
18179 auto *GSE = cast<GenericSelectionExpr>(E);
18180
18181 SmallVector<Expr *, 4> AssocExprs;
18182 bool AnyChanged = false;
18183 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
18184 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
18185 if (AssocExpr.isInvalid())
18186 return ExprError();
18187 if (AssocExpr.isUsable()) {
18188 AssocExprs.push_back(AssocExpr.get());
18189 AnyChanged = true;
18190 } else {
18191 AssocExprs.push_back(OrigAssocExpr);
18192 }
18193 }
18194
18195 return AnyChanged ? S.CreateGenericSelectionExpr(
18196 GSE->getGenericLoc(), GSE->getDefaultLoc(),
18197 GSE->getRParenLoc(), GSE->getControllingExpr(),
18198 GSE->getAssocTypeSourceInfos(), AssocExprs)
18199 : ExprEmpty();
18200 }
18201
18202 // [Clang extension]
18203 // -- If e has the form __builtin_choose_expr(...), the set of potential
18204 // results is the union of the sets of potential results of the
18205 // second and third subexpressions.
18206 case Expr::ChooseExprClass: {
18207 auto *CE = cast<ChooseExpr>(E);
18208
18209 ExprResult LHS = Rebuild(CE->getLHS());
18210 if (LHS.isInvalid())
18211 return ExprError();
18212
18213 ExprResult RHS = Rebuild(CE->getLHS());
18214 if (RHS.isInvalid())
18215 return ExprError();
18216
18217 if (!LHS.get() && !RHS.get())
18218 return ExprEmpty();
18219 if (!LHS.isUsable())
18220 LHS = CE->getLHS();
18221 if (!RHS.isUsable())
18222 RHS = CE->getRHS();
18223
18224 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
18225 RHS.get(), CE->getRParenLoc());
18226 }
18227
18228 // Step through non-syntactic nodes.
18229 case Expr::ConstantExprClass: {
18230 auto *CE = cast<ConstantExpr>(E);
18231 ExprResult Sub = Rebuild(CE->getSubExpr());
18232 if (!Sub.isUsable())
18233 return Sub;
18234 return ConstantExpr::Create(S.Context, Sub.get());
18235 }
18236
18237 // We could mostly rely on the recursive rebuilding to rebuild implicit
18238 // casts, but not at the top level, so rebuild them here.
18239 case Expr::ImplicitCastExprClass: {
18240 auto *ICE = cast<ImplicitCastExpr>(E);
18241 // Only step through the narrow set of cast kinds we expect to encounter.
18242 // Anything else suggests we've left the region in which potential results
18243 // can be found.
18244 switch (ICE->getCastKind()) {
18245 case CK_NoOp:
18246 case CK_DerivedToBase:
18247 case CK_UncheckedDerivedToBase: {
18248 ExprResult Sub = Rebuild(ICE->getSubExpr());
18249 if (!Sub.isUsable())
18250 return Sub;
18251 CXXCastPath Path(ICE->path());
18252 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
18253 ICE->getValueKind(), &Path);
18254 }
18255
18256 default:
18257 break;
18258 }
18259 break;
18260 }
18261
18262 default:
18263 break;
18264 }
18265
18266 // Can't traverse through this node. Nothing to do.
18267 return ExprEmpty();
18268 }
18269
CheckLValueToRValueConversionOperand(Expr * E)18270 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
18271 // Check whether the operand is or contains an object of non-trivial C union
18272 // type.
18273 if (E->getType().isVolatileQualified() &&
18274 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
18275 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
18276 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
18277 Sema::NTCUC_LValueToRValueVolatile,
18278 NTCUK_Destruct|NTCUK_Copy);
18279
18280 // C++2a [basic.def.odr]p4:
18281 // [...] an expression of non-volatile-qualified non-class type to which
18282 // the lvalue-to-rvalue conversion is applied [...]
18283 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
18284 return E;
18285
18286 ExprResult Result =
18287 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
18288 if (Result.isInvalid())
18289 return ExprError();
18290 return Result.get() ? Result : E;
18291 }
18292
ActOnConstantExpression(ExprResult Res)18293 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
18294 Res = CorrectDelayedTyposInExpr(Res);
18295
18296 if (!Res.isUsable())
18297 return Res;
18298
18299 // If a constant-expression is a reference to a variable where we delay
18300 // deciding whether it is an odr-use, just assume we will apply the
18301 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
18302 // (a non-type template argument), we have special handling anyway.
18303 return CheckLValueToRValueConversionOperand(Res.get());
18304 }
18305
CleanupVarDeclMarking()18306 void Sema::CleanupVarDeclMarking() {
18307 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
18308 // call.
18309 MaybeODRUseExprSet LocalMaybeODRUseExprs;
18310 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
18311
18312 for (Expr *E : LocalMaybeODRUseExprs) {
18313 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
18314 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
18315 DRE->getLocation(), *this);
18316 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
18317 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
18318 *this);
18319 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
18320 for (VarDecl *VD : *FP)
18321 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
18322 } else {
18323 llvm_unreachable("Unexpected expression");
18324 }
18325 }
18326
18327 assert(MaybeODRUseExprs.empty() &&
18328 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
18329 }
18330
DoMarkVarDeclReferenced(Sema & SemaRef,SourceLocation Loc,VarDecl * Var,Expr * E)18331 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
18332 VarDecl *Var, Expr *E) {
18333 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
18334 isa<FunctionParmPackExpr>(E)) &&
18335 "Invalid Expr argument to DoMarkVarDeclReferenced");
18336 Var->setReferenced();
18337
18338 if (Var->isInvalidDecl())
18339 return;
18340
18341 auto *MSI = Var->getMemberSpecializationInfo();
18342 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18343 : Var->getTemplateSpecializationKind();
18344
18345 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18346 bool UsableInConstantExpr =
18347 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18348
18349 // C++20 [expr.const]p12:
18350 // A variable [...] is needed for constant evaluation if it is [...] a
18351 // variable whose name appears as a potentially constant evaluated
18352 // expression that is either a contexpr variable or is of non-volatile
18353 // const-qualified integral type or of reference type
18354 bool NeededForConstantEvaluation =
18355 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18356
18357 bool NeedDefinition =
18358 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18359
18360 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
18361 "Can't instantiate a partial template specialization.");
18362
18363 // If this might be a member specialization of a static data member, check
18364 // the specialization is visible. We already did the checks for variable
18365 // template specializations when we created them.
18366 if (NeedDefinition && TSK != TSK_Undeclared &&
18367 !isa<VarTemplateSpecializationDecl>(Var))
18368 SemaRef.checkSpecializationVisibility(Loc, Var);
18369
18370 // Perform implicit instantiation of static data members, static data member
18371 // templates of class templates, and variable template specializations. Delay
18372 // instantiations of variable templates, except for those that could be used
18373 // in a constant expression.
18374 if (NeedDefinition && isTemplateInstantiation(TSK)) {
18375 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18376 // instantiation declaration if a variable is usable in a constant
18377 // expression (among other cases).
18378 bool TryInstantiating =
18379 TSK == TSK_ImplicitInstantiation ||
18380 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18381
18382 if (TryInstantiating) {
18383 SourceLocation PointOfInstantiation =
18384 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18385 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18386 if (FirstInstantiation) {
18387 PointOfInstantiation = Loc;
18388 if (MSI)
18389 MSI->setPointOfInstantiation(PointOfInstantiation);
18390 // FIXME: Notify listener.
18391 else
18392 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18393 }
18394
18395 if (UsableInConstantExpr) {
18396 // Do not defer instantiations of variables that could be used in a
18397 // constant expression.
18398 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18399 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18400 });
18401
18402 // Re-set the member to trigger a recomputation of the dependence bits
18403 // for the expression.
18404 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18405 DRE->setDecl(DRE->getDecl());
18406 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
18407 ME->setMemberDecl(ME->getMemberDecl());
18408 } else if (FirstInstantiation ||
18409 isa<VarTemplateSpecializationDecl>(Var)) {
18410 // FIXME: For a specialization of a variable template, we don't
18411 // distinguish between "declaration and type implicitly instantiated"
18412 // and "implicit instantiation of definition requested", so we have
18413 // no direct way to avoid enqueueing the pending instantiation
18414 // multiple times.
18415 SemaRef.PendingInstantiations
18416 .push_back(std::make_pair(Var, PointOfInstantiation));
18417 }
18418 }
18419 }
18420
18421 // C++2a [basic.def.odr]p4:
18422 // A variable x whose name appears as a potentially-evaluated expression e
18423 // is odr-used by e unless
18424 // -- x is a reference that is usable in constant expressions
18425 // -- x is a variable of non-reference type that is usable in constant
18426 // expressions and has no mutable subobjects [FIXME], and e is an
18427 // element of the set of potential results of an expression of
18428 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
18429 // conversion is applied
18430 // -- x is a variable of non-reference type, and e is an element of the set
18431 // of potential results of a discarded-value expression to which the
18432 // lvalue-to-rvalue conversion is not applied [FIXME]
18433 //
18434 // We check the first part of the second bullet here, and
18435 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18436 // FIXME: To get the third bullet right, we need to delay this even for
18437 // variables that are not usable in constant expressions.
18438
18439 // If we already know this isn't an odr-use, there's nothing more to do.
18440 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18441 if (DRE->isNonOdrUse())
18442 return;
18443 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18444 if (ME->isNonOdrUse())
18445 return;
18446
18447 switch (OdrUse) {
18448 case OdrUseContext::None:
18449 assert((!E || isa<FunctionParmPackExpr>(E)) &&
18450 "missing non-odr-use marking for unevaluated decl ref");
18451 break;
18452
18453 case OdrUseContext::FormallyOdrUsed:
18454 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18455 // behavior.
18456 break;
18457
18458 case OdrUseContext::Used:
18459 // If we might later find that this expression isn't actually an odr-use,
18460 // delay the marking.
18461 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18462 SemaRef.MaybeODRUseExprs.insert(E);
18463 else
18464 MarkVarDeclODRUsed(Var, Loc, SemaRef);
18465 break;
18466
18467 case OdrUseContext::Dependent:
18468 // If this is a dependent context, we don't need to mark variables as
18469 // odr-used, but we may still need to track them for lambda capture.
18470 // FIXME: Do we also need to do this inside dependent typeid expressions
18471 // (which are modeled as unevaluated at this point)?
18472 const bool RefersToEnclosingScope =
18473 (SemaRef.CurContext != Var->getDeclContext() &&
18474 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18475 if (RefersToEnclosingScope) {
18476 LambdaScopeInfo *const LSI =
18477 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18478 if (LSI && (!LSI->CallOperator ||
18479 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18480 // If a variable could potentially be odr-used, defer marking it so
18481 // until we finish analyzing the full expression for any
18482 // lvalue-to-rvalue
18483 // or discarded value conversions that would obviate odr-use.
18484 // Add it to the list of potential captures that will be analyzed
18485 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18486 // unless the variable is a reference that was initialized by a constant
18487 // expression (this will never need to be captured or odr-used).
18488 //
18489 // FIXME: We can simplify this a lot after implementing P0588R1.
18490 assert(E && "Capture variable should be used in an expression.");
18491 if (!Var->getType()->isReferenceType() ||
18492 !Var->isUsableInConstantExpressions(SemaRef.Context))
18493 LSI->addPotentialCapture(E->IgnoreParens());
18494 }
18495 }
18496 break;
18497 }
18498 }
18499
18500 /// Mark a variable referenced, and check whether it is odr-used
18501 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
18502 /// used directly for normal expressions referring to VarDecl.
MarkVariableReferenced(SourceLocation Loc,VarDecl * Var)18503 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18504 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18505 }
18506
MarkExprReferenced(Sema & SemaRef,SourceLocation Loc,Decl * D,Expr * E,bool MightBeOdrUse)18507 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18508 Decl *D, Expr *E, bool MightBeOdrUse) {
18509 if (SemaRef.isInOpenMPDeclareTargetContext())
18510 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18511
18512 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18513 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18514 return;
18515 }
18516
18517 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18518
18519 // If this is a call to a method via a cast, also mark the method in the
18520 // derived class used in case codegen can devirtualize the call.
18521 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18522 if (!ME)
18523 return;
18524 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18525 if (!MD)
18526 return;
18527 // Only attempt to devirtualize if this is truly a virtual call.
18528 bool IsVirtualCall = MD->isVirtual() &&
18529 ME->performsVirtualDispatch(SemaRef.getLangOpts());
18530 if (!IsVirtualCall)
18531 return;
18532
18533 // If it's possible to devirtualize the call, mark the called function
18534 // referenced.
18535 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18536 ME->getBase(), SemaRef.getLangOpts().AppleKext);
18537 if (DM)
18538 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18539 }
18540
18541 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18542 ///
18543 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
18544 /// handled with care if the DeclRefExpr is not newly-created.
MarkDeclRefReferenced(DeclRefExpr * E,const Expr * Base)18545 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18546 // TODO: update this with DR# once a defect report is filed.
18547 // C++11 defect. The address of a pure member should not be an ODR use, even
18548 // if it's a qualified reference.
18549 bool OdrUse = true;
18550 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18551 if (Method->isVirtual() &&
18552 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18553 OdrUse = false;
18554
18555 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18556 if (!isConstantEvaluated() && FD->isConsteval() &&
18557 !RebuildingImmediateInvocation)
18558 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18559 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18560 }
18561
18562 /// Perform reference-marking and odr-use handling for a MemberExpr.
MarkMemberReferenced(MemberExpr * E)18563 void Sema::MarkMemberReferenced(MemberExpr *E) {
18564 // C++11 [basic.def.odr]p2:
18565 // A non-overloaded function whose name appears as a potentially-evaluated
18566 // expression or a member of a set of candidate functions, if selected by
18567 // overload resolution when referred to from a potentially-evaluated
18568 // expression, is odr-used, unless it is a pure virtual function and its
18569 // name is not explicitly qualified.
18570 bool MightBeOdrUse = true;
18571 if (E->performsVirtualDispatch(getLangOpts())) {
18572 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18573 if (Method->isPure())
18574 MightBeOdrUse = false;
18575 }
18576 SourceLocation Loc =
18577 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18578 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18579 }
18580
18581 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
MarkFunctionParmPackReferenced(FunctionParmPackExpr * E)18582 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18583 for (VarDecl *VD : *E)
18584 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18585 }
18586
18587 /// Perform marking for a reference to an arbitrary declaration. It
18588 /// marks the declaration referenced, and performs odr-use checking for
18589 /// functions and variables. This method should not be used when building a
18590 /// normal expression which refers to a variable.
MarkAnyDeclReferenced(SourceLocation Loc,Decl * D,bool MightBeOdrUse)18591 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18592 bool MightBeOdrUse) {
18593 if (MightBeOdrUse) {
18594 if (auto *VD = dyn_cast<VarDecl>(D)) {
18595 MarkVariableReferenced(Loc, VD);
18596 return;
18597 }
18598 }
18599 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18600 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18601 return;
18602 }
18603 D->setReferenced();
18604 }
18605
18606 namespace {
18607 // Mark all of the declarations used by a type as referenced.
18608 // FIXME: Not fully implemented yet! We need to have a better understanding
18609 // of when we're entering a context we should not recurse into.
18610 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18611 // TreeTransforms rebuilding the type in a new context. Rather than
18612 // duplicating the TreeTransform logic, we should consider reusing it here.
18613 // Currently that causes problems when rebuilding LambdaExprs.
18614 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18615 Sema &S;
18616 SourceLocation Loc;
18617
18618 public:
18619 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18620
MarkReferencedDecls(Sema & S,SourceLocation Loc)18621 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18622
18623 bool TraverseTemplateArgument(const TemplateArgument &Arg);
18624 };
18625 }
18626
TraverseTemplateArgument(const TemplateArgument & Arg)18627 bool MarkReferencedDecls::TraverseTemplateArgument(
18628 const TemplateArgument &Arg) {
18629 {
18630 // A non-type template argument is a constant-evaluated context.
18631 EnterExpressionEvaluationContext Evaluated(
18632 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18633 if (Arg.getKind() == TemplateArgument::Declaration) {
18634 if (Decl *D = Arg.getAsDecl())
18635 S.MarkAnyDeclReferenced(Loc, D, true);
18636 } else if (Arg.getKind() == TemplateArgument::Expression) {
18637 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18638 }
18639 }
18640
18641 return Inherited::TraverseTemplateArgument(Arg);
18642 }
18643
MarkDeclarationsReferencedInType(SourceLocation Loc,QualType T)18644 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18645 MarkReferencedDecls Marker(*this, Loc);
18646 Marker.TraverseType(T);
18647 }
18648
18649 namespace {
18650 /// Helper class that marks all of the declarations referenced by
18651 /// potentially-evaluated subexpressions as "referenced".
18652 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18653 public:
18654 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18655 bool SkipLocalVariables;
18656
EvaluatedExprMarker(Sema & S,bool SkipLocalVariables)18657 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18658 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18659
visitUsedDecl(SourceLocation Loc,Decl * D)18660 void visitUsedDecl(SourceLocation Loc, Decl *D) {
18661 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18662 }
18663
VisitDeclRefExpr(DeclRefExpr * E)18664 void VisitDeclRefExpr(DeclRefExpr *E) {
18665 // If we were asked not to visit local variables, don't.
18666 if (SkipLocalVariables) {
18667 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18668 if (VD->hasLocalStorage())
18669 return;
18670 }
18671
18672 // FIXME: This can trigger the instantiation of the initializer of a
18673 // variable, which can cause the expression to become value-dependent
18674 // or error-dependent. Do we need to propagate the new dependence bits?
18675 S.MarkDeclRefReferenced(E);
18676 }
18677
VisitMemberExpr(MemberExpr * E)18678 void VisitMemberExpr(MemberExpr *E) {
18679 S.MarkMemberReferenced(E);
18680 Visit(E->getBase());
18681 }
18682 };
18683 } // namespace
18684
18685 /// Mark any declarations that appear within this expression or any
18686 /// potentially-evaluated subexpressions as "referenced".
18687 ///
18688 /// \param SkipLocalVariables If true, don't mark local variables as
18689 /// 'referenced'.
MarkDeclarationsReferencedInExpr(Expr * E,bool SkipLocalVariables)18690 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18691 bool SkipLocalVariables) {
18692 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18693 }
18694
18695 /// Emit a diagnostic that describes an effect on the run-time behavior
18696 /// of the program being compiled.
18697 ///
18698 /// This routine emits the given diagnostic when the code currently being
18699 /// type-checked is "potentially evaluated", meaning that there is a
18700 /// possibility that the code will actually be executable. Code in sizeof()
18701 /// expressions, code used only during overload resolution, etc., are not
18702 /// potentially evaluated. This routine will suppress such diagnostics or,
18703 /// in the absolutely nutty case of potentially potentially evaluated
18704 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18705 /// later.
18706 ///
18707 /// This routine should be used for all diagnostics that describe the run-time
18708 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18709 /// Failure to do so will likely result in spurious diagnostics or failures
18710 /// during overload resolution or within sizeof/alignof/typeof/typeid.
DiagRuntimeBehavior(SourceLocation Loc,ArrayRef<const Stmt * > Stmts,const PartialDiagnostic & PD)18711 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18712 const PartialDiagnostic &PD) {
18713 switch (ExprEvalContexts.back().Context) {
18714 case ExpressionEvaluationContext::Unevaluated:
18715 case ExpressionEvaluationContext::UnevaluatedList:
18716 case ExpressionEvaluationContext::UnevaluatedAbstract:
18717 case ExpressionEvaluationContext::DiscardedStatement:
18718 // The argument will never be evaluated, so don't complain.
18719 break;
18720
18721 case ExpressionEvaluationContext::ConstantEvaluated:
18722 // Relevant diagnostics should be produced by constant evaluation.
18723 break;
18724
18725 case ExpressionEvaluationContext::PotentiallyEvaluated:
18726 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18727 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18728 FunctionScopes.back()->PossiblyUnreachableDiags.
18729 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18730 return true;
18731 }
18732
18733 // The initializer of a constexpr variable or of the first declaration of a
18734 // static data member is not syntactically a constant evaluated constant,
18735 // but nonetheless is always required to be a constant expression, so we
18736 // can skip diagnosing.
18737 // FIXME: Using the mangling context here is a hack.
18738 if (auto *VD = dyn_cast_or_null<VarDecl>(
18739 ExprEvalContexts.back().ManglingContextDecl)) {
18740 if (VD->isConstexpr() ||
18741 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18742 break;
18743 // FIXME: For any other kind of variable, we should build a CFG for its
18744 // initializer and check whether the context in question is reachable.
18745 }
18746
18747 Diag(Loc, PD);
18748 return true;
18749 }
18750
18751 return false;
18752 }
18753
DiagRuntimeBehavior(SourceLocation Loc,const Stmt * Statement,const PartialDiagnostic & PD)18754 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18755 const PartialDiagnostic &PD) {
18756 return DiagRuntimeBehavior(
18757 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18758 }
18759
CheckCallReturnType(QualType ReturnType,SourceLocation Loc,CallExpr * CE,FunctionDecl * FD)18760 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18761 CallExpr *CE, FunctionDecl *FD) {
18762 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18763 return false;
18764
18765 // If we're inside a decltype's expression, don't check for a valid return
18766 // type or construct temporaries until we know whether this is the last call.
18767 if (ExprEvalContexts.back().ExprContext ==
18768 ExpressionEvaluationContextRecord::EK_Decltype) {
18769 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18770 return false;
18771 }
18772
18773 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18774 FunctionDecl *FD;
18775 CallExpr *CE;
18776
18777 public:
18778 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18779 : FD(FD), CE(CE) { }
18780
18781 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18782 if (!FD) {
18783 S.Diag(Loc, diag::err_call_incomplete_return)
18784 << T << CE->getSourceRange();
18785 return;
18786 }
18787
18788 S.Diag(Loc, diag::err_call_function_incomplete_return)
18789 << CE->getSourceRange() << FD << T;
18790 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18791 << FD->getDeclName();
18792 }
18793 } Diagnoser(FD, CE);
18794
18795 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18796 return true;
18797
18798 return false;
18799 }
18800
18801 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18802 // will prevent this condition from triggering, which is what we want.
DiagnoseAssignmentAsCondition(Expr * E)18803 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18804 SourceLocation Loc;
18805
18806 unsigned diagnostic = diag::warn_condition_is_assignment;
18807 bool IsOrAssign = false;
18808
18809 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18810 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18811 return;
18812
18813 IsOrAssign = Op->getOpcode() == BO_OrAssign;
18814
18815 // Greylist some idioms by putting them into a warning subcategory.
18816 if (ObjCMessageExpr *ME
18817 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18818 Selector Sel = ME->getSelector();
18819
18820 // self = [<foo> init...]
18821 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18822 diagnostic = diag::warn_condition_is_idiomatic_assignment;
18823
18824 // <foo> = [<bar> nextObject]
18825 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18826 diagnostic = diag::warn_condition_is_idiomatic_assignment;
18827 }
18828
18829 Loc = Op->getOperatorLoc();
18830 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18831 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18832 return;
18833
18834 IsOrAssign = Op->getOperator() == OO_PipeEqual;
18835 Loc = Op->getOperatorLoc();
18836 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18837 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18838 else {
18839 // Not an assignment.
18840 return;
18841 }
18842
18843 Diag(Loc, diagnostic) << E->getSourceRange();
18844
18845 SourceLocation Open = E->getBeginLoc();
18846 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18847 Diag(Loc, diag::note_condition_assign_silence)
18848 << FixItHint::CreateInsertion(Open, "(")
18849 << FixItHint::CreateInsertion(Close, ")");
18850
18851 if (IsOrAssign)
18852 Diag(Loc, diag::note_condition_or_assign_to_comparison)
18853 << FixItHint::CreateReplacement(Loc, "!=");
18854 else
18855 Diag(Loc, diag::note_condition_assign_to_comparison)
18856 << FixItHint::CreateReplacement(Loc, "==");
18857 }
18858
18859 /// Redundant parentheses over an equality comparison can indicate
18860 /// that the user intended an assignment used as condition.
DiagnoseEqualityWithExtraParens(ParenExpr * ParenE)18861 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18862 // Don't warn if the parens came from a macro.
18863 SourceLocation parenLoc = ParenE->getBeginLoc();
18864 if (parenLoc.isInvalid() || parenLoc.isMacroID())
18865 return;
18866 // Don't warn for dependent expressions.
18867 if (ParenE->isTypeDependent())
18868 return;
18869
18870 Expr *E = ParenE->IgnoreParens();
18871
18872 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18873 if (opE->getOpcode() == BO_EQ &&
18874 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18875 == Expr::MLV_Valid) {
18876 SourceLocation Loc = opE->getOperatorLoc();
18877
18878 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18879 SourceRange ParenERange = ParenE->getSourceRange();
18880 Diag(Loc, diag::note_equality_comparison_silence)
18881 << FixItHint::CreateRemoval(ParenERange.getBegin())
18882 << FixItHint::CreateRemoval(ParenERange.getEnd());
18883 Diag(Loc, diag::note_equality_comparison_to_assign)
18884 << FixItHint::CreateReplacement(Loc, "=");
18885 }
18886 }
18887
CheckBooleanCondition(SourceLocation Loc,Expr * E,bool IsConstexpr)18888 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18889 bool IsConstexpr) {
18890 DiagnoseAssignmentAsCondition(E);
18891 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18892 DiagnoseEqualityWithExtraParens(parenE);
18893
18894 ExprResult result = CheckPlaceholderExpr(E);
18895 if (result.isInvalid()) return ExprError();
18896 E = result.get();
18897
18898 if (!E->isTypeDependent()) {
18899 if (getLangOpts().CPlusPlus)
18900 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18901
18902 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18903 if (ERes.isInvalid())
18904 return ExprError();
18905 E = ERes.get();
18906
18907 QualType T = E->getType();
18908 if (!T->isScalarType()) { // C99 6.8.4.1p1
18909 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18910 << T << E->getSourceRange();
18911 return ExprError();
18912 }
18913 CheckBoolLikeConversion(E, Loc);
18914 }
18915
18916 return E;
18917 }
18918
ActOnCondition(Scope * S,SourceLocation Loc,Expr * SubExpr,ConditionKind CK)18919 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18920 Expr *SubExpr, ConditionKind CK) {
18921 // Empty conditions are valid in for-statements.
18922 if (!SubExpr)
18923 return ConditionResult();
18924
18925 ExprResult Cond;
18926 switch (CK) {
18927 case ConditionKind::Boolean:
18928 Cond = CheckBooleanCondition(Loc, SubExpr);
18929 break;
18930
18931 case ConditionKind::ConstexprIf:
18932 Cond = CheckBooleanCondition(Loc, SubExpr, true);
18933 break;
18934
18935 case ConditionKind::Switch:
18936 Cond = CheckSwitchCondition(Loc, SubExpr);
18937 break;
18938 }
18939 if (Cond.isInvalid()) {
18940 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
18941 {SubExpr});
18942 if (!Cond.get())
18943 return ConditionError();
18944 }
18945 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18946 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18947 if (!FullExpr.get())
18948 return ConditionError();
18949
18950 return ConditionResult(*this, nullptr, FullExpr,
18951 CK == ConditionKind::ConstexprIf);
18952 }
18953
18954 namespace {
18955 /// A visitor for rebuilding a call to an __unknown_any expression
18956 /// to have an appropriate type.
18957 struct RebuildUnknownAnyFunction
18958 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18959
18960 Sema &S;
18961
RebuildUnknownAnyFunction__anond87cafbf2811::RebuildUnknownAnyFunction18962 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18963
VisitStmt__anond87cafbf2811::RebuildUnknownAnyFunction18964 ExprResult VisitStmt(Stmt *S) {
18965 llvm_unreachable("unexpected statement!");
18966 }
18967
VisitExpr__anond87cafbf2811::RebuildUnknownAnyFunction18968 ExprResult VisitExpr(Expr *E) {
18969 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18970 << E->getSourceRange();
18971 return ExprError();
18972 }
18973
18974 /// Rebuild an expression which simply semantically wraps another
18975 /// expression which it shares the type and value kind of.
rebuildSugarExpr__anond87cafbf2811::RebuildUnknownAnyFunction18976 template <class T> ExprResult rebuildSugarExpr(T *E) {
18977 ExprResult SubResult = Visit(E->getSubExpr());
18978 if (SubResult.isInvalid()) return ExprError();
18979
18980 Expr *SubExpr = SubResult.get();
18981 E->setSubExpr(SubExpr);
18982 E->setType(SubExpr->getType());
18983 E->setValueKind(SubExpr->getValueKind());
18984 assert(E->getObjectKind() == OK_Ordinary);
18985 return E;
18986 }
18987
VisitParenExpr__anond87cafbf2811::RebuildUnknownAnyFunction18988 ExprResult VisitParenExpr(ParenExpr *E) {
18989 return rebuildSugarExpr(E);
18990 }
18991
VisitUnaryExtension__anond87cafbf2811::RebuildUnknownAnyFunction18992 ExprResult VisitUnaryExtension(UnaryOperator *E) {
18993 return rebuildSugarExpr(E);
18994 }
18995
VisitUnaryAddrOf__anond87cafbf2811::RebuildUnknownAnyFunction18996 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18997 ExprResult SubResult = Visit(E->getSubExpr());
18998 if (SubResult.isInvalid()) return ExprError();
18999
19000 Expr *SubExpr = SubResult.get();
19001 E->setSubExpr(SubExpr);
19002 E->setType(S.Context.getPointerType(SubExpr->getType()));
19003 assert(E->getValueKind() == VK_RValue);
19004 assert(E->getObjectKind() == OK_Ordinary);
19005 return E;
19006 }
19007
resolveDecl__anond87cafbf2811::RebuildUnknownAnyFunction19008 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
19009 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
19010
19011 E->setType(VD->getType());
19012
19013 assert(E->getValueKind() == VK_RValue);
19014 if (S.getLangOpts().CPlusPlus &&
19015 !(isa<CXXMethodDecl>(VD) &&
19016 cast<CXXMethodDecl>(VD)->isInstance()))
19017 E->setValueKind(VK_LValue);
19018
19019 return E;
19020 }
19021
VisitMemberExpr__anond87cafbf2811::RebuildUnknownAnyFunction19022 ExprResult VisitMemberExpr(MemberExpr *E) {
19023 return resolveDecl(E, E->getMemberDecl());
19024 }
19025
VisitDeclRefExpr__anond87cafbf2811::RebuildUnknownAnyFunction19026 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19027 return resolveDecl(E, E->getDecl());
19028 }
19029 };
19030 }
19031
19032 /// Given a function expression of unknown-any type, try to rebuild it
19033 /// to have a function type.
rebuildUnknownAnyFunction(Sema & S,Expr * FunctionExpr)19034 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
19035 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
19036 if (Result.isInvalid()) return ExprError();
19037 return S.DefaultFunctionArrayConversion(Result.get());
19038 }
19039
19040 namespace {
19041 /// A visitor for rebuilding an expression of type __unknown_anytype
19042 /// into one which resolves the type directly on the referring
19043 /// expression. Strict preservation of the original source
19044 /// structure is not a goal.
19045 struct RebuildUnknownAnyExpr
19046 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
19047
19048 Sema &S;
19049
19050 /// The current destination type.
19051 QualType DestType;
19052
RebuildUnknownAnyExpr__anond87cafbf2911::RebuildUnknownAnyExpr19053 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
19054 : S(S), DestType(CastType) {}
19055
VisitStmt__anond87cafbf2911::RebuildUnknownAnyExpr19056 ExprResult VisitStmt(Stmt *S) {
19057 llvm_unreachable("unexpected statement!");
19058 }
19059
VisitExpr__anond87cafbf2911::RebuildUnknownAnyExpr19060 ExprResult VisitExpr(Expr *E) {
19061 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19062 << E->getSourceRange();
19063 return ExprError();
19064 }
19065
19066 ExprResult VisitCallExpr(CallExpr *E);
19067 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
19068
19069 /// Rebuild an expression which simply semantically wraps another
19070 /// expression which it shares the type and value kind of.
rebuildSugarExpr__anond87cafbf2911::RebuildUnknownAnyExpr19071 template <class T> ExprResult rebuildSugarExpr(T *E) {
19072 ExprResult SubResult = Visit(E->getSubExpr());
19073 if (SubResult.isInvalid()) return ExprError();
19074 Expr *SubExpr = SubResult.get();
19075 E->setSubExpr(SubExpr);
19076 E->setType(SubExpr->getType());
19077 E->setValueKind(SubExpr->getValueKind());
19078 assert(E->getObjectKind() == OK_Ordinary);
19079 return E;
19080 }
19081
VisitParenExpr__anond87cafbf2911::RebuildUnknownAnyExpr19082 ExprResult VisitParenExpr(ParenExpr *E) {
19083 return rebuildSugarExpr(E);
19084 }
19085
VisitUnaryExtension__anond87cafbf2911::RebuildUnknownAnyExpr19086 ExprResult VisitUnaryExtension(UnaryOperator *E) {
19087 return rebuildSugarExpr(E);
19088 }
19089
VisitUnaryAddrOf__anond87cafbf2911::RebuildUnknownAnyExpr19090 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
19091 const PointerType *Ptr = DestType->getAs<PointerType>();
19092 if (!Ptr) {
19093 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
19094 << E->getSourceRange();
19095 return ExprError();
19096 }
19097
19098 if (isa<CallExpr>(E->getSubExpr())) {
19099 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
19100 << E->getSourceRange();
19101 return ExprError();
19102 }
19103
19104 assert(E->getValueKind() == VK_RValue);
19105 assert(E->getObjectKind() == OK_Ordinary);
19106 E->setType(DestType);
19107
19108 // Build the sub-expression as if it were an object of the pointee type.
19109 DestType = Ptr->getPointeeType();
19110 ExprResult SubResult = Visit(E->getSubExpr());
19111 if (SubResult.isInvalid()) return ExprError();
19112 E->setSubExpr(SubResult.get());
19113 return E;
19114 }
19115
19116 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
19117
19118 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
19119
VisitMemberExpr__anond87cafbf2911::RebuildUnknownAnyExpr19120 ExprResult VisitMemberExpr(MemberExpr *E) {
19121 return resolveDecl(E, E->getMemberDecl());
19122 }
19123
VisitDeclRefExpr__anond87cafbf2911::RebuildUnknownAnyExpr19124 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
19125 return resolveDecl(E, E->getDecl());
19126 }
19127 };
19128 }
19129
19130 /// Rebuilds a call expression which yielded __unknown_anytype.
VisitCallExpr(CallExpr * E)19131 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
19132 Expr *CalleeExpr = E->getCallee();
19133
19134 enum FnKind {
19135 FK_MemberFunction,
19136 FK_FunctionPointer,
19137 FK_BlockPointer
19138 };
19139
19140 FnKind Kind;
19141 QualType CalleeType = CalleeExpr->getType();
19142 if (CalleeType == S.Context.BoundMemberTy) {
19143 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
19144 Kind = FK_MemberFunction;
19145 CalleeType = Expr::findBoundMemberType(CalleeExpr);
19146 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
19147 CalleeType = Ptr->getPointeeType();
19148 Kind = FK_FunctionPointer;
19149 } else {
19150 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
19151 Kind = FK_BlockPointer;
19152 }
19153 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
19154
19155 // Verify that this is a legal result type of a function.
19156 if (DestType->isArrayType() || DestType->isFunctionType()) {
19157 unsigned diagID = diag::err_func_returning_array_function;
19158 if (Kind == FK_BlockPointer)
19159 diagID = diag::err_block_returning_array_function;
19160
19161 S.Diag(E->getExprLoc(), diagID)
19162 << DestType->isFunctionType() << DestType;
19163 return ExprError();
19164 }
19165
19166 // Otherwise, go ahead and set DestType as the call's result.
19167 E->setType(DestType.getNonLValueExprType(S.Context));
19168 E->setValueKind(Expr::getValueKindForType(DestType));
19169 assert(E->getObjectKind() == OK_Ordinary);
19170
19171 // Rebuild the function type, replacing the result type with DestType.
19172 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
19173 if (Proto) {
19174 // __unknown_anytype(...) is a special case used by the debugger when
19175 // it has no idea what a function's signature is.
19176 //
19177 // We want to build this call essentially under the K&R
19178 // unprototyped rules, but making a FunctionNoProtoType in C++
19179 // would foul up all sorts of assumptions. However, we cannot
19180 // simply pass all arguments as variadic arguments, nor can we
19181 // portably just call the function under a non-variadic type; see
19182 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
19183 // However, it turns out that in practice it is generally safe to
19184 // call a function declared as "A foo(B,C,D);" under the prototype
19185 // "A foo(B,C,D,...);". The only known exception is with the
19186 // Windows ABI, where any variadic function is implicitly cdecl
19187 // regardless of its normal CC. Therefore we change the parameter
19188 // types to match the types of the arguments.
19189 //
19190 // This is a hack, but it is far superior to moving the
19191 // corresponding target-specific code from IR-gen to Sema/AST.
19192
19193 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
19194 SmallVector<QualType, 8> ArgTypes;
19195 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
19196 ArgTypes.reserve(E->getNumArgs());
19197 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
19198 Expr *Arg = E->getArg(i);
19199 QualType ArgType = Arg->getType();
19200 if (E->isLValue()) {
19201 ArgType = S.Context.getLValueReferenceType(ArgType);
19202 } else if (E->isXValue()) {
19203 ArgType = S.Context.getRValueReferenceType(ArgType);
19204 }
19205 ArgTypes.push_back(ArgType);
19206 }
19207 ParamTypes = ArgTypes;
19208 }
19209 DestType = S.Context.getFunctionType(DestType, ParamTypes,
19210 Proto->getExtProtoInfo());
19211 } else {
19212 DestType = S.Context.getFunctionNoProtoType(DestType,
19213 FnType->getExtInfo());
19214 }
19215
19216 // Rebuild the appropriate pointer-to-function type.
19217 switch (Kind) {
19218 case FK_MemberFunction:
19219 // Nothing to do.
19220 break;
19221
19222 case FK_FunctionPointer:
19223 DestType = S.Context.getPointerType(DestType);
19224 break;
19225
19226 case FK_BlockPointer:
19227 DestType = S.Context.getBlockPointerType(DestType);
19228 break;
19229 }
19230
19231 // Finally, we can recurse.
19232 ExprResult CalleeResult = Visit(CalleeExpr);
19233 if (!CalleeResult.isUsable()) return ExprError();
19234 E->setCallee(CalleeResult.get());
19235
19236 // Bind a temporary if necessary.
19237 return S.MaybeBindToTemporary(E);
19238 }
19239
VisitObjCMessageExpr(ObjCMessageExpr * E)19240 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
19241 // Verify that this is a legal result type of a call.
19242 if (DestType->isArrayType() || DestType->isFunctionType()) {
19243 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
19244 << DestType->isFunctionType() << DestType;
19245 return ExprError();
19246 }
19247
19248 // Rewrite the method result type if available.
19249 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
19250 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
19251 Method->setReturnType(DestType);
19252 }
19253
19254 // Change the type of the message.
19255 E->setType(DestType.getNonReferenceType());
19256 E->setValueKind(Expr::getValueKindForType(DestType));
19257
19258 return S.MaybeBindToTemporary(E);
19259 }
19260
VisitImplicitCastExpr(ImplicitCastExpr * E)19261 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
19262 // The only case we should ever see here is a function-to-pointer decay.
19263 if (E->getCastKind() == CK_FunctionToPointerDecay) {
19264 assert(E->getValueKind() == VK_RValue);
19265 assert(E->getObjectKind() == OK_Ordinary);
19266
19267 E->setType(DestType);
19268
19269 // Rebuild the sub-expression as the pointee (function) type.
19270 DestType = DestType->castAs<PointerType>()->getPointeeType();
19271
19272 ExprResult Result = Visit(E->getSubExpr());
19273 if (!Result.isUsable()) return ExprError();
19274
19275 E->setSubExpr(Result.get());
19276 return E;
19277 } else if (E->getCastKind() == CK_LValueToRValue) {
19278 assert(E->getValueKind() == VK_RValue);
19279 assert(E->getObjectKind() == OK_Ordinary);
19280
19281 assert(isa<BlockPointerType>(E->getType()));
19282
19283 E->setType(DestType);
19284
19285 // The sub-expression has to be a lvalue reference, so rebuild it as such.
19286 DestType = S.Context.getLValueReferenceType(DestType);
19287
19288 ExprResult Result = Visit(E->getSubExpr());
19289 if (!Result.isUsable()) return ExprError();
19290
19291 E->setSubExpr(Result.get());
19292 return E;
19293 } else {
19294 llvm_unreachable("Unhandled cast type!");
19295 }
19296 }
19297
resolveDecl(Expr * E,ValueDecl * VD)19298 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
19299 ExprValueKind ValueKind = VK_LValue;
19300 QualType Type = DestType;
19301
19302 // We know how to make this work for certain kinds of decls:
19303
19304 // - functions
19305 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
19306 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
19307 DestType = Ptr->getPointeeType();
19308 ExprResult Result = resolveDecl(E, VD);
19309 if (Result.isInvalid()) return ExprError();
19310 return S.ImpCastExprToType(Result.get(), Type,
19311 CK_FunctionToPointerDecay, VK_RValue);
19312 }
19313
19314 if (!Type->isFunctionType()) {
19315 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
19316 << VD << E->getSourceRange();
19317 return ExprError();
19318 }
19319 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
19320 // We must match the FunctionDecl's type to the hack introduced in
19321 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
19322 // type. See the lengthy commentary in that routine.
19323 QualType FDT = FD->getType();
19324 const FunctionType *FnType = FDT->castAs<FunctionType>();
19325 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19326 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19327 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19328 SourceLocation Loc = FD->getLocation();
19329 FunctionDecl *NewFD = FunctionDecl::Create(
19330 S.Context, FD->getDeclContext(), Loc, Loc,
19331 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19332 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
19333 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19334
19335 if (FD->getQualifier())
19336 NewFD->setQualifierInfo(FD->getQualifierLoc());
19337
19338 SmallVector<ParmVarDecl*, 16> Params;
19339 for (const auto &AI : FT->param_types()) {
19340 ParmVarDecl *Param =
19341 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19342 Param->setScopeInfo(0, Params.size());
19343 Params.push_back(Param);
19344 }
19345 NewFD->setParams(Params);
19346 DRE->setDecl(NewFD);
19347 VD = DRE->getDecl();
19348 }
19349 }
19350
19351 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19352 if (MD->isInstance()) {
19353 ValueKind = VK_RValue;
19354 Type = S.Context.BoundMemberTy;
19355 }
19356
19357 // Function references aren't l-values in C.
19358 if (!S.getLangOpts().CPlusPlus)
19359 ValueKind = VK_RValue;
19360
19361 // - variables
19362 } else if (isa<VarDecl>(VD)) {
19363 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19364 Type = RefTy->getPointeeType();
19365 } else if (Type->isFunctionType()) {
19366 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19367 << VD << E->getSourceRange();
19368 return ExprError();
19369 }
19370
19371 // - nothing else
19372 } else {
19373 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19374 << VD << E->getSourceRange();
19375 return ExprError();
19376 }
19377
19378 // Modifying the declaration like this is friendly to IR-gen but
19379 // also really dangerous.
19380 VD->setType(DestType);
19381 E->setType(Type);
19382 E->setValueKind(ValueKind);
19383 return E;
19384 }
19385
19386 /// Check a cast of an unknown-any type. We intentionally only
19387 /// trigger this for C-style casts.
checkUnknownAnyCast(SourceRange TypeRange,QualType CastType,Expr * CastExpr,CastKind & CastKind,ExprValueKind & VK,CXXCastPath & Path)19388 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19389 Expr *CastExpr, CastKind &CastKind,
19390 ExprValueKind &VK, CXXCastPath &Path) {
19391 // The type we're casting to must be either void or complete.
19392 if (!CastType->isVoidType() &&
19393 RequireCompleteType(TypeRange.getBegin(), CastType,
19394 diag::err_typecheck_cast_to_incomplete))
19395 return ExprError();
19396
19397 // Rewrite the casted expression from scratch.
19398 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19399 if (!result.isUsable()) return ExprError();
19400
19401 CastExpr = result.get();
19402 VK = CastExpr->getValueKind();
19403 CastKind = CK_NoOp;
19404
19405 return CastExpr;
19406 }
19407
forceUnknownAnyToType(Expr * E,QualType ToType)19408 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19409 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19410 }
19411
checkUnknownAnyArg(SourceLocation callLoc,Expr * arg,QualType & paramType)19412 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19413 Expr *arg, QualType ¶mType) {
19414 // If the syntactic form of the argument is not an explicit cast of
19415 // any sort, just do default argument promotion.
19416 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19417 if (!castArg) {
19418 ExprResult result = DefaultArgumentPromotion(arg);
19419 if (result.isInvalid()) return ExprError();
19420 paramType = result.get()->getType();
19421 return result;
19422 }
19423
19424 // Otherwise, use the type that was written in the explicit cast.
19425 assert(!arg->hasPlaceholderType());
19426 paramType = castArg->getTypeAsWritten();
19427
19428 // Copy-initialize a parameter of that type.
19429 InitializedEntity entity =
19430 InitializedEntity::InitializeParameter(Context, paramType,
19431 /*consumed*/ false);
19432 return PerformCopyInitialization(entity, callLoc, arg);
19433 }
19434
diagnoseUnknownAnyExpr(Sema & S,Expr * E)19435 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19436 Expr *orig = E;
19437 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19438 while (true) {
19439 E = E->IgnoreParenImpCasts();
19440 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19441 E = call->getCallee();
19442 diagID = diag::err_uncasted_call_of_unknown_any;
19443 } else {
19444 break;
19445 }
19446 }
19447
19448 SourceLocation loc;
19449 NamedDecl *d;
19450 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19451 loc = ref->getLocation();
19452 d = ref->getDecl();
19453 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19454 loc = mem->getMemberLoc();
19455 d = mem->getMemberDecl();
19456 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19457 diagID = diag::err_uncasted_call_of_unknown_any;
19458 loc = msg->getSelectorStartLoc();
19459 d = msg->getMethodDecl();
19460 if (!d) {
19461 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19462 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19463 << orig->getSourceRange();
19464 return ExprError();
19465 }
19466 } else {
19467 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19468 << E->getSourceRange();
19469 return ExprError();
19470 }
19471
19472 S.Diag(loc, diagID) << d << orig->getSourceRange();
19473
19474 // Never recoverable.
19475 return ExprError();
19476 }
19477
19478 /// Check for operands with placeholder types and complain if found.
19479 /// Returns ExprError() if there was an error and no recovery was possible.
CheckPlaceholderExpr(Expr * E)19480 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19481 if (!Context.isDependenceAllowed()) {
19482 // C cannot handle TypoExpr nodes on either side of a binop because it
19483 // doesn't handle dependent types properly, so make sure any TypoExprs have
19484 // been dealt with before checking the operands.
19485 ExprResult Result = CorrectDelayedTyposInExpr(E);
19486 if (!Result.isUsable()) return ExprError();
19487 E = Result.get();
19488 }
19489
19490 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19491 if (!placeholderType) return E;
19492
19493 switch (placeholderType->getKind()) {
19494
19495 // Overloaded expressions.
19496 case BuiltinType::Overload: {
19497 // Try to resolve a single function template specialization.
19498 // This is obligatory.
19499 ExprResult Result = E;
19500 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19501 return Result;
19502
19503 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19504 // leaves Result unchanged on failure.
19505 Result = E;
19506 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19507 return Result;
19508
19509 // If that failed, try to recover with a call.
19510 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19511 /*complain*/ true);
19512 return Result;
19513 }
19514
19515 // Bound member functions.
19516 case BuiltinType::BoundMember: {
19517 ExprResult result = E;
19518 const Expr *BME = E->IgnoreParens();
19519 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19520 // Try to give a nicer diagnostic if it is a bound member that we recognize.
19521 if (isa<CXXPseudoDestructorExpr>(BME)) {
19522 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19523 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19524 if (ME->getMemberNameInfo().getName().getNameKind() ==
19525 DeclarationName::CXXDestructorName)
19526 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19527 }
19528 tryToRecoverWithCall(result, PD,
19529 /*complain*/ true);
19530 return result;
19531 }
19532
19533 // ARC unbridged casts.
19534 case BuiltinType::ARCUnbridgedCast: {
19535 Expr *realCast = stripARCUnbridgedCast(E);
19536 diagnoseARCUnbridgedCast(realCast);
19537 return realCast;
19538 }
19539
19540 // Expressions of unknown type.
19541 case BuiltinType::UnknownAny:
19542 return diagnoseUnknownAnyExpr(*this, E);
19543
19544 // Pseudo-objects.
19545 case BuiltinType::PseudoObject:
19546 return checkPseudoObjectRValue(E);
19547
19548 case BuiltinType::BuiltinFn: {
19549 // Accept __noop without parens by implicitly converting it to a call expr.
19550 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19551 if (DRE) {
19552 auto *FD = cast<FunctionDecl>(DRE->getDecl());
19553 if (FD->getBuiltinID() == Builtin::BI__noop) {
19554 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19555 CK_BuiltinFnToFnPtr)
19556 .get();
19557 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19558 VK_RValue, SourceLocation(),
19559 FPOptionsOverride());
19560 }
19561 }
19562
19563 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19564 return ExprError();
19565 }
19566
19567 case BuiltinType::IncompleteMatrixIdx:
19568 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19569 ->getRowIdx()
19570 ->getBeginLoc(),
19571 diag::err_matrix_incomplete_index);
19572 return ExprError();
19573
19574 // Expressions of unknown type.
19575 case BuiltinType::OMPArraySection:
19576 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19577 return ExprError();
19578
19579 // Expressions of unknown type.
19580 case BuiltinType::OMPArrayShaping:
19581 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19582
19583 case BuiltinType::OMPIterator:
19584 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19585
19586 // Everything else should be impossible.
19587 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19588 case BuiltinType::Id:
19589 #include "clang/Basic/OpenCLImageTypes.def"
19590 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19591 case BuiltinType::Id:
19592 #include "clang/Basic/OpenCLExtensionTypes.def"
19593 #define SVE_TYPE(Name, Id, SingletonId) \
19594 case BuiltinType::Id:
19595 #include "clang/Basic/AArch64SVEACLETypes.def"
19596 #define PPC_VECTOR_TYPE(Name, Id, Size) \
19597 case BuiltinType::Id:
19598 #include "clang/Basic/PPCTypes.def"
19599 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
19600 #include "clang/Basic/RISCVVTypes.def"
19601 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19602 #define PLACEHOLDER_TYPE(Id, SingletonId)
19603 #include "clang/AST/BuiltinTypes.def"
19604 break;
19605 }
19606
19607 llvm_unreachable("invalid placeholder type!");
19608 }
19609
CheckCaseExpression(Expr * E)19610 bool Sema::CheckCaseExpression(Expr *E) {
19611 if (E->isTypeDependent())
19612 return true;
19613 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19614 return E->getType()->isIntegralOrEnumerationType();
19615 return false;
19616 }
19617
19618 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19619 ExprResult
ActOnObjCBoolLiteral(SourceLocation OpLoc,tok::TokenKind Kind)19620 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19621 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19622 "Unknown Objective-C Boolean value!");
19623 QualType BoolT = Context.ObjCBuiltinBoolTy;
19624 if (!Context.getBOOLDecl()) {
19625 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19626 Sema::LookupOrdinaryName);
19627 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19628 NamedDecl *ND = Result.getFoundDecl();
19629 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19630 Context.setBOOLDecl(TD);
19631 }
19632 }
19633 if (Context.getBOOLDecl())
19634 BoolT = Context.getBOOLType();
19635 return new (Context)
19636 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19637 }
19638
ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,SourceLocation AtLoc,SourceLocation RParen)19639 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19640 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19641 SourceLocation RParen) {
19642
19643 StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19644
19645 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19646 return Spec.getPlatform() == Platform;
19647 });
19648
19649 VersionTuple Version;
19650 if (Spec != AvailSpecs.end())
19651 Version = Spec->getVersion();
19652
19653 // The use of `@available` in the enclosing function should be analyzed to
19654 // warn when it's used inappropriately (i.e. not if(@available)).
19655 if (getCurFunctionOrMethodDecl())
19656 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19657 else if (getCurBlock() || getCurLambda())
19658 getCurFunction()->HasPotentialAvailabilityViolations = true;
19659
19660 return new (Context)
19661 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19662 }
19663
CreateRecoveryExpr(SourceLocation Begin,SourceLocation End,ArrayRef<Expr * > SubExprs,QualType T)19664 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19665 ArrayRef<Expr *> SubExprs, QualType T) {
19666 if (!Context.getLangOpts().RecoveryAST)
19667 return ExprError();
19668
19669 if (isSFINAEContext())
19670 return ExprError();
19671
19672 if (T.isNull() || T->isUndeducedType() ||
19673 !Context.getLangOpts().RecoveryASTType)
19674 // We don't know the concrete type, fallback to dependent type.
19675 T = Context.DependentTy;
19676
19677 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19678 }
19679