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/Support/ConvertUTF.h"
50 #include "llvm/Support/SaveAndRestore.h"
51 using namespace clang;
52 using namespace sema;
53 using llvm::RoundingMode;
54
55 /// Determine whether the use of this declaration is valid, without
56 /// emitting diagnostics.
CanUseDecl(NamedDecl * D,bool TreatUnavailableAsInvalid)57 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
58 // See if this is an auto-typed variable whose initializer we are parsing.
59 if (ParsingInitForAutoVars.count(D))
60 return false;
61
62 // See if this is a deleted function.
63 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
64 if (FD->isDeleted())
65 return false;
66
67 // If the function has a deduced return type, and we can't deduce it,
68 // then we can't use it either.
69 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
70 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
71 return false;
72
73 // See if this is an aligned allocation/deallocation function that is
74 // unavailable.
75 if (TreatUnavailableAsInvalid &&
76 isUnavailableAlignedAllocationFunction(*FD))
77 return false;
78 }
79
80 // See if this function is unavailable.
81 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
82 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
83 return false;
84
85 return true;
86 }
87
DiagnoseUnusedOfDecl(Sema & S,NamedDecl * D,SourceLocation Loc)88 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
89 // Warn if this is used but marked unused.
90 if (const auto *A = D->getAttr<UnusedAttr>()) {
91 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
92 // should diagnose them.
93 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
94 A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
95 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
96 if (DC && !DC->hasAttr<UnusedAttr>())
97 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
98 }
99 }
100 }
101
102 /// Emit a note explaining that this function is deleted.
NoteDeletedFunction(FunctionDecl * Decl)103 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
104 assert(Decl && Decl->isDeleted());
105
106 if (Decl->isDefaulted()) {
107 // If the method was explicitly defaulted, point at that declaration.
108 if (!Decl->isImplicit())
109 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
110
111 // Try to diagnose why this special member function was implicitly
112 // deleted. This might fail, if that reason no longer applies.
113 DiagnoseDeletedDefaultedFunction(Decl);
114 return;
115 }
116
117 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
118 if (Ctor && Ctor->isInheritingConstructor())
119 return NoteDeletedInheritingConstructor(Ctor);
120
121 Diag(Decl->getLocation(), diag::note_availability_specified_here)
122 << Decl << 1;
123 }
124
125 /// Determine whether a FunctionDecl was ever declared with an
126 /// explicit storage class.
hasAnyExplicitStorageClass(const FunctionDecl * D)127 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
128 for (auto I : D->redecls()) {
129 if (I->getStorageClass() != SC_None)
130 return true;
131 }
132 return false;
133 }
134
135 /// Check whether we're in an extern inline function and referring to a
136 /// variable or function with internal linkage (C11 6.7.4p3).
137 ///
138 /// This is only a warning because we used to silently accept this code, but
139 /// in many cases it will not behave correctly. This is not enabled in C++ mode
140 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
141 /// and so while there may still be user mistakes, most of the time we can't
142 /// prove that there are errors.
diagnoseUseOfInternalDeclInInlineFunction(Sema & S,const NamedDecl * D,SourceLocation Loc)143 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
144 const NamedDecl *D,
145 SourceLocation Loc) {
146 // This is disabled under C++; there are too many ways for this to fire in
147 // contexts where the warning is a false positive, or where it is technically
148 // correct but benign.
149 if (S.getLangOpts().CPlusPlus)
150 return;
151
152 // Check if this is an inlined function or method.
153 FunctionDecl *Current = S.getCurFunctionDecl();
154 if (!Current)
155 return;
156 if (!Current->isInlined())
157 return;
158 if (!Current->isExternallyVisible())
159 return;
160
161 // Check if the decl has internal linkage.
162 if (D->getFormalLinkage() != InternalLinkage)
163 return;
164
165 // Downgrade from ExtWarn to Extension if
166 // (1) the supposedly external inline function is in the main file,
167 // and probably won't be included anywhere else.
168 // (2) the thing we're referencing is a pure function.
169 // (3) the thing we're referencing is another inline function.
170 // This last can give us false negatives, but it's better than warning on
171 // wrappers for simple C library functions.
172 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
173 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
174 if (!DowngradeWarning && UsedFn)
175 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
176
177 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
178 : diag::ext_internal_in_extern_inline)
179 << /*IsVar=*/!UsedFn << D;
180
181 S.MaybeSuggestAddingStaticToDecl(Current);
182
183 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
184 << D;
185 }
186
MaybeSuggestAddingStaticToDecl(const FunctionDecl * Cur)187 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
188 const FunctionDecl *First = Cur->getFirstDecl();
189
190 // Suggest "static" on the function, if possible.
191 if (!hasAnyExplicitStorageClass(First)) {
192 SourceLocation DeclBegin = First->getSourceRange().getBegin();
193 Diag(DeclBegin, diag::note_convert_inline_to_static)
194 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
195 }
196 }
197
198 /// Determine whether the use of this declaration is valid, and
199 /// emit any corresponding diagnostics.
200 ///
201 /// This routine diagnoses various problems with referencing
202 /// declarations that can occur when using a declaration. For example,
203 /// it might warn if a deprecated or unavailable declaration is being
204 /// used, or produce an error (and return true) if a C++0x deleted
205 /// function is being used.
206 ///
207 /// \returns true if there was an error (this declaration cannot be
208 /// referenced), false otherwise.
209 ///
DiagnoseUseOfDecl(NamedDecl * D,ArrayRef<SourceLocation> Locs,const ObjCInterfaceDecl * UnknownObjCClass,bool ObjCPropertyAccess,bool AvoidPartialAvailabilityChecks,ObjCInterfaceDecl * ClassReceiver)210 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
211 const ObjCInterfaceDecl *UnknownObjCClass,
212 bool ObjCPropertyAccess,
213 bool AvoidPartialAvailabilityChecks,
214 ObjCInterfaceDecl *ClassReceiver) {
215 SourceLocation Loc = Locs.front();
216 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
217 // If there were any diagnostics suppressed by template argument deduction,
218 // emit them now.
219 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
220 if (Pos != SuppressedDiagnostics.end()) {
221 for (const PartialDiagnosticAt &Suppressed : Pos->second)
222 Diag(Suppressed.first, Suppressed.second);
223
224 // Clear out the list of suppressed diagnostics, so that we don't emit
225 // them again for this specialization. However, we don't obsolete this
226 // entry from the table, because we want to avoid ever emitting these
227 // diagnostics again.
228 Pos->second.clear();
229 }
230
231 // C++ [basic.start.main]p3:
232 // The function 'main' shall not be used within a program.
233 if (cast<FunctionDecl>(D)->isMain())
234 Diag(Loc, diag::ext_main_used);
235
236 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
237 }
238
239 // See if this is an auto-typed variable whose initializer we are parsing.
240 if (ParsingInitForAutoVars.count(D)) {
241 if (isa<BindingDecl>(D)) {
242 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
243 << D->getDeclName();
244 } else {
245 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
246 << D->getDeclName() << cast<VarDecl>(D)->getType();
247 }
248 return true;
249 }
250
251 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
252 // See if this is a deleted function.
253 if (FD->isDeleted()) {
254 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
255 if (Ctor && Ctor->isInheritingConstructor())
256 Diag(Loc, diag::err_deleted_inherited_ctor_use)
257 << Ctor->getParent()
258 << Ctor->getInheritedConstructor().getConstructor()->getParent();
259 else
260 Diag(Loc, diag::err_deleted_function_use);
261 NoteDeletedFunction(FD);
262 return true;
263 }
264
265 // [expr.prim.id]p4
266 // A program that refers explicitly or implicitly to a function with a
267 // trailing requires-clause whose constraint-expression is not satisfied,
268 // other than to declare it, is ill-formed. [...]
269 //
270 // See if this is a function with constraints that need to be satisfied.
271 // Check this before deducing the return type, as it might instantiate the
272 // definition.
273 if (FD->getTrailingRequiresClause()) {
274 ConstraintSatisfaction Satisfaction;
275 if (CheckFunctionConstraints(FD, Satisfaction, Loc))
276 // A diagnostic will have already been generated (non-constant
277 // constraint expression, for example)
278 return true;
279 if (!Satisfaction.IsSatisfied) {
280 Diag(Loc,
281 diag::err_reference_to_function_with_unsatisfied_constraints)
282 << D;
283 DiagnoseUnsatisfiedConstraint(Satisfaction);
284 return true;
285 }
286 }
287
288 // If the function has a deduced return type, and we can't deduce it,
289 // then we can't use it either.
290 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
291 DeduceReturnType(FD, Loc))
292 return true;
293
294 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
295 return true;
296
297 if (getLangOpts().SYCLIsDevice && !checkSYCLDeviceFunction(Loc, FD))
298 return true;
299 }
300
301 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
302 // Lambdas are only default-constructible or assignable in C++2a onwards.
303 if (MD->getParent()->isLambda() &&
304 ((isa<CXXConstructorDecl>(MD) &&
305 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
306 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
307 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
308 << !isa<CXXConstructorDecl>(MD);
309 }
310 }
311
312 auto getReferencedObjCProp = [](const NamedDecl *D) ->
313 const ObjCPropertyDecl * {
314 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
315 return MD->findPropertyDecl();
316 return nullptr;
317 };
318 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
319 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
320 return true;
321 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
322 return true;
323 }
324
325 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
326 // Only the variables omp_in and omp_out are allowed in the combiner.
327 // Only the variables omp_priv and omp_orig are allowed in the
328 // initializer-clause.
329 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
330 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
331 isa<VarDecl>(D)) {
332 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
333 << getCurFunction()->HasOMPDeclareReductionCombiner;
334 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
335 return true;
336 }
337
338 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
339 // List-items in map clauses on this construct may only refer to the declared
340 // variable var and entities that could be referenced by a procedure defined
341 // at the same location
342 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
343 !isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
344 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
345 << getOpenMPDeclareMapperVarName();
346 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
347 return true;
348 }
349
350 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
351 AvoidPartialAvailabilityChecks, ClassReceiver);
352
353 DiagnoseUnusedOfDecl(*this, D, Loc);
354
355 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
356
357 // CUDA/HIP: Diagnose invalid references of host global variables in device
358 // functions. Reference of device global variables in host functions is
359 // allowed through shadow variables therefore it is not diagnosed.
360 if (LangOpts.CUDAIsDevice) {
361 auto *FD = dyn_cast_or_null<FunctionDecl>(CurContext);
362 auto Target = IdentifyCUDATarget(FD);
363 if (FD && Target != CFT_Host) {
364 const auto *VD = dyn_cast<VarDecl>(D);
365 if (VD && VD->hasGlobalStorage() && !VD->hasAttr<CUDADeviceAttr>() &&
366 !VD->hasAttr<CUDAConstantAttr>() && !VD->hasAttr<CUDASharedAttr>() &&
367 !VD->getType()->isCUDADeviceBuiltinSurfaceType() &&
368 !VD->getType()->isCUDADeviceBuiltinTextureType() &&
369 !VD->isConstexpr() && !VD->getType().isConstQualified())
370 targetDiag(*Locs.begin(), diag::err_ref_bad_target)
371 << /*host*/ 2 << /*variable*/ 1 << VD << Target;
372 }
373 }
374
375 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)) {
376 if (const auto *VD = dyn_cast<ValueDecl>(D))
377 checkDeviceDecl(VD, Loc);
378
379 if (!Context.getTargetInfo().isTLSSupported())
380 if (const auto *VD = dyn_cast<VarDecl>(D))
381 if (VD->getTLSKind() != VarDecl::TLS_None)
382 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
383 }
384
385 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
386 !isUnevaluatedContext()) {
387 // C++ [expr.prim.req.nested] p3
388 // A local parameter shall only appear as an unevaluated operand
389 // (Clause 8) within the constraint-expression.
390 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
391 << D;
392 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
393 return true;
394 }
395
396 return false;
397 }
398
399 /// DiagnoseSentinelCalls - This routine checks whether a call or
400 /// message-send is to a declaration with the sentinel attribute, and
401 /// if so, it checks that the requirements of the sentinel are
402 /// satisfied.
DiagnoseSentinelCalls(NamedDecl * D,SourceLocation Loc,ArrayRef<Expr * > Args)403 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
404 ArrayRef<Expr *> Args) {
405 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
406 if (!attr)
407 return;
408
409 // The number of formal parameters of the declaration.
410 unsigned numFormalParams;
411
412 // The kind of declaration. This is also an index into a %select in
413 // the diagnostic.
414 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
415
416 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
417 numFormalParams = MD->param_size();
418 calleeType = CT_Method;
419 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
420 numFormalParams = FD->param_size();
421 calleeType = CT_Function;
422 } else if (isa<VarDecl>(D)) {
423 QualType type = cast<ValueDecl>(D)->getType();
424 const FunctionType *fn = nullptr;
425 if (const PointerType *ptr = type->getAs<PointerType>()) {
426 fn = ptr->getPointeeType()->getAs<FunctionType>();
427 if (!fn) return;
428 calleeType = CT_Function;
429 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
430 fn = ptr->getPointeeType()->castAs<FunctionType>();
431 calleeType = CT_Block;
432 } else {
433 return;
434 }
435
436 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
437 numFormalParams = proto->getNumParams();
438 } else {
439 numFormalParams = 0;
440 }
441 } else {
442 return;
443 }
444
445 // "nullPos" is the number of formal parameters at the end which
446 // effectively count as part of the variadic arguments. This is
447 // useful if you would prefer to not have *any* formal parameters,
448 // but the language forces you to have at least one.
449 unsigned nullPos = attr->getNullPos();
450 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
451 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
452
453 // The number of arguments which should follow the sentinel.
454 unsigned numArgsAfterSentinel = attr->getSentinel();
455
456 // If there aren't enough arguments for all the formal parameters,
457 // the sentinel, and the args after the sentinel, complain.
458 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
459 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
460 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
461 return;
462 }
463
464 // Otherwise, find the sentinel expression.
465 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
466 if (!sentinelExpr) return;
467 if (sentinelExpr->isValueDependent()) return;
468 if (Context.isSentinelNullExpr(sentinelExpr)) return;
469
470 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
471 // or 'NULL' if those are actually defined in the context. Only use
472 // 'nil' for ObjC methods, where it's much more likely that the
473 // variadic arguments form a list of object pointers.
474 SourceLocation MissingNilLoc = getLocForEndOfToken(sentinelExpr->getEndLoc());
475 std::string NullValue;
476 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
477 NullValue = "nil";
478 else if (getLangOpts().CPlusPlus11)
479 NullValue = "nullptr";
480 else if (PP.isMacroDefined("NULL"))
481 NullValue = "NULL";
482 else
483 NullValue = "(void*) 0";
484
485 if (MissingNilLoc.isInvalid())
486 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
487 else
488 Diag(MissingNilLoc, diag::warn_missing_sentinel)
489 << int(calleeType)
490 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
491 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
492 }
493
getExprRange(Expr * E) const494 SourceRange Sema::getExprRange(Expr *E) const {
495 return E ? E->getSourceRange() : SourceRange();
496 }
497
498 //===----------------------------------------------------------------------===//
499 // Standard Promotions and Conversions
500 //===----------------------------------------------------------------------===//
501
502 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
DefaultFunctionArrayConversion(Expr * E,bool Diagnose)503 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
504 // Handle any placeholder expressions which made it here.
505 if (E->getType()->isPlaceholderType()) {
506 ExprResult result = CheckPlaceholderExpr(E);
507 if (result.isInvalid()) return ExprError();
508 E = result.get();
509 }
510
511 QualType Ty = E->getType();
512 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
513
514 if (Ty->isFunctionType()) {
515 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
516 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
517 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
518 return ExprError();
519
520 E = ImpCastExprToType(E, Context.getPointerType(Ty),
521 CK_FunctionToPointerDecay).get();
522 } else if (Ty->isArrayType()) {
523 // In C90 mode, arrays only promote to pointers if the array expression is
524 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
525 // type 'array of type' is converted to an expression that has type 'pointer
526 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
527 // that has type 'array of type' ...". The relevant change is "an lvalue"
528 // (C90) to "an expression" (C99).
529 //
530 // C++ 4.2p1:
531 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
532 // T" can be converted to an rvalue of type "pointer to T".
533 //
534 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
535 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
536 CK_ArrayToPointerDecay).get();
537 }
538 return E;
539 }
540
CheckForNullPointerDereference(Sema & S,Expr * E)541 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
542 // Check to see if we are dereferencing a null pointer. If so,
543 // and if not volatile-qualified, this is undefined behavior that the
544 // optimizer will delete, so warn about it. People sometimes try to use this
545 // to get a deterministic trap and are surprised by clang's behavior. This
546 // only handles the pattern "*null", which is a very syntactic check.
547 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
548 if (UO && UO->getOpcode() == UO_Deref &&
549 UO->getSubExpr()->getType()->isPointerType()) {
550 const LangAS AS =
551 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
552 if ((!isTargetAddressSpace(AS) ||
553 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
554 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
555 S.Context, Expr::NPC_ValueDependentIsNotNull) &&
556 !UO->getType().isVolatileQualified()) {
557 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
558 S.PDiag(diag::warn_indirection_through_null)
559 << UO->getSubExpr()->getSourceRange());
560 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
561 S.PDiag(diag::note_indirection_through_null));
562 }
563 }
564 }
565
DiagnoseDirectIsaAccess(Sema & S,const ObjCIvarRefExpr * OIRE,SourceLocation AssignLoc,const Expr * RHS)566 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
567 SourceLocation AssignLoc,
568 const Expr* RHS) {
569 const ObjCIvarDecl *IV = OIRE->getDecl();
570 if (!IV)
571 return;
572
573 DeclarationName MemberName = IV->getDeclName();
574 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
575 if (!Member || !Member->isStr("isa"))
576 return;
577
578 const Expr *Base = OIRE->getBase();
579 QualType BaseType = Base->getType();
580 if (OIRE->isArrow())
581 BaseType = BaseType->getPointeeType();
582 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
583 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
584 ObjCInterfaceDecl *ClassDeclared = nullptr;
585 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
586 if (!ClassDeclared->getSuperClass()
587 && (*ClassDeclared->ivar_begin()) == IV) {
588 if (RHS) {
589 NamedDecl *ObjectSetClass =
590 S.LookupSingleName(S.TUScope,
591 &S.Context.Idents.get("object_setClass"),
592 SourceLocation(), S.LookupOrdinaryName);
593 if (ObjectSetClass) {
594 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
595 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
596 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
597 "object_setClass(")
598 << FixItHint::CreateReplacement(
599 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
600 << FixItHint::CreateInsertion(RHSLocEnd, ")");
601 }
602 else
603 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
604 } else {
605 NamedDecl *ObjectGetClass =
606 S.LookupSingleName(S.TUScope,
607 &S.Context.Idents.get("object_getClass"),
608 SourceLocation(), S.LookupOrdinaryName);
609 if (ObjectGetClass)
610 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
611 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
612 "object_getClass(")
613 << FixItHint::CreateReplacement(
614 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
615 else
616 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
617 }
618 S.Diag(IV->getLocation(), diag::note_ivar_decl);
619 }
620 }
621 }
622
DefaultLvalueConversion(Expr * E)623 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
624 // Handle any placeholder expressions which made it here.
625 if (E->getType()->isPlaceholderType()) {
626 ExprResult result = CheckPlaceholderExpr(E);
627 if (result.isInvalid()) return ExprError();
628 E = result.get();
629 }
630
631 // C++ [conv.lval]p1:
632 // A glvalue of a non-function, non-array type T can be
633 // converted to a prvalue.
634 if (!E->isGLValue()) return E;
635
636 QualType T = E->getType();
637 assert(!T.isNull() && "r-value conversion on typeless expression?");
638
639 // lvalue-to-rvalue conversion cannot be applied to function or array types.
640 if (T->isFunctionType() || T->isArrayType())
641 return E;
642
643 // We don't want to throw lvalue-to-rvalue casts on top of
644 // expressions of certain types in C++.
645 if (getLangOpts().CPlusPlus &&
646 (E->getType() == Context.OverloadTy ||
647 T->isDependentType() ||
648 T->isRecordType()))
649 return E;
650
651 // The C standard is actually really unclear on this point, and
652 // DR106 tells us what the result should be but not why. It's
653 // generally best to say that void types just doesn't undergo
654 // lvalue-to-rvalue at all. Note that expressions of unqualified
655 // 'void' type are never l-values, but qualified void can be.
656 if (T->isVoidType())
657 return E;
658
659 // OpenCL usually rejects direct accesses to values of 'half' type.
660 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
661 T->isHalfType()) {
662 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
663 << 0 << T;
664 return ExprError();
665 }
666
667 CheckForNullPointerDereference(*this, E);
668 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
669 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
670 &Context.Idents.get("object_getClass"),
671 SourceLocation(), LookupOrdinaryName);
672 if (ObjectGetClass)
673 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
674 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
675 << FixItHint::CreateReplacement(
676 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
677 else
678 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
679 }
680 else if (const ObjCIvarRefExpr *OIRE =
681 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
682 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
683
684 // C++ [conv.lval]p1:
685 // [...] If T is a non-class type, the type of the prvalue is the
686 // cv-unqualified version of T. Otherwise, the type of the
687 // rvalue is T.
688 //
689 // C99 6.3.2.1p2:
690 // If the lvalue has qualified type, the value has the unqualified
691 // version of the type of the lvalue; otherwise, the value has the
692 // type of the lvalue.
693 if (T.hasQualifiers())
694 T = T.getUnqualifiedType();
695
696 // Under the MS ABI, lock down the inheritance model now.
697 if (T->isMemberPointerType() &&
698 Context.getTargetInfo().getCXXABI().isMicrosoft())
699 (void)isCompleteType(E->getExprLoc(), T);
700
701 ExprResult Res = CheckLValueToRValueConversionOperand(E);
702 if (Res.isInvalid())
703 return Res;
704 E = Res.get();
705
706 // Loading a __weak object implicitly retains the value, so we need a cleanup to
707 // balance that.
708 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
709 Cleanup.setExprNeedsCleanups(true);
710
711 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
712 Cleanup.setExprNeedsCleanups(true);
713
714 // C++ [conv.lval]p3:
715 // If T is cv std::nullptr_t, the result is a null pointer constant.
716 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
717 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_RValue,
718 CurFPFeatureOverrides());
719
720 // C11 6.3.2.1p2:
721 // ... if the lvalue has atomic type, the value has the non-atomic version
722 // of the type of the lvalue ...
723 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
724 T = Atomic->getValueType().getUnqualifiedType();
725 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
726 nullptr, VK_RValue, FPOptionsOverride());
727 }
728
729 return Res;
730 }
731
DefaultFunctionArrayLvalueConversion(Expr * E,bool Diagnose)732 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
733 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
734 if (Res.isInvalid())
735 return ExprError();
736 Res = DefaultLvalueConversion(Res.get());
737 if (Res.isInvalid())
738 return ExprError();
739 return Res;
740 }
741
742 /// CallExprUnaryConversions - a special case of an unary conversion
743 /// performed on a function designator of a call expression.
CallExprUnaryConversions(Expr * E)744 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
745 QualType Ty = E->getType();
746 ExprResult Res = E;
747 // Only do implicit cast for a function type, but not for a pointer
748 // to function type.
749 if (Ty->isFunctionType()) {
750 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
751 CK_FunctionToPointerDecay);
752 if (Res.isInvalid())
753 return ExprError();
754 }
755 Res = DefaultLvalueConversion(Res.get());
756 if (Res.isInvalid())
757 return ExprError();
758 return Res.get();
759 }
760
761 /// UsualUnaryConversions - Performs various conversions that are common to most
762 /// operators (C99 6.3). The conversions of array and function types are
763 /// sometimes suppressed. For example, the array->pointer conversion doesn't
764 /// apply if the array is an argument to the sizeof or address (&) operators.
765 /// In these instances, this routine should *not* be called.
UsualUnaryConversions(Expr * E)766 ExprResult Sema::UsualUnaryConversions(Expr *E) {
767 // First, convert to an r-value.
768 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
769 if (Res.isInvalid())
770 return ExprError();
771 E = Res.get();
772
773 QualType Ty = E->getType();
774 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
775
776 // Half FP have to be promoted to float unless it is natively supported
777 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
778 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
779
780 // Try to perform integral promotions if the object has a theoretically
781 // promotable type.
782 if (Ty->isIntegralOrUnscopedEnumerationType()) {
783 // C99 6.3.1.1p2:
784 //
785 // The following may be used in an expression wherever an int or
786 // unsigned int may be used:
787 // - an object or expression with an integer type whose integer
788 // conversion rank is less than or equal to the rank of int
789 // and unsigned int.
790 // - A bit-field of type _Bool, int, signed int, or unsigned int.
791 //
792 // If an int can represent all values of the original type, the
793 // value is converted to an int; otherwise, it is converted to an
794 // unsigned int. These are called the integer promotions. All
795 // other types are unchanged by the integer promotions.
796
797 QualType PTy = Context.isPromotableBitField(E);
798 if (!PTy.isNull()) {
799 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
800 return E;
801 }
802 if (Ty->isPromotableIntegerType()) {
803 QualType PT = Context.getPromotedIntegerType(Ty);
804 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
805 return E;
806 }
807 }
808 return E;
809 }
810
811 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
812 /// do not have a prototype. Arguments that have type float or __fp16
813 /// are promoted to double. All other argument types are converted by
814 /// UsualUnaryConversions().
DefaultArgumentPromotion(Expr * E)815 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
816 QualType Ty = E->getType();
817 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
818
819 ExprResult Res = UsualUnaryConversions(E);
820 if (Res.isInvalid())
821 return ExprError();
822 E = Res.get();
823
824 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
825 // promote to double.
826 // Note that default argument promotion applies only to float (and
827 // half/fp16); it does not apply to _Float16.
828 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
829 if (BTy && (BTy->getKind() == BuiltinType::Half ||
830 BTy->getKind() == BuiltinType::Float)) {
831 if (getLangOpts().OpenCL &&
832 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
833 if (BTy->getKind() == BuiltinType::Half) {
834 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
835 }
836 } else {
837 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
838 }
839 }
840
841 // C++ performs lvalue-to-rvalue conversion as a default argument
842 // promotion, even on class types, but note:
843 // C++11 [conv.lval]p2:
844 // When an lvalue-to-rvalue conversion occurs in an unevaluated
845 // operand or a subexpression thereof the value contained in the
846 // referenced object is not accessed. Otherwise, if the glvalue
847 // has a class type, the conversion copy-initializes a temporary
848 // of type T from the glvalue and the result of the conversion
849 // is a prvalue for the temporary.
850 // FIXME: add some way to gate this entire thing for correctness in
851 // potentially potentially evaluated contexts.
852 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
853 ExprResult Temp = PerformCopyInitialization(
854 InitializedEntity::InitializeTemporary(E->getType()),
855 E->getExprLoc(), E);
856 if (Temp.isInvalid())
857 return ExprError();
858 E = Temp.get();
859 }
860
861 return E;
862 }
863
864 /// Determine the degree of POD-ness for an expression.
865 /// Incomplete types are considered POD, since this check can be performed
866 /// when we're in an unevaluated context.
isValidVarArgType(const QualType & Ty)867 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
868 if (Ty->isIncompleteType()) {
869 // C++11 [expr.call]p7:
870 // After these conversions, if the argument does not have arithmetic,
871 // enumeration, pointer, pointer to member, or class type, the program
872 // is ill-formed.
873 //
874 // Since we've already performed array-to-pointer and function-to-pointer
875 // decay, the only such type in C++ is cv void. This also handles
876 // initializer lists as variadic arguments.
877 if (Ty->isVoidType())
878 return VAK_Invalid;
879
880 if (Ty->isObjCObjectType())
881 return VAK_Invalid;
882 return VAK_Valid;
883 }
884
885 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
886 return VAK_Invalid;
887
888 if (Ty.isCXX98PODType(Context))
889 return VAK_Valid;
890
891 // C++11 [expr.call]p7:
892 // Passing a potentially-evaluated argument of class type (Clause 9)
893 // having a non-trivial copy constructor, a non-trivial move constructor,
894 // or a non-trivial destructor, with no corresponding parameter,
895 // is conditionally-supported with implementation-defined semantics.
896 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
897 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
898 if (!Record->hasNonTrivialCopyConstructor() &&
899 !Record->hasNonTrivialMoveConstructor() &&
900 !Record->hasNonTrivialDestructor())
901 return VAK_ValidInCXX11;
902
903 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
904 return VAK_Valid;
905
906 if (Ty->isObjCObjectType())
907 return VAK_Invalid;
908
909 if (getLangOpts().MSVCCompat)
910 return VAK_MSVCUndefined;
911
912 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
913 // permitted to reject them. We should consider doing so.
914 return VAK_Undefined;
915 }
916
checkVariadicArgument(const Expr * E,VariadicCallType CT)917 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
918 // Don't allow one to pass an Objective-C interface to a vararg.
919 const QualType &Ty = E->getType();
920 VarArgKind VAK = isValidVarArgType(Ty);
921
922 // Complain about passing non-POD types through varargs.
923 switch (VAK) {
924 case VAK_ValidInCXX11:
925 DiagRuntimeBehavior(
926 E->getBeginLoc(), nullptr,
927 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
928 LLVM_FALLTHROUGH;
929 case VAK_Valid:
930 if (Ty->isRecordType()) {
931 // This is unlikely to be what the user intended. If the class has a
932 // 'c_str' member function, the user probably meant to call that.
933 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
934 PDiag(diag::warn_pass_class_arg_to_vararg)
935 << Ty << CT << hasCStrMethod(E) << ".c_str()");
936 }
937 break;
938
939 case VAK_Undefined:
940 case VAK_MSVCUndefined:
941 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
942 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
943 << getLangOpts().CPlusPlus11 << Ty << CT);
944 break;
945
946 case VAK_Invalid:
947 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
948 Diag(E->getBeginLoc(),
949 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
950 << Ty << CT;
951 else if (Ty->isObjCObjectType())
952 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
953 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
954 << Ty << CT);
955 else
956 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
957 << isa<InitListExpr>(E) << Ty << CT;
958 break;
959 }
960 }
961
962 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
963 /// will create a trap if the resulting type is not a POD type.
DefaultVariadicArgumentPromotion(Expr * E,VariadicCallType CT,FunctionDecl * FDecl)964 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
965 FunctionDecl *FDecl) {
966 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
967 // Strip the unbridged-cast placeholder expression off, if applicable.
968 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
969 (CT == VariadicMethod ||
970 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
971 E = stripARCUnbridgedCast(E);
972
973 // Otherwise, do normal placeholder checking.
974 } else {
975 ExprResult ExprRes = CheckPlaceholderExpr(E);
976 if (ExprRes.isInvalid())
977 return ExprError();
978 E = ExprRes.get();
979 }
980 }
981
982 ExprResult ExprRes = DefaultArgumentPromotion(E);
983 if (ExprRes.isInvalid())
984 return ExprError();
985
986 // Copy blocks to the heap.
987 if (ExprRes.get()->getType()->isBlockPointerType())
988 maybeExtendBlockObject(ExprRes);
989
990 E = ExprRes.get();
991
992 // Diagnostics regarding non-POD argument types are
993 // emitted along with format string checking in Sema::CheckFunctionCall().
994 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
995 // Turn this into a trap.
996 CXXScopeSpec SS;
997 SourceLocation TemplateKWLoc;
998 UnqualifiedId Name;
999 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1000 E->getBeginLoc());
1001 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1002 /*HasTrailingLParen=*/true,
1003 /*IsAddressOfOperand=*/false);
1004 if (TrapFn.isInvalid())
1005 return ExprError();
1006
1007 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),
1008 None, E->getEndLoc());
1009 if (Call.isInvalid())
1010 return ExprError();
1011
1012 ExprResult Comma =
1013 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1014 if (Comma.isInvalid())
1015 return ExprError();
1016 return Comma.get();
1017 }
1018
1019 if (!getLangOpts().CPlusPlus &&
1020 RequireCompleteType(E->getExprLoc(), E->getType(),
1021 diag::err_call_incomplete_argument))
1022 return ExprError();
1023
1024 return E;
1025 }
1026
1027 /// Converts an integer to complex float type. Helper function of
1028 /// UsualArithmeticConversions()
1029 ///
1030 /// \return false if the integer expression is an integer type and is
1031 /// successfully converted to the complex type.
handleIntegerToComplexFloatConversion(Sema & S,ExprResult & IntExpr,ExprResult & ComplexExpr,QualType IntTy,QualType ComplexTy,bool SkipCast)1032 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1033 ExprResult &ComplexExpr,
1034 QualType IntTy,
1035 QualType ComplexTy,
1036 bool SkipCast) {
1037 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1038 if (SkipCast) return false;
1039 if (IntTy->isIntegerType()) {
1040 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1041 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1042 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1043 CK_FloatingRealToComplex);
1044 } else {
1045 assert(IntTy->isComplexIntegerType());
1046 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1047 CK_IntegralComplexToFloatingComplex);
1048 }
1049 return false;
1050 }
1051
1052 /// Handle arithmetic conversion with complex types. Helper function of
1053 /// UsualArithmeticConversions()
handleComplexFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1054 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1055 ExprResult &RHS, QualType LHSType,
1056 QualType RHSType,
1057 bool IsCompAssign) {
1058 // if we have an integer operand, the result is the complex type.
1059 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1060 /*skipCast*/false))
1061 return LHSType;
1062 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1063 /*skipCast*/IsCompAssign))
1064 return RHSType;
1065
1066 // This handles complex/complex, complex/float, or float/complex.
1067 // When both operands are complex, the shorter operand is converted to the
1068 // type of the longer, and that is the type of the result. This corresponds
1069 // to what is done when combining two real floating-point operands.
1070 // The fun begins when size promotion occur across type domains.
1071 // From H&S 6.3.4: When one operand is complex and the other is a real
1072 // floating-point type, the less precise type is converted, within it's
1073 // real or complex domain, to the precision of the other type. For example,
1074 // when combining a "long double" with a "double _Complex", the
1075 // "double _Complex" is promoted to "long double _Complex".
1076
1077 // Compute the rank of the two types, regardless of whether they are complex.
1078 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1079
1080 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1081 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1082 QualType LHSElementType =
1083 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1084 QualType RHSElementType =
1085 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1086
1087 QualType ResultType = S.Context.getComplexType(LHSElementType);
1088 if (Order < 0) {
1089 // Promote the precision of the LHS if not an assignment.
1090 ResultType = S.Context.getComplexType(RHSElementType);
1091 if (!IsCompAssign) {
1092 if (LHSComplexType)
1093 LHS =
1094 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1095 else
1096 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1097 }
1098 } else if (Order > 0) {
1099 // Promote the precision of the RHS.
1100 if (RHSComplexType)
1101 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1102 else
1103 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1104 }
1105 return ResultType;
1106 }
1107
1108 /// Handle arithmetic conversion from integer to float. Helper function
1109 /// of UsualArithmeticConversions()
handleIntToFloatConversion(Sema & S,ExprResult & FloatExpr,ExprResult & IntExpr,QualType FloatTy,QualType IntTy,bool ConvertFloat,bool ConvertInt)1110 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1111 ExprResult &IntExpr,
1112 QualType FloatTy, QualType IntTy,
1113 bool ConvertFloat, bool ConvertInt) {
1114 if (IntTy->isIntegerType()) {
1115 if (ConvertInt)
1116 // Convert intExpr to the lhs floating point type.
1117 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1118 CK_IntegralToFloating);
1119 return FloatTy;
1120 }
1121
1122 // Convert both sides to the appropriate complex float.
1123 assert(IntTy->isComplexIntegerType());
1124 QualType result = S.Context.getComplexType(FloatTy);
1125
1126 // _Complex int -> _Complex float
1127 if (ConvertInt)
1128 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1129 CK_IntegralComplexToFloatingComplex);
1130
1131 // float -> _Complex float
1132 if (ConvertFloat)
1133 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1134 CK_FloatingRealToComplex);
1135
1136 return result;
1137 }
1138
1139 /// Handle arithmethic conversion with floating point types. Helper
1140 /// function of UsualArithmeticConversions()
handleFloatConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1141 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1142 ExprResult &RHS, QualType LHSType,
1143 QualType RHSType, bool IsCompAssign) {
1144 bool LHSFloat = LHSType->isRealFloatingType();
1145 bool RHSFloat = RHSType->isRealFloatingType();
1146
1147 // N1169 4.1.4: If one of the operands has a floating type and the other
1148 // operand has a fixed-point type, the fixed-point operand
1149 // is converted to the floating type [...]
1150 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1151 if (LHSFloat)
1152 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1153 else if (!IsCompAssign)
1154 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1155 return LHSFloat ? LHSType : RHSType;
1156 }
1157
1158 // If we have two real floating types, convert the smaller operand
1159 // to the bigger result.
1160 if (LHSFloat && RHSFloat) {
1161 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1162 if (order > 0) {
1163 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1164 return LHSType;
1165 }
1166
1167 assert(order < 0 && "illegal float comparison");
1168 if (!IsCompAssign)
1169 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1170 return RHSType;
1171 }
1172
1173 if (LHSFloat) {
1174 // Half FP has to be promoted to float unless it is natively supported
1175 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1176 LHSType = S.Context.FloatTy;
1177
1178 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1179 /*ConvertFloat=*/!IsCompAssign,
1180 /*ConvertInt=*/ true);
1181 }
1182 assert(RHSFloat);
1183 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1184 /*ConvertFloat=*/ true,
1185 /*ConvertInt=*/!IsCompAssign);
1186 }
1187
1188 /// Diagnose attempts to convert between __float128 and long double if
1189 /// there is no support for such conversion. Helper function of
1190 /// UsualArithmeticConversions().
unsupportedTypeConversion(const Sema & S,QualType LHSType,QualType RHSType)1191 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1192 QualType RHSType) {
1193 /* No issue converting if at least one of the types is not a floating point
1194 type or the two types have the same rank.
1195 */
1196 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1197 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1198 return false;
1199
1200 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1201 "The remaining types must be floating point types.");
1202
1203 auto *LHSComplex = LHSType->getAs<ComplexType>();
1204 auto *RHSComplex = RHSType->getAs<ComplexType>();
1205
1206 QualType LHSElemType = LHSComplex ?
1207 LHSComplex->getElementType() : LHSType;
1208 QualType RHSElemType = RHSComplex ?
1209 RHSComplex->getElementType() : RHSType;
1210
1211 // No issue if the two types have the same representation
1212 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1213 &S.Context.getFloatTypeSemantics(RHSElemType))
1214 return false;
1215
1216 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1217 RHSElemType == S.Context.LongDoubleTy);
1218 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1219 RHSElemType == S.Context.Float128Ty);
1220
1221 // We've handled the situation where __float128 and long double have the same
1222 // representation. We allow all conversions for all possible long double types
1223 // except PPC's double double.
1224 return Float128AndLongDouble &&
1225 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1226 &llvm::APFloat::PPCDoubleDouble());
1227 }
1228
1229 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1230
1231 namespace {
1232 /// These helper callbacks are placed in an anonymous namespace to
1233 /// permit their use as function template parameters.
doIntegralCast(Sema & S,Expr * op,QualType toType)1234 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1235 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1236 }
1237
doComplexIntegralCast(Sema & S,Expr * op,QualType toType)1238 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1239 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1240 CK_IntegralComplexCast);
1241 }
1242 }
1243
1244 /// Handle integer arithmetic conversions. Helper function of
1245 /// UsualArithmeticConversions()
1246 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
handleIntegerConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1247 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1248 ExprResult &RHS, QualType LHSType,
1249 QualType RHSType, bool IsCompAssign) {
1250 // The rules for this case are in C99 6.3.1.8
1251 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1252 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1253 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1254 if (LHSSigned == RHSSigned) {
1255 // Same signedness; use the higher-ranked type
1256 if (order >= 0) {
1257 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1258 return LHSType;
1259 } else if (!IsCompAssign)
1260 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1261 return RHSType;
1262 } else if (order != (LHSSigned ? 1 : -1)) {
1263 // The unsigned type has greater than or equal rank to the
1264 // signed type, so use the unsigned type
1265 if (RHSSigned) {
1266 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1267 return LHSType;
1268 } else if (!IsCompAssign)
1269 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1270 return RHSType;
1271 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1272 // The two types are different widths; if we are here, that
1273 // means the signed type is larger than the unsigned type, so
1274 // use the signed type.
1275 if (LHSSigned) {
1276 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1277 return LHSType;
1278 } else if (!IsCompAssign)
1279 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1280 return RHSType;
1281 } else {
1282 // The signed type is higher-ranked than the unsigned type,
1283 // but isn't actually any bigger (like unsigned int and long
1284 // on most 32-bit systems). Use the unsigned type corresponding
1285 // to the signed type.
1286 QualType result =
1287 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1288 RHS = (*doRHSCast)(S, RHS.get(), result);
1289 if (!IsCompAssign)
1290 LHS = (*doLHSCast)(S, LHS.get(), result);
1291 return result;
1292 }
1293 }
1294
1295 /// Handle conversions with GCC complex int extension. Helper function
1296 /// of UsualArithmeticConversions()
handleComplexIntConversion(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType LHSType,QualType RHSType,bool IsCompAssign)1297 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1298 ExprResult &RHS, QualType LHSType,
1299 QualType RHSType,
1300 bool IsCompAssign) {
1301 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1302 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1303
1304 if (LHSComplexInt && RHSComplexInt) {
1305 QualType LHSEltType = LHSComplexInt->getElementType();
1306 QualType RHSEltType = RHSComplexInt->getElementType();
1307 QualType ScalarType =
1308 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1309 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1310
1311 return S.Context.getComplexType(ScalarType);
1312 }
1313
1314 if (LHSComplexInt) {
1315 QualType LHSEltType = LHSComplexInt->getElementType();
1316 QualType ScalarType =
1317 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1318 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1319 QualType ComplexType = S.Context.getComplexType(ScalarType);
1320 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1321 CK_IntegralRealToComplex);
1322
1323 return ComplexType;
1324 }
1325
1326 assert(RHSComplexInt);
1327
1328 QualType RHSEltType = RHSComplexInt->getElementType();
1329 QualType ScalarType =
1330 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1331 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1332 QualType ComplexType = S.Context.getComplexType(ScalarType);
1333
1334 if (!IsCompAssign)
1335 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1336 CK_IntegralRealToComplex);
1337 return ComplexType;
1338 }
1339
1340 /// Return the rank of a given fixed point or integer type. The value itself
1341 /// doesn't matter, but the values must be increasing with proper increasing
1342 /// rank as described in N1169 4.1.1.
GetFixedPointRank(QualType Ty)1343 static unsigned GetFixedPointRank(QualType Ty) {
1344 const auto *BTy = Ty->getAs<BuiltinType>();
1345 assert(BTy && "Expected a builtin type.");
1346
1347 switch (BTy->getKind()) {
1348 case BuiltinType::ShortFract:
1349 case BuiltinType::UShortFract:
1350 case BuiltinType::SatShortFract:
1351 case BuiltinType::SatUShortFract:
1352 return 1;
1353 case BuiltinType::Fract:
1354 case BuiltinType::UFract:
1355 case BuiltinType::SatFract:
1356 case BuiltinType::SatUFract:
1357 return 2;
1358 case BuiltinType::LongFract:
1359 case BuiltinType::ULongFract:
1360 case BuiltinType::SatLongFract:
1361 case BuiltinType::SatULongFract:
1362 return 3;
1363 case BuiltinType::ShortAccum:
1364 case BuiltinType::UShortAccum:
1365 case BuiltinType::SatShortAccum:
1366 case BuiltinType::SatUShortAccum:
1367 return 4;
1368 case BuiltinType::Accum:
1369 case BuiltinType::UAccum:
1370 case BuiltinType::SatAccum:
1371 case BuiltinType::SatUAccum:
1372 return 5;
1373 case BuiltinType::LongAccum:
1374 case BuiltinType::ULongAccum:
1375 case BuiltinType::SatLongAccum:
1376 case BuiltinType::SatULongAccum:
1377 return 6;
1378 default:
1379 if (BTy->isInteger())
1380 return 0;
1381 llvm_unreachable("Unexpected fixed point or integer type");
1382 }
1383 }
1384
1385 /// handleFixedPointConversion - Fixed point operations between fixed
1386 /// point types and integers or other fixed point types do not fall under
1387 /// usual arithmetic conversion since these conversions could result in loss
1388 /// of precsision (N1169 4.1.4). These operations should be calculated with
1389 /// the full precision of their result type (N1169 4.1.6.2.1).
handleFixedPointConversion(Sema & S,QualType LHSTy,QualType RHSTy)1390 static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
1391 QualType RHSTy) {
1392 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1393 "Expected at least one of the operands to be a fixed point type");
1394 assert((LHSTy->isFixedPointOrIntegerType() ||
1395 RHSTy->isFixedPointOrIntegerType()) &&
1396 "Special fixed point arithmetic operation conversions are only "
1397 "applied to ints or other fixed point types");
1398
1399 // If one operand has signed fixed-point type and the other operand has
1400 // unsigned fixed-point type, then the unsigned fixed-point operand is
1401 // converted to its corresponding signed fixed-point type and the resulting
1402 // type is the type of the converted operand.
1403 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1404 LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);
1405 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1406 RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);
1407
1408 // The result type is the type with the highest rank, whereby a fixed-point
1409 // conversion rank is always greater than an integer conversion rank; if the
1410 // type of either of the operands is a saturating fixedpoint type, the result
1411 // type shall be the saturating fixed-point type corresponding to the type
1412 // with the highest rank; the resulting value is converted (taking into
1413 // account rounding and overflow) to the precision of the resulting type.
1414 // Same ranks between signed and unsigned types are resolved earlier, so both
1415 // types are either signed or both unsigned at this point.
1416 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1417 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1418
1419 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1420
1421 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1422 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1423
1424 return ResultTy;
1425 }
1426
1427 /// Check that the usual arithmetic conversions can be performed on this pair of
1428 /// expressions that might be of enumeration type.
checkEnumArithmeticConversions(Sema & S,Expr * LHS,Expr * RHS,SourceLocation Loc,Sema::ArithConvKind ACK)1429 static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
1430 SourceLocation Loc,
1431 Sema::ArithConvKind ACK) {
1432 // C++2a [expr.arith.conv]p1:
1433 // If one operand is of enumeration type and the other operand is of a
1434 // different enumeration type or a floating-point type, this behavior is
1435 // deprecated ([depr.arith.conv.enum]).
1436 //
1437 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1438 // Eventually we will presumably reject these cases (in C++23 onwards?).
1439 QualType L = LHS->getType(), R = RHS->getType();
1440 bool LEnum = L->isUnscopedEnumerationType(),
1441 REnum = R->isUnscopedEnumerationType();
1442 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1443 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1444 (REnum && L->isFloatingType())) {
1445 S.Diag(Loc, S.getLangOpts().CPlusPlus20
1446 ? diag::warn_arith_conv_enum_float_cxx20
1447 : diag::warn_arith_conv_enum_float)
1448 << LHS->getSourceRange() << RHS->getSourceRange()
1449 << (int)ACK << LEnum << L << R;
1450 } else if (!IsCompAssign && LEnum && REnum &&
1451 !S.Context.hasSameUnqualifiedType(L, R)) {
1452 unsigned DiagID;
1453 if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1454 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1455 // If either enumeration type is unnamed, it's less likely that the
1456 // user cares about this, but this situation is still deprecated in
1457 // C++2a. Use a different warning group.
1458 DiagID = S.getLangOpts().CPlusPlus20
1459 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1460 : diag::warn_arith_conv_mixed_anon_enum_types;
1461 } else if (ACK == Sema::ACK_Conditional) {
1462 // Conditional expressions are separated out because they have
1463 // historically had a different warning flag.
1464 DiagID = S.getLangOpts().CPlusPlus20
1465 ? diag::warn_conditional_mixed_enum_types_cxx20
1466 : diag::warn_conditional_mixed_enum_types;
1467 } else if (ACK == Sema::ACK_Comparison) {
1468 // Comparison expressions are separated out because they have
1469 // historically had a different warning flag.
1470 DiagID = S.getLangOpts().CPlusPlus20
1471 ? diag::warn_comparison_mixed_enum_types_cxx20
1472 : diag::warn_comparison_mixed_enum_types;
1473 } else {
1474 DiagID = S.getLangOpts().CPlusPlus20
1475 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1476 : diag::warn_arith_conv_mixed_enum_types;
1477 }
1478 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1479 << (int)ACK << L << R;
1480 }
1481 }
1482
1483 /// UsualArithmeticConversions - Performs various conversions that are common to
1484 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1485 /// routine returns the first non-arithmetic type found. The client is
1486 /// responsible for emitting appropriate error diagnostics.
UsualArithmeticConversions(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,ArithConvKind ACK)1487 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1488 SourceLocation Loc,
1489 ArithConvKind ACK) {
1490 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1491
1492 if (ACK != ACK_CompAssign) {
1493 LHS = UsualUnaryConversions(LHS.get());
1494 if (LHS.isInvalid())
1495 return QualType();
1496 }
1497
1498 RHS = UsualUnaryConversions(RHS.get());
1499 if (RHS.isInvalid())
1500 return QualType();
1501
1502 // For conversion purposes, we ignore any qualifiers.
1503 // For example, "const float" and "float" are equivalent.
1504 QualType LHSType =
1505 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1506 QualType RHSType =
1507 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1508
1509 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1510 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1511 LHSType = AtomicLHS->getValueType();
1512
1513 // If both types are identical, no conversion is needed.
1514 if (LHSType == RHSType)
1515 return LHSType;
1516
1517 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1518 // The caller can deal with this (e.g. pointer + int).
1519 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1520 return QualType();
1521
1522 // Apply unary and bitfield promotions to the LHS's type.
1523 QualType LHSUnpromotedType = LHSType;
1524 if (LHSType->isPromotableIntegerType())
1525 LHSType = Context.getPromotedIntegerType(LHSType);
1526 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1527 if (!LHSBitfieldPromoteTy.isNull())
1528 LHSType = LHSBitfieldPromoteTy;
1529 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1530 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1531
1532 // If both types are identical, no conversion is needed.
1533 if (LHSType == RHSType)
1534 return LHSType;
1535
1536 // ExtInt types aren't subject to conversions between them or normal integers,
1537 // so this fails.
1538 if(LHSType->isExtIntType() || RHSType->isExtIntType())
1539 return QualType();
1540
1541 // At this point, we have two different arithmetic types.
1542
1543 // Diagnose attempts to convert between __float128 and long double where
1544 // such conversions currently can't be handled.
1545 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1546 return QualType();
1547
1548 // Handle complex types first (C99 6.3.1.8p1).
1549 if (LHSType->isComplexType() || RHSType->isComplexType())
1550 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1551 ACK == ACK_CompAssign);
1552
1553 // Now handle "real" floating types (i.e. float, double, long double).
1554 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1555 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1556 ACK == ACK_CompAssign);
1557
1558 // Handle GCC complex int extension.
1559 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1560 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1561 ACK == ACK_CompAssign);
1562
1563 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1564 return handleFixedPointConversion(*this, LHSType, RHSType);
1565
1566 // Finally, we have two differing integer types.
1567 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1568 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1569 }
1570
1571 //===----------------------------------------------------------------------===//
1572 // Semantic Analysis for various Expression Types
1573 //===----------------------------------------------------------------------===//
1574
1575
1576 ExprResult
ActOnGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<ParsedType> ArgTypes,ArrayRef<Expr * > ArgExprs)1577 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1578 SourceLocation DefaultLoc,
1579 SourceLocation RParenLoc,
1580 Expr *ControllingExpr,
1581 ArrayRef<ParsedType> ArgTypes,
1582 ArrayRef<Expr *> ArgExprs) {
1583 unsigned NumAssocs = ArgTypes.size();
1584 assert(NumAssocs == ArgExprs.size());
1585
1586 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1587 for (unsigned i = 0; i < NumAssocs; ++i) {
1588 if (ArgTypes[i])
1589 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1590 else
1591 Types[i] = nullptr;
1592 }
1593
1594 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1595 ControllingExpr,
1596 llvm::makeArrayRef(Types, NumAssocs),
1597 ArgExprs);
1598 delete [] Types;
1599 return ER;
1600 }
1601
1602 ExprResult
CreateGenericSelectionExpr(SourceLocation KeyLoc,SourceLocation DefaultLoc,SourceLocation RParenLoc,Expr * ControllingExpr,ArrayRef<TypeSourceInfo * > Types,ArrayRef<Expr * > Exprs)1603 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1604 SourceLocation DefaultLoc,
1605 SourceLocation RParenLoc,
1606 Expr *ControllingExpr,
1607 ArrayRef<TypeSourceInfo *> Types,
1608 ArrayRef<Expr *> Exprs) {
1609 unsigned NumAssocs = Types.size();
1610 assert(NumAssocs == Exprs.size());
1611
1612 // Decay and strip qualifiers for the controlling expression type, and handle
1613 // placeholder type replacement. See committee discussion from WG14 DR423.
1614 {
1615 EnterExpressionEvaluationContext Unevaluated(
1616 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1617 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1618 if (R.isInvalid())
1619 return ExprError();
1620 ControllingExpr = R.get();
1621 }
1622
1623 // The controlling expression is an unevaluated operand, so side effects are
1624 // likely unintended.
1625 if (!inTemplateInstantiation() &&
1626 ControllingExpr->HasSideEffects(Context, false))
1627 Diag(ControllingExpr->getExprLoc(),
1628 diag::warn_side_effects_unevaluated_context);
1629
1630 bool TypeErrorFound = false,
1631 IsResultDependent = ControllingExpr->isTypeDependent(),
1632 ContainsUnexpandedParameterPack
1633 = ControllingExpr->containsUnexpandedParameterPack();
1634
1635 for (unsigned i = 0; i < NumAssocs; ++i) {
1636 if (Exprs[i]->containsUnexpandedParameterPack())
1637 ContainsUnexpandedParameterPack = true;
1638
1639 if (Types[i]) {
1640 if (Types[i]->getType()->containsUnexpandedParameterPack())
1641 ContainsUnexpandedParameterPack = true;
1642
1643 if (Types[i]->getType()->isDependentType()) {
1644 IsResultDependent = true;
1645 } else {
1646 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1647 // complete object type other than a variably modified type."
1648 unsigned D = 0;
1649 if (Types[i]->getType()->isIncompleteType())
1650 D = diag::err_assoc_type_incomplete;
1651 else if (!Types[i]->getType()->isObjectType())
1652 D = diag::err_assoc_type_nonobject;
1653 else if (Types[i]->getType()->isVariablyModifiedType())
1654 D = diag::err_assoc_type_variably_modified;
1655
1656 if (D != 0) {
1657 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1658 << Types[i]->getTypeLoc().getSourceRange()
1659 << Types[i]->getType();
1660 TypeErrorFound = true;
1661 }
1662
1663 // C11 6.5.1.1p2 "No two generic associations in the same generic
1664 // selection shall specify compatible types."
1665 for (unsigned j = i+1; j < NumAssocs; ++j)
1666 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1667 Context.typesAreCompatible(Types[i]->getType(),
1668 Types[j]->getType())) {
1669 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1670 diag::err_assoc_compatible_types)
1671 << Types[j]->getTypeLoc().getSourceRange()
1672 << Types[j]->getType()
1673 << Types[i]->getType();
1674 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1675 diag::note_compat_assoc)
1676 << Types[i]->getTypeLoc().getSourceRange()
1677 << Types[i]->getType();
1678 TypeErrorFound = true;
1679 }
1680 }
1681 }
1682 }
1683 if (TypeErrorFound)
1684 return ExprError();
1685
1686 // If we determined that the generic selection is result-dependent, don't
1687 // try to compute the result expression.
1688 if (IsResultDependent)
1689 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr, Types,
1690 Exprs, DefaultLoc, RParenLoc,
1691 ContainsUnexpandedParameterPack);
1692
1693 SmallVector<unsigned, 1> CompatIndices;
1694 unsigned DefaultIndex = -1U;
1695 for (unsigned i = 0; i < NumAssocs; ++i) {
1696 if (!Types[i])
1697 DefaultIndex = i;
1698 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1699 Types[i]->getType()))
1700 CompatIndices.push_back(i);
1701 }
1702
1703 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1704 // type compatible with at most one of the types named in its generic
1705 // association list."
1706 if (CompatIndices.size() > 1) {
1707 // We strip parens here because the controlling expression is typically
1708 // parenthesized in macro definitions.
1709 ControllingExpr = ControllingExpr->IgnoreParens();
1710 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_multi_match)
1711 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1712 << (unsigned)CompatIndices.size();
1713 for (unsigned I : CompatIndices) {
1714 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1715 diag::note_compat_assoc)
1716 << Types[I]->getTypeLoc().getSourceRange()
1717 << Types[I]->getType();
1718 }
1719 return ExprError();
1720 }
1721
1722 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1723 // its controlling expression shall have type compatible with exactly one of
1724 // the types named in its generic association list."
1725 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1726 // We strip parens here because the controlling expression is typically
1727 // parenthesized in macro definitions.
1728 ControllingExpr = ControllingExpr->IgnoreParens();
1729 Diag(ControllingExpr->getBeginLoc(), diag::err_generic_sel_no_match)
1730 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1731 return ExprError();
1732 }
1733
1734 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1735 // type name that is compatible with the type of the controlling expression,
1736 // then the result expression of the generic selection is the expression
1737 // in that generic association. Otherwise, the result expression of the
1738 // generic selection is the expression in the default generic association."
1739 unsigned ResultIndex =
1740 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1741
1742 return GenericSelectionExpr::Create(
1743 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1744 ContainsUnexpandedParameterPack, ResultIndex);
1745 }
1746
1747 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1748 /// location of the token and the offset of the ud-suffix within it.
getUDSuffixLoc(Sema & S,SourceLocation TokLoc,unsigned Offset)1749 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1750 unsigned Offset) {
1751 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1752 S.getLangOpts());
1753 }
1754
1755 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1756 /// 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)1757 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1758 IdentifierInfo *UDSuffix,
1759 SourceLocation UDSuffixLoc,
1760 ArrayRef<Expr*> Args,
1761 SourceLocation LitEndLoc) {
1762 assert(Args.size() <= 2 && "too many arguments for literal operator");
1763
1764 QualType ArgTy[2];
1765 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1766 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1767 if (ArgTy[ArgIdx]->isArrayType())
1768 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1769 }
1770
1771 DeclarationName OpName =
1772 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1773 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1774 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1775
1776 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1777 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1778 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1779 /*AllowStringTemplatePack*/ false,
1780 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1781 return ExprError();
1782
1783 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1784 }
1785
1786 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1787 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1788 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1789 /// multiple tokens. However, the common case is that StringToks points to one
1790 /// string.
1791 ///
1792 ExprResult
ActOnStringLiteral(ArrayRef<Token> StringToks,Scope * UDLScope)1793 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1794 assert(!StringToks.empty() && "Must have at least one string!");
1795
1796 StringLiteralParser Literal(StringToks, PP);
1797 if (Literal.hadError)
1798 return ExprError();
1799
1800 SmallVector<SourceLocation, 4> StringTokLocs;
1801 for (const Token &Tok : StringToks)
1802 StringTokLocs.push_back(Tok.getLocation());
1803
1804 QualType CharTy = Context.CharTy;
1805 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1806 if (Literal.isWide()) {
1807 CharTy = Context.getWideCharType();
1808 Kind = StringLiteral::Wide;
1809 } else if (Literal.isUTF8()) {
1810 if (getLangOpts().Char8)
1811 CharTy = Context.Char8Ty;
1812 Kind = StringLiteral::UTF8;
1813 } else if (Literal.isUTF16()) {
1814 CharTy = Context.Char16Ty;
1815 Kind = StringLiteral::UTF16;
1816 } else if (Literal.isUTF32()) {
1817 CharTy = Context.Char32Ty;
1818 Kind = StringLiteral::UTF32;
1819 } else if (Literal.isPascal()) {
1820 CharTy = Context.UnsignedCharTy;
1821 }
1822
1823 // Warn on initializing an array of char from a u8 string literal; this
1824 // becomes ill-formed in C++2a.
1825 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
1826 !getLangOpts().Char8 && Kind == StringLiteral::UTF8) {
1827 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
1828
1829 // Create removals for all 'u8' prefixes in the string literal(s). This
1830 // ensures C++2a compatibility (but may change the program behavior when
1831 // built by non-Clang compilers for which the execution character set is
1832 // not always UTF-8).
1833 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
1834 SourceLocation RemovalDiagLoc;
1835 for (const Token &Tok : StringToks) {
1836 if (Tok.getKind() == tok::utf8_string_literal) {
1837 if (RemovalDiagLoc.isInvalid())
1838 RemovalDiagLoc = Tok.getLocation();
1839 RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1840 Tok.getLocation(),
1841 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
1842 getSourceManager(), getLangOpts())));
1843 }
1844 }
1845 Diag(RemovalDiagLoc, RemovalDiag);
1846 }
1847
1848 QualType StrTy =
1849 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
1850
1851 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1852 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1853 Kind, Literal.Pascal, StrTy,
1854 &StringTokLocs[0],
1855 StringTokLocs.size());
1856 if (Literal.getUDSuffix().empty())
1857 return Lit;
1858
1859 // We're building a user-defined literal.
1860 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1861 SourceLocation UDSuffixLoc =
1862 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1863 Literal.getUDSuffixOffset());
1864
1865 // Make sure we're allowed user-defined literals here.
1866 if (!UDLScope)
1867 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1868
1869 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1870 // operator "" X (str, len)
1871 QualType SizeType = Context.getSizeType();
1872
1873 DeclarationName OpName =
1874 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1875 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1876 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1877
1878 QualType ArgTy[] = {
1879 Context.getArrayDecayedType(StrTy), SizeType
1880 };
1881
1882 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1883 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1884 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1885 /*AllowStringTemplatePack*/ true,
1886 /*DiagnoseMissing*/ true, Lit)) {
1887
1888 case LOLR_Cooked: {
1889 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1890 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1891 StringTokLocs[0]);
1892 Expr *Args[] = { Lit, LenArg };
1893
1894 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1895 }
1896
1897 case LOLR_Template: {
1898 TemplateArgumentListInfo ExplicitArgs;
1899 TemplateArgument Arg(Lit);
1900 TemplateArgumentLocInfo ArgInfo(Lit);
1901 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1902 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1903 &ExplicitArgs);
1904 }
1905
1906 case LOLR_StringTemplatePack: {
1907 TemplateArgumentListInfo ExplicitArgs;
1908
1909 unsigned CharBits = Context.getIntWidth(CharTy);
1910 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1911 llvm::APSInt Value(CharBits, CharIsUnsigned);
1912
1913 TemplateArgument TypeArg(CharTy);
1914 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1915 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1916
1917 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1918 Value = Lit->getCodeUnit(I);
1919 TemplateArgument Arg(Context, Value, CharTy);
1920 TemplateArgumentLocInfo ArgInfo;
1921 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1922 }
1923 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1924 &ExplicitArgs);
1925 }
1926 case LOLR_Raw:
1927 case LOLR_ErrorNoDiagnostic:
1928 llvm_unreachable("unexpected literal operator lookup result");
1929 case LOLR_Error:
1930 return ExprError();
1931 }
1932 llvm_unreachable("unexpected literal operator lookup result");
1933 }
1934
1935 DeclRefExpr *
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,SourceLocation Loc,const CXXScopeSpec * SS)1936 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1937 SourceLocation Loc,
1938 const CXXScopeSpec *SS) {
1939 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1940 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1941 }
1942
1943 DeclRefExpr *
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,const DeclarationNameInfo & NameInfo,const CXXScopeSpec * SS,NamedDecl * FoundD,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)1944 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1945 const DeclarationNameInfo &NameInfo,
1946 const CXXScopeSpec *SS, NamedDecl *FoundD,
1947 SourceLocation TemplateKWLoc,
1948 const TemplateArgumentListInfo *TemplateArgs) {
1949 NestedNameSpecifierLoc NNS =
1950 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
1951 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
1952 TemplateArgs);
1953 }
1954
1955 // CUDA/HIP: Check whether a captured reference variable is referencing a
1956 // host variable in a device or host device lambda.
isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema & S,VarDecl * VD)1957 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
1958 VarDecl *VD) {
1959 if (!S.getLangOpts().CUDA || !VD->hasInit())
1960 return false;
1961 assert(VD->getType()->isReferenceType());
1962
1963 // Check whether the reference variable is referencing a host variable.
1964 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
1965 if (!DRE)
1966 return false;
1967 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
1968 if (!Referee || !Referee->hasGlobalStorage() ||
1969 Referee->hasAttr<CUDADeviceAttr>())
1970 return false;
1971
1972 // Check whether the current function is a device or host device lambda.
1973 // Check whether the reference variable is a capture by getDeclContext()
1974 // since refersToEnclosingVariableOrCapture() is not ready at this point.
1975 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
1976 if (MD && MD->getParent()->isLambda() &&
1977 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
1978 VD->getDeclContext() != MD)
1979 return true;
1980
1981 return false;
1982 }
1983
getNonOdrUseReasonInCurrentContext(ValueDecl * D)1984 NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
1985 // A declaration named in an unevaluated operand never constitutes an odr-use.
1986 if (isUnevaluatedContext())
1987 return NOUR_Unevaluated;
1988
1989 // C++2a [basic.def.odr]p4:
1990 // A variable x whose name appears as a potentially-evaluated expression e
1991 // is odr-used by e unless [...] x is a reference that is usable in
1992 // constant expressions.
1993 // CUDA/HIP:
1994 // If a reference variable referencing a host variable is captured in a
1995 // device or host device lambda, the value of the referee must be copied
1996 // to the capture and the reference variable must be treated as odr-use
1997 // since the value of the referee is not known at compile time and must
1998 // be loaded from the captured.
1999 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2000 if (VD->getType()->isReferenceType() &&
2001 !(getLangOpts().OpenMP && isOpenMPCapturedDecl(D)) &&
2002 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&
2003 VD->isUsableInConstantExpressions(Context))
2004 return NOUR_Constant;
2005 }
2006
2007 // All remaining non-variable cases constitute an odr-use. For variables, we
2008 // need to wait and see how the expression is used.
2009 return NOUR_None;
2010 }
2011
2012 /// BuildDeclRefExpr - Build an expression that references a
2013 /// declaration that does not require a closure capture.
2014 DeclRefExpr *
BuildDeclRefExpr(ValueDecl * D,QualType Ty,ExprValueKind VK,const DeclarationNameInfo & NameInfo,NestedNameSpecifierLoc NNS,NamedDecl * FoundD,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)2015 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2016 const DeclarationNameInfo &NameInfo,
2017 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2018 SourceLocation TemplateKWLoc,
2019 const TemplateArgumentListInfo *TemplateArgs) {
2020 bool RefersToCapturedVariable =
2021 isa<VarDecl>(D) &&
2022 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
2023
2024 DeclRefExpr *E = DeclRefExpr::Create(
2025 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2026 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2027 MarkDeclRefReferenced(E);
2028
2029 // C++ [except.spec]p17:
2030 // An exception-specification is considered to be needed when:
2031 // - in an expression, the function is the unique lookup result or
2032 // the selected member of a set of overloaded functions.
2033 //
2034 // We delay doing this until after we've built the function reference and
2035 // marked it as used so that:
2036 // a) if the function is defaulted, we get errors from defining it before /
2037 // instead of errors from computing its exception specification, and
2038 // b) if the function is a defaulted comparison, we can use the body we
2039 // build when defining it as input to the exception specification
2040 // computation rather than computing a new body.
2041 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
2042 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2043 if (auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2044 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2045 }
2046 }
2047
2048 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2049 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2050 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2051 getCurFunction()->recordUseOfWeak(E);
2052
2053 FieldDecl *FD = dyn_cast<FieldDecl>(D);
2054 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
2055 FD = IFD->getAnonField();
2056 if (FD) {
2057 UnusedPrivateFields.remove(FD);
2058 // Just in case we're building an illegal pointer-to-member.
2059 if (FD->isBitField())
2060 E->setObjectKind(OK_BitField);
2061 }
2062
2063 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2064 // designates a bit-field.
2065 if (auto *BD = dyn_cast<BindingDecl>(D))
2066 if (auto *BE = BD->getBinding())
2067 E->setObjectKind(BE->getObjectKind());
2068
2069 return E;
2070 }
2071
2072 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2073 /// possibly a list of template arguments.
2074 ///
2075 /// If this produces template arguments, it is permitted to call
2076 /// DecomposeTemplateName.
2077 ///
2078 /// This actually loses a lot of source location information for
2079 /// non-standard name kinds; we should consider preserving that in
2080 /// some way.
2081 void
DecomposeUnqualifiedId(const UnqualifiedId & Id,TemplateArgumentListInfo & Buffer,DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * & TemplateArgs)2082 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2083 TemplateArgumentListInfo &Buffer,
2084 DeclarationNameInfo &NameInfo,
2085 const TemplateArgumentListInfo *&TemplateArgs) {
2086 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2087 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2088 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2089
2090 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2091 Id.TemplateId->NumArgs);
2092 translateTemplateArguments(TemplateArgsPtr, Buffer);
2093
2094 TemplateName TName = Id.TemplateId->Template.get();
2095 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2096 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2097 TemplateArgs = &Buffer;
2098 } else {
2099 NameInfo = GetNameFromUnqualifiedId(Id);
2100 TemplateArgs = nullptr;
2101 }
2102 }
2103
emitEmptyLookupTypoDiagnostic(const TypoCorrection & TC,Sema & SemaRef,const CXXScopeSpec & SS,DeclarationName Typo,SourceLocation TypoLoc,ArrayRef<Expr * > Args,unsigned DiagnosticID,unsigned DiagnosticSuggestID)2104 static void emitEmptyLookupTypoDiagnostic(
2105 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2106 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2107 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2108 DeclContext *Ctx =
2109 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2110 if (!TC) {
2111 // Emit a special diagnostic for failed member lookups.
2112 // FIXME: computing the declaration context might fail here (?)
2113 if (Ctx)
2114 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2115 << SS.getRange();
2116 else
2117 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2118 return;
2119 }
2120
2121 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2122 bool DroppedSpecifier =
2123 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2124 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2125 ? diag::note_implicit_param_decl
2126 : diag::note_previous_decl;
2127 if (!Ctx)
2128 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2129 SemaRef.PDiag(NoteID));
2130 else
2131 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2132 << Typo << Ctx << DroppedSpecifier
2133 << SS.getRange(),
2134 SemaRef.PDiag(NoteID));
2135 }
2136
2137 /// Diagnose a lookup that found results in an enclosing class during error
2138 /// recovery. This usually indicates that the results were found in a dependent
2139 /// base class that could not be searched as part of a template definition.
2140 /// Always issues a diagnostic (though this may be only a warning in MS
2141 /// compatibility mode).
2142 ///
2143 /// Return \c true if the error is unrecoverable, or \c false if the caller
2144 /// should attempt to recover using these lookup results.
DiagnoseDependentMemberLookup(LookupResult & R)2145 bool Sema::DiagnoseDependentMemberLookup(LookupResult &R) {
2146 // During a default argument instantiation the CurContext points
2147 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2148 // function parameter list, hence add an explicit check.
2149 bool isDefaultArgument =
2150 !CodeSynthesisContexts.empty() &&
2151 CodeSynthesisContexts.back().Kind ==
2152 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2153 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2154 bool isInstance = CurMethod && CurMethod->isInstance() &&
2155 R.getNamingClass() == CurMethod->getParent() &&
2156 !isDefaultArgument;
2157
2158 // There are two ways we can find a class-scope declaration during template
2159 // instantiation that we did not find in the template definition: if it is a
2160 // member of a dependent base class, or if it is declared after the point of
2161 // use in the same class. Distinguish these by comparing the class in which
2162 // the member was found to the naming class of the lookup.
2163 unsigned DiagID = diag::err_found_in_dependent_base;
2164 unsigned NoteID = diag::note_member_declared_at;
2165 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2166 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2167 : diag::err_found_later_in_class;
2168 } else if (getLangOpts().MSVCCompat) {
2169 DiagID = diag::ext_found_in_dependent_base;
2170 NoteID = diag::note_dependent_member_use;
2171 }
2172
2173 if (isInstance) {
2174 // Give a code modification hint to insert 'this->'.
2175 Diag(R.getNameLoc(), DiagID)
2176 << R.getLookupName()
2177 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2178 CheckCXXThisCapture(R.getNameLoc());
2179 } else {
2180 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2181 // they're not shadowed).
2182 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2183 }
2184
2185 for (NamedDecl *D : R)
2186 Diag(D->getLocation(), NoteID);
2187
2188 // Return true if we are inside a default argument instantiation
2189 // and the found name refers to an instance member function, otherwise
2190 // the caller will try to create an implicit member call and this is wrong
2191 // for default arguments.
2192 //
2193 // FIXME: Is this special case necessary? We could allow the caller to
2194 // diagnose this.
2195 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2196 Diag(R.getNameLoc(), diag::err_member_call_without_object);
2197 return true;
2198 }
2199
2200 // Tell the callee to try to recover.
2201 return false;
2202 }
2203
2204 /// Diagnose an empty lookup.
2205 ///
2206 /// \return false if new lookup candidates were found
DiagnoseEmptyLookup(Scope * S,CXXScopeSpec & SS,LookupResult & R,CorrectionCandidateCallback & CCC,TemplateArgumentListInfo * ExplicitTemplateArgs,ArrayRef<Expr * > Args,TypoExpr ** Out)2207 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2208 CorrectionCandidateCallback &CCC,
2209 TemplateArgumentListInfo *ExplicitTemplateArgs,
2210 ArrayRef<Expr *> Args, TypoExpr **Out) {
2211 DeclarationName Name = R.getLookupName();
2212
2213 unsigned diagnostic = diag::err_undeclared_var_use;
2214 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2215 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2216 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2217 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2218 diagnostic = diag::err_undeclared_use;
2219 diagnostic_suggest = diag::err_undeclared_use_suggest;
2220 }
2221
2222 // If the original lookup was an unqualified lookup, fake an
2223 // unqualified lookup. This is useful when (for example) the
2224 // original lookup would not have found something because it was a
2225 // dependent name.
2226 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
2227 while (DC) {
2228 if (isa<CXXRecordDecl>(DC)) {
2229 LookupQualifiedName(R, DC);
2230
2231 if (!R.empty()) {
2232 // Don't give errors about ambiguities in this lookup.
2233 R.suppressDiagnostics();
2234
2235 // If there's a best viable function among the results, only mention
2236 // that one in the notes.
2237 OverloadCandidateSet Candidates(R.getNameLoc(),
2238 OverloadCandidateSet::CSK_Normal);
2239 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2240 OverloadCandidateSet::iterator Best;
2241 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2242 OR_Success) {
2243 R.clear();
2244 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2245 R.resolveKind();
2246 }
2247
2248 return DiagnoseDependentMemberLookup(R);
2249 }
2250
2251 R.clear();
2252 }
2253
2254 DC = DC->getLookupParent();
2255 }
2256
2257 // We didn't find anything, so try to correct for a typo.
2258 TypoCorrection Corrected;
2259 if (S && Out) {
2260 SourceLocation TypoLoc = R.getNameLoc();
2261 assert(!ExplicitTemplateArgs &&
2262 "Diagnosing an empty lookup with explicit template args!");
2263 *Out = CorrectTypoDelayed(
2264 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2265 [=](const TypoCorrection &TC) {
2266 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2267 diagnostic, diagnostic_suggest);
2268 },
2269 nullptr, CTK_ErrorRecovery);
2270 if (*Out)
2271 return true;
2272 } else if (S &&
2273 (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
2274 S, &SS, CCC, CTK_ErrorRecovery))) {
2275 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2276 bool DroppedSpecifier =
2277 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2278 R.setLookupName(Corrected.getCorrection());
2279
2280 bool AcceptableWithRecovery = false;
2281 bool AcceptableWithoutRecovery = false;
2282 NamedDecl *ND = Corrected.getFoundDecl();
2283 if (ND) {
2284 if (Corrected.isOverloaded()) {
2285 OverloadCandidateSet OCS(R.getNameLoc(),
2286 OverloadCandidateSet::CSK_Normal);
2287 OverloadCandidateSet::iterator Best;
2288 for (NamedDecl *CD : Corrected) {
2289 if (FunctionTemplateDecl *FTD =
2290 dyn_cast<FunctionTemplateDecl>(CD))
2291 AddTemplateOverloadCandidate(
2292 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2293 Args, OCS);
2294 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2295 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2296 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
2297 Args, OCS);
2298 }
2299 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2300 case OR_Success:
2301 ND = Best->FoundDecl;
2302 Corrected.setCorrectionDecl(ND);
2303 break;
2304 default:
2305 // FIXME: Arbitrarily pick the first declaration for the note.
2306 Corrected.setCorrectionDecl(ND);
2307 break;
2308 }
2309 }
2310 R.addDecl(ND);
2311 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2312 CXXRecordDecl *Record = nullptr;
2313 if (Corrected.getCorrectionSpecifier()) {
2314 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2315 Record = Ty->getAsCXXRecordDecl();
2316 }
2317 if (!Record)
2318 Record = cast<CXXRecordDecl>(
2319 ND->getDeclContext()->getRedeclContext());
2320 R.setNamingClass(Record);
2321 }
2322
2323 auto *UnderlyingND = ND->getUnderlyingDecl();
2324 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2325 isa<FunctionTemplateDecl>(UnderlyingND);
2326 // FIXME: If we ended up with a typo for a type name or
2327 // Objective-C class name, we're in trouble because the parser
2328 // is in the wrong place to recover. Suggest the typo
2329 // correction, but don't make it a fix-it since we're not going
2330 // to recover well anyway.
2331 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2332 getAsTypeTemplateDecl(UnderlyingND) ||
2333 isa<ObjCInterfaceDecl>(UnderlyingND);
2334 } else {
2335 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2336 // because we aren't able to recover.
2337 AcceptableWithoutRecovery = true;
2338 }
2339
2340 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2341 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2342 ? diag::note_implicit_param_decl
2343 : diag::note_previous_decl;
2344 if (SS.isEmpty())
2345 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2346 PDiag(NoteID), AcceptableWithRecovery);
2347 else
2348 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2349 << Name << computeDeclContext(SS, false)
2350 << DroppedSpecifier << SS.getRange(),
2351 PDiag(NoteID), AcceptableWithRecovery);
2352
2353 // Tell the callee whether to try to recover.
2354 return !AcceptableWithRecovery;
2355 }
2356 }
2357 R.clear();
2358
2359 // Emit a special diagnostic for failed member lookups.
2360 // FIXME: computing the declaration context might fail here (?)
2361 if (!SS.isEmpty()) {
2362 Diag(R.getNameLoc(), diag::err_no_member)
2363 << Name << computeDeclContext(SS, false)
2364 << SS.getRange();
2365 return true;
2366 }
2367
2368 // Give up, we can't recover.
2369 Diag(R.getNameLoc(), diagnostic) << Name;
2370 return true;
2371 }
2372
2373 /// In Microsoft mode, if we are inside a template class whose parent class has
2374 /// dependent base classes, and we can't resolve an unqualified identifier, then
2375 /// assume the identifier is a member of a dependent base class. We can only
2376 /// recover successfully in static methods, instance methods, and other contexts
2377 /// where 'this' is available. This doesn't precisely match MSVC's
2378 /// instantiation model, but it's close enough.
2379 static Expr *
recoverFromMSUnqualifiedLookup(Sema & S,ASTContext & Context,DeclarationNameInfo & NameInfo,SourceLocation TemplateKWLoc,const TemplateArgumentListInfo * TemplateArgs)2380 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2381 DeclarationNameInfo &NameInfo,
2382 SourceLocation TemplateKWLoc,
2383 const TemplateArgumentListInfo *TemplateArgs) {
2384 // Only try to recover from lookup into dependent bases in static methods or
2385 // contexts where 'this' is available.
2386 QualType ThisType = S.getCurrentThisType();
2387 const CXXRecordDecl *RD = nullptr;
2388 if (!ThisType.isNull())
2389 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2390 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2391 RD = MD->getParent();
2392 if (!RD || !RD->hasAnyDependentBases())
2393 return nullptr;
2394
2395 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2396 // is available, suggest inserting 'this->' as a fixit.
2397 SourceLocation Loc = NameInfo.getLoc();
2398 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2399 DB << NameInfo.getName() << RD;
2400
2401 if (!ThisType.isNull()) {
2402 DB << FixItHint::CreateInsertion(Loc, "this->");
2403 return CXXDependentScopeMemberExpr::Create(
2404 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2405 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2406 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2407 }
2408
2409 // Synthesize a fake NNS that points to the derived class. This will
2410 // perform name lookup during template instantiation.
2411 CXXScopeSpec SS;
2412 auto *NNS =
2413 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2414 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2415 return DependentScopeDeclRefExpr::Create(
2416 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2417 TemplateArgs);
2418 }
2419
2420 ExprResult
ActOnIdExpression(Scope * S,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & Id,bool HasTrailingLParen,bool IsAddressOfOperand,CorrectionCandidateCallback * CCC,bool IsInlineAsmIdentifier,Token * KeywordReplacement)2421 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2422 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2423 bool HasTrailingLParen, bool IsAddressOfOperand,
2424 CorrectionCandidateCallback *CCC,
2425 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2426 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2427 "cannot be direct & operand and have a trailing lparen");
2428 if (SS.isInvalid())
2429 return ExprError();
2430
2431 TemplateArgumentListInfo TemplateArgsBuffer;
2432
2433 // Decompose the UnqualifiedId into the following data.
2434 DeclarationNameInfo NameInfo;
2435 const TemplateArgumentListInfo *TemplateArgs;
2436 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2437
2438 DeclarationName Name = NameInfo.getName();
2439 IdentifierInfo *II = Name.getAsIdentifierInfo();
2440 SourceLocation NameLoc = NameInfo.getLoc();
2441
2442 if (II && II->isEditorPlaceholder()) {
2443 // FIXME: When typed placeholders are supported we can create a typed
2444 // placeholder expression node.
2445 return ExprError();
2446 }
2447
2448 // C++ [temp.dep.expr]p3:
2449 // An id-expression is type-dependent if it contains:
2450 // -- an identifier that was declared with a dependent type,
2451 // (note: handled after lookup)
2452 // -- a template-id that is dependent,
2453 // (note: handled in BuildTemplateIdExpr)
2454 // -- a conversion-function-id that specifies a dependent type,
2455 // -- a nested-name-specifier that contains a class-name that
2456 // names a dependent type.
2457 // Determine whether this is a member of an unknown specialization;
2458 // we need to handle these differently.
2459 bool DependentID = false;
2460 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2461 Name.getCXXNameType()->isDependentType()) {
2462 DependentID = true;
2463 } else if (SS.isSet()) {
2464 if (DeclContext *DC = computeDeclContext(SS, false)) {
2465 if (RequireCompleteDeclContext(SS, DC))
2466 return ExprError();
2467 } else {
2468 DependentID = true;
2469 }
2470 }
2471
2472 if (DependentID)
2473 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2474 IsAddressOfOperand, TemplateArgs);
2475
2476 // Perform the required lookup.
2477 LookupResult R(*this, NameInfo,
2478 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2479 ? LookupObjCImplicitSelfParam
2480 : LookupOrdinaryName);
2481 if (TemplateKWLoc.isValid() || TemplateArgs) {
2482 // Lookup the template name again to correctly establish the context in
2483 // which it was found. This is really unfortunate as we already did the
2484 // lookup to determine that it was a template name in the first place. If
2485 // this becomes a performance hit, we can work harder to preserve those
2486 // results until we get here but it's likely not worth it.
2487 bool MemberOfUnknownSpecialization;
2488 AssumedTemplateKind AssumedTemplate;
2489 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2490 MemberOfUnknownSpecialization, TemplateKWLoc,
2491 &AssumedTemplate))
2492 return ExprError();
2493
2494 if (MemberOfUnknownSpecialization ||
2495 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2496 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2497 IsAddressOfOperand, TemplateArgs);
2498 } else {
2499 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2500 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2501
2502 // If the result might be in a dependent base class, this is a dependent
2503 // id-expression.
2504 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2505 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2506 IsAddressOfOperand, TemplateArgs);
2507
2508 // If this reference is in an Objective-C method, then we need to do
2509 // some special Objective-C lookup, too.
2510 if (IvarLookupFollowUp) {
2511 ExprResult E(LookupInObjCMethod(R, S, II, true));
2512 if (E.isInvalid())
2513 return ExprError();
2514
2515 if (Expr *Ex = E.getAs<Expr>())
2516 return Ex;
2517 }
2518 }
2519
2520 if (R.isAmbiguous())
2521 return ExprError();
2522
2523 // This could be an implicitly declared function reference (legal in C90,
2524 // extension in C99, forbidden in C++).
2525 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2526 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2527 if (D) R.addDecl(D);
2528 }
2529
2530 // Determine whether this name might be a candidate for
2531 // argument-dependent lookup.
2532 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2533
2534 if (R.empty() && !ADL) {
2535 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2536 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2537 TemplateKWLoc, TemplateArgs))
2538 return E;
2539 }
2540
2541 // Don't diagnose an empty lookup for inline assembly.
2542 if (IsInlineAsmIdentifier)
2543 return ExprError();
2544
2545 // If this name wasn't predeclared and if this is not a function
2546 // call, diagnose the problem.
2547 TypoExpr *TE = nullptr;
2548 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2549 : nullptr);
2550 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2551 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2552 "Typo correction callback misconfigured");
2553 if (CCC) {
2554 // Make sure the callback knows what the typo being diagnosed is.
2555 CCC->setTypoName(II);
2556 if (SS.isValid())
2557 CCC->setTypoNNS(SS.getScopeRep());
2558 }
2559 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2560 // a template name, but we happen to have always already looked up the name
2561 // before we get here if it must be a template name.
2562 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2563 None, &TE)) {
2564 if (TE && KeywordReplacement) {
2565 auto &State = getTypoExprState(TE);
2566 auto BestTC = State.Consumer->getNextCorrection();
2567 if (BestTC.isKeyword()) {
2568 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2569 if (State.DiagHandler)
2570 State.DiagHandler(BestTC);
2571 KeywordReplacement->startToken();
2572 KeywordReplacement->setKind(II->getTokenID());
2573 KeywordReplacement->setIdentifierInfo(II);
2574 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2575 // Clean up the state associated with the TypoExpr, since it has
2576 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2577 clearDelayedTypo(TE);
2578 // Signal that a correction to a keyword was performed by returning a
2579 // valid-but-null ExprResult.
2580 return (Expr*)nullptr;
2581 }
2582 State.Consumer->resetCorrectionStream();
2583 }
2584 return TE ? TE : ExprError();
2585 }
2586
2587 assert(!R.empty() &&
2588 "DiagnoseEmptyLookup returned false but added no results");
2589
2590 // If we found an Objective-C instance variable, let
2591 // LookupInObjCMethod build the appropriate expression to
2592 // reference the ivar.
2593 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2594 R.clear();
2595 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2596 // In a hopelessly buggy code, Objective-C instance variable
2597 // lookup fails and no expression will be built to reference it.
2598 if (!E.isInvalid() && !E.get())
2599 return ExprError();
2600 return E;
2601 }
2602 }
2603
2604 // This is guaranteed from this point on.
2605 assert(!R.empty() || ADL);
2606
2607 // Check whether this might be a C++ implicit instance member access.
2608 // C++ [class.mfct.non-static]p3:
2609 // When an id-expression that is not part of a class member access
2610 // syntax and not used to form a pointer to member is used in the
2611 // body of a non-static member function of class X, if name lookup
2612 // resolves the name in the id-expression to a non-static non-type
2613 // member of some class C, the id-expression is transformed into a
2614 // class member access expression using (*this) as the
2615 // postfix-expression to the left of the . operator.
2616 //
2617 // But we don't actually need to do this for '&' operands if R
2618 // resolved to a function or overloaded function set, because the
2619 // expression is ill-formed if it actually works out to be a
2620 // non-static member function:
2621 //
2622 // C++ [expr.ref]p4:
2623 // Otherwise, if E1.E2 refers to a non-static member function. . .
2624 // [t]he expression can be used only as the left-hand operand of a
2625 // member function call.
2626 //
2627 // There are other safeguards against such uses, but it's important
2628 // to get this right here so that we don't end up making a
2629 // spuriously dependent expression if we're inside a dependent
2630 // instance method.
2631 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2632 bool MightBeImplicitMember;
2633 if (!IsAddressOfOperand)
2634 MightBeImplicitMember = true;
2635 else if (!SS.isEmpty())
2636 MightBeImplicitMember = false;
2637 else if (R.isOverloadedResult())
2638 MightBeImplicitMember = false;
2639 else if (R.isUnresolvableResult())
2640 MightBeImplicitMember = true;
2641 else
2642 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2643 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2644 isa<MSPropertyDecl>(R.getFoundDecl());
2645
2646 if (MightBeImplicitMember)
2647 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2648 R, TemplateArgs, S);
2649 }
2650
2651 if (TemplateArgs || TemplateKWLoc.isValid()) {
2652
2653 // In C++1y, if this is a variable template id, then check it
2654 // in BuildTemplateIdExpr().
2655 // The single lookup result must be a variable template declaration.
2656 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2657 Id.TemplateId->Kind == TNK_Var_template) {
2658 assert(R.getAsSingle<VarTemplateDecl>() &&
2659 "There should only be one declaration found.");
2660 }
2661
2662 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2663 }
2664
2665 return BuildDeclarationNameExpr(SS, R, ADL);
2666 }
2667
2668 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2669 /// declaration name, generally during template instantiation.
2670 /// There's a large number of things which don't need to be done along
2671 /// this path.
BuildQualifiedDeclarationNameExpr(CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,bool IsAddressOfOperand,const Scope * S,TypeSourceInfo ** RecoveryTSI)2672 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2673 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2674 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2675 DeclContext *DC = computeDeclContext(SS, false);
2676 if (!DC)
2677 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2678 NameInfo, /*TemplateArgs=*/nullptr);
2679
2680 if (RequireCompleteDeclContext(SS, DC))
2681 return ExprError();
2682
2683 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2684 LookupQualifiedName(R, DC);
2685
2686 if (R.isAmbiguous())
2687 return ExprError();
2688
2689 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2690 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2691 NameInfo, /*TemplateArgs=*/nullptr);
2692
2693 if (R.empty()) {
2694 // Don't diagnose problems with invalid record decl, the secondary no_member
2695 // diagnostic during template instantiation is likely bogus, e.g. if a class
2696 // is invalid because it's derived from an invalid base class, then missing
2697 // members were likely supposed to be inherited.
2698 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2699 if (CD->isInvalidDecl())
2700 return ExprError();
2701 Diag(NameInfo.getLoc(), diag::err_no_member)
2702 << NameInfo.getName() << DC << SS.getRange();
2703 return ExprError();
2704 }
2705
2706 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2707 // Diagnose a missing typename if this resolved unambiguously to a type in
2708 // a dependent context. If we can recover with a type, downgrade this to
2709 // a warning in Microsoft compatibility mode.
2710 unsigned DiagID = diag::err_typename_missing;
2711 if (RecoveryTSI && getLangOpts().MSVCCompat)
2712 DiagID = diag::ext_typename_missing;
2713 SourceLocation Loc = SS.getBeginLoc();
2714 auto D = Diag(Loc, DiagID);
2715 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2716 << SourceRange(Loc, NameInfo.getEndLoc());
2717
2718 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2719 // context.
2720 if (!RecoveryTSI)
2721 return ExprError();
2722
2723 // Only issue the fixit if we're prepared to recover.
2724 D << FixItHint::CreateInsertion(Loc, "typename ");
2725
2726 // Recover by pretending this was an elaborated type.
2727 QualType Ty = Context.getTypeDeclType(TD);
2728 TypeLocBuilder TLB;
2729 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2730
2731 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2732 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2733 QTL.setElaboratedKeywordLoc(SourceLocation());
2734 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2735
2736 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2737
2738 return ExprEmpty();
2739 }
2740
2741 // Defend against this resolving to an implicit member access. We usually
2742 // won't get here if this might be a legitimate a class member (we end up in
2743 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2744 // a pointer-to-member or in an unevaluated context in C++11.
2745 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2746 return BuildPossibleImplicitMemberExpr(SS,
2747 /*TemplateKWLoc=*/SourceLocation(),
2748 R, /*TemplateArgs=*/nullptr, S);
2749
2750 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2751 }
2752
2753 /// The parser has read a name in, and Sema has detected that we're currently
2754 /// inside an ObjC method. Perform some additional checks and determine if we
2755 /// should form a reference to an ivar.
2756 ///
2757 /// Ideally, most of this would be done by lookup, but there's
2758 /// actually quite a lot of extra work involved.
LookupIvarInObjCMethod(LookupResult & Lookup,Scope * S,IdentifierInfo * II)2759 DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
2760 IdentifierInfo *II) {
2761 SourceLocation Loc = Lookup.getNameLoc();
2762 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2763
2764 // Check for error condition which is already reported.
2765 if (!CurMethod)
2766 return DeclResult(true);
2767
2768 // There are two cases to handle here. 1) scoped lookup could have failed,
2769 // in which case we should look for an ivar. 2) scoped lookup could have
2770 // found a decl, but that decl is outside the current instance method (i.e.
2771 // a global variable). In these two cases, we do a lookup for an ivar with
2772 // this name, if the lookup sucedes, we replace it our current decl.
2773
2774 // If we're in a class method, we don't normally want to look for
2775 // ivars. But if we don't find anything else, and there's an
2776 // ivar, that's an error.
2777 bool IsClassMethod = CurMethod->isClassMethod();
2778
2779 bool LookForIvars;
2780 if (Lookup.empty())
2781 LookForIvars = true;
2782 else if (IsClassMethod)
2783 LookForIvars = false;
2784 else
2785 LookForIvars = (Lookup.isSingleResult() &&
2786 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2787 ObjCInterfaceDecl *IFace = nullptr;
2788 if (LookForIvars) {
2789 IFace = CurMethod->getClassInterface();
2790 ObjCInterfaceDecl *ClassDeclared;
2791 ObjCIvarDecl *IV = nullptr;
2792 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2793 // Diagnose using an ivar in a class method.
2794 if (IsClassMethod) {
2795 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2796 return DeclResult(true);
2797 }
2798
2799 // Diagnose the use of an ivar outside of the declaring class.
2800 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2801 !declaresSameEntity(ClassDeclared, IFace) &&
2802 !getLangOpts().DebuggerSupport)
2803 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2804
2805 // Success.
2806 return IV;
2807 }
2808 } else if (CurMethod->isInstanceMethod()) {
2809 // We should warn if a local variable hides an ivar.
2810 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2811 ObjCInterfaceDecl *ClassDeclared;
2812 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2813 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2814 declaresSameEntity(IFace, ClassDeclared))
2815 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2816 }
2817 }
2818 } else if (Lookup.isSingleResult() &&
2819 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2820 // If accessing a stand-alone ivar in a class method, this is an error.
2821 if (const ObjCIvarDecl *IV =
2822 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
2823 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
2824 return DeclResult(true);
2825 }
2826 }
2827
2828 // Didn't encounter an error, didn't find an ivar.
2829 return DeclResult(false);
2830 }
2831
BuildIvarRefExpr(Scope * S,SourceLocation Loc,ObjCIvarDecl * IV)2832 ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
2833 ObjCIvarDecl *IV) {
2834 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2835 assert(CurMethod && CurMethod->isInstanceMethod() &&
2836 "should not reference ivar from this context");
2837
2838 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
2839 assert(IFace && "should not reference ivar from this context");
2840
2841 // If we're referencing an invalid decl, just return this as a silent
2842 // error node. The error diagnostic was already emitted on the decl.
2843 if (IV->isInvalidDecl())
2844 return ExprError();
2845
2846 // Check if referencing a field with __attribute__((deprecated)).
2847 if (DiagnoseUseOfDecl(IV, Loc))
2848 return ExprError();
2849
2850 // FIXME: This should use a new expr for a direct reference, don't
2851 // turn this into Self->ivar, just return a BareIVarExpr or something.
2852 IdentifierInfo &II = Context.Idents.get("self");
2853 UnqualifiedId SelfName;
2854 SelfName.setIdentifier(&II, SourceLocation());
2855 SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2856 CXXScopeSpec SelfScopeSpec;
2857 SourceLocation TemplateKWLoc;
2858 ExprResult SelfExpr =
2859 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
2860 /*HasTrailingLParen=*/false,
2861 /*IsAddressOfOperand=*/false);
2862 if (SelfExpr.isInvalid())
2863 return ExprError();
2864
2865 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2866 if (SelfExpr.isInvalid())
2867 return ExprError();
2868
2869 MarkAnyDeclReferenced(Loc, IV, true);
2870
2871 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2872 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2873 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2874 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2875
2876 ObjCIvarRefExpr *Result = new (Context)
2877 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2878 IV->getLocation(), SelfExpr.get(), true, true);
2879
2880 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2881 if (!isUnevaluatedContext() &&
2882 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2883 getCurFunction()->recordUseOfWeak(Result);
2884 }
2885 if (getLangOpts().ObjCAutoRefCount)
2886 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
2887 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
2888
2889 return Result;
2890 }
2891
2892 /// The parser has read a name in, and Sema has detected that we're currently
2893 /// inside an ObjC method. Perform some additional checks and determine if we
2894 /// should form a reference to an ivar. If so, build an expression referencing
2895 /// that ivar.
2896 ExprResult
LookupInObjCMethod(LookupResult & Lookup,Scope * S,IdentifierInfo * II,bool AllowBuiltinCreation)2897 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2898 IdentifierInfo *II, bool AllowBuiltinCreation) {
2899 // FIXME: Integrate this lookup step into LookupParsedName.
2900 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
2901 if (Ivar.isInvalid())
2902 return ExprError();
2903 if (Ivar.isUsable())
2904 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
2905 cast<ObjCIvarDecl>(Ivar.get()));
2906
2907 if (Lookup.empty() && II && AllowBuiltinCreation)
2908 LookupBuiltin(Lookup);
2909
2910 // Sentinel value saying that we didn't do anything special.
2911 return ExprResult(false);
2912 }
2913
2914 /// Cast a base object to a member's actual type.
2915 ///
2916 /// There are two relevant checks:
2917 ///
2918 /// C++ [class.access.base]p7:
2919 ///
2920 /// If a class member access operator [...] is used to access a non-static
2921 /// data member or non-static member function, the reference is ill-formed if
2922 /// the left operand [...] cannot be implicitly converted to a pointer to the
2923 /// naming class of the right operand.
2924 ///
2925 /// C++ [expr.ref]p7:
2926 ///
2927 /// If E2 is a non-static data member or a non-static member function, the
2928 /// program is ill-formed if the class of which E2 is directly a member is an
2929 /// ambiguous base (11.8) of the naming class (11.9.3) of E2.
2930 ///
2931 /// Note that the latter check does not consider access; the access of the
2932 /// "real" base class is checked as appropriate when checking the access of the
2933 /// member name.
2934 ExprResult
PerformObjectMemberConversion(Expr * From,NestedNameSpecifier * Qualifier,NamedDecl * FoundDecl,NamedDecl * Member)2935 Sema::PerformObjectMemberConversion(Expr *From,
2936 NestedNameSpecifier *Qualifier,
2937 NamedDecl *FoundDecl,
2938 NamedDecl *Member) {
2939 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2940 if (!RD)
2941 return From;
2942
2943 QualType DestRecordType;
2944 QualType DestType;
2945 QualType FromRecordType;
2946 QualType FromType = From->getType();
2947 bool PointerConversions = false;
2948 if (isa<FieldDecl>(Member)) {
2949 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2950 auto FromPtrType = FromType->getAs<PointerType>();
2951 DestRecordType = Context.getAddrSpaceQualType(
2952 DestRecordType, FromPtrType
2953 ? FromType->getPointeeType().getAddressSpace()
2954 : FromType.getAddressSpace());
2955
2956 if (FromPtrType) {
2957 DestType = Context.getPointerType(DestRecordType);
2958 FromRecordType = FromPtrType->getPointeeType();
2959 PointerConversions = true;
2960 } else {
2961 DestType = DestRecordType;
2962 FromRecordType = FromType;
2963 }
2964 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2965 if (Method->isStatic())
2966 return From;
2967
2968 DestType = Method->getThisType();
2969 DestRecordType = DestType->getPointeeType();
2970
2971 if (FromType->getAs<PointerType>()) {
2972 FromRecordType = FromType->getPointeeType();
2973 PointerConversions = true;
2974 } else {
2975 FromRecordType = FromType;
2976 DestType = DestRecordType;
2977 }
2978
2979 LangAS FromAS = FromRecordType.getAddressSpace();
2980 LangAS DestAS = DestRecordType.getAddressSpace();
2981 if (FromAS != DestAS) {
2982 QualType FromRecordTypeWithoutAS =
2983 Context.removeAddrSpaceQualType(FromRecordType);
2984 QualType FromTypeWithDestAS =
2985 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2986 if (PointerConversions)
2987 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2988 From = ImpCastExprToType(From, FromTypeWithDestAS,
2989 CK_AddressSpaceConversion, From->getValueKind())
2990 .get();
2991 }
2992 } else {
2993 // No conversion necessary.
2994 return From;
2995 }
2996
2997 if (DestType->isDependentType() || FromType->isDependentType())
2998 return From;
2999
3000 // If the unqualified types are the same, no conversion is necessary.
3001 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3002 return From;
3003
3004 SourceRange FromRange = From->getSourceRange();
3005 SourceLocation FromLoc = FromRange.getBegin();
3006
3007 ExprValueKind VK = From->getValueKind();
3008
3009 // C++ [class.member.lookup]p8:
3010 // [...] Ambiguities can often be resolved by qualifying a name with its
3011 // class name.
3012 //
3013 // If the member was a qualified name and the qualified referred to a
3014 // specific base subobject type, we'll cast to that intermediate type
3015 // first and then to the object in which the member is declared. That allows
3016 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3017 //
3018 // class Base { public: int x; };
3019 // class Derived1 : public Base { };
3020 // class Derived2 : public Base { };
3021 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3022 //
3023 // void VeryDerived::f() {
3024 // x = 17; // error: ambiguous base subobjects
3025 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3026 // }
3027 if (Qualifier && Qualifier->getAsType()) {
3028 QualType QType = QualType(Qualifier->getAsType(), 0);
3029 assert(QType->isRecordType() && "lookup done with non-record type");
3030
3031 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
3032
3033 // In C++98, the qualifier type doesn't actually have to be a base
3034 // type of the object type, in which case we just ignore it.
3035 // Otherwise build the appropriate casts.
3036 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3037 CXXCastPath BasePath;
3038 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3039 FromLoc, FromRange, &BasePath))
3040 return ExprError();
3041
3042 if (PointerConversions)
3043 QType = Context.getPointerType(QType);
3044 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3045 VK, &BasePath).get();
3046
3047 FromType = QType;
3048 FromRecordType = QRecordType;
3049
3050 // If the qualifier type was the same as the destination type,
3051 // we're done.
3052 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3053 return From;
3054 }
3055 }
3056
3057 CXXCastPath BasePath;
3058 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3059 FromLoc, FromRange, &BasePath,
3060 /*IgnoreAccess=*/true))
3061 return ExprError();
3062
3063 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3064 VK, &BasePath);
3065 }
3066
UseArgumentDependentLookup(const CXXScopeSpec & SS,const LookupResult & R,bool HasTrailingLParen)3067 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
3068 const LookupResult &R,
3069 bool HasTrailingLParen) {
3070 // Only when used directly as the postfix-expression of a call.
3071 if (!HasTrailingLParen)
3072 return false;
3073
3074 // Never if a scope specifier was provided.
3075 if (SS.isSet())
3076 return false;
3077
3078 // Only in C++ or ObjC++.
3079 if (!getLangOpts().CPlusPlus)
3080 return false;
3081
3082 // Turn off ADL when we find certain kinds of declarations during
3083 // normal lookup:
3084 for (NamedDecl *D : R) {
3085 // C++0x [basic.lookup.argdep]p3:
3086 // -- a declaration of a class member
3087 // Since using decls preserve this property, we check this on the
3088 // original decl.
3089 if (D->isCXXClassMember())
3090 return false;
3091
3092 // C++0x [basic.lookup.argdep]p3:
3093 // -- a block-scope function declaration that is not a
3094 // using-declaration
3095 // NOTE: we also trigger this for function templates (in fact, we
3096 // don't check the decl type at all, since all other decl types
3097 // turn off ADL anyway).
3098 if (isa<UsingShadowDecl>(D))
3099 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3100 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3101 return false;
3102
3103 // C++0x [basic.lookup.argdep]p3:
3104 // -- a declaration that is neither a function or a function
3105 // template
3106 // And also for builtin functions.
3107 if (isa<FunctionDecl>(D)) {
3108 FunctionDecl *FDecl = cast<FunctionDecl>(D);
3109
3110 // But also builtin functions.
3111 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3112 return false;
3113 } else if (!isa<FunctionTemplateDecl>(D))
3114 return false;
3115 }
3116
3117 return true;
3118 }
3119
3120
3121 /// Diagnoses obvious problems with the use of the given declaration
3122 /// as an expression. This is only actually called for lookups that
3123 /// were not overloaded, and it doesn't promise that the declaration
3124 /// will in fact be used.
CheckDeclInExpr(Sema & S,SourceLocation Loc,NamedDecl * D)3125 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
3126 if (D->isInvalidDecl())
3127 return true;
3128
3129 if (isa<TypedefNameDecl>(D)) {
3130 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3131 return true;
3132 }
3133
3134 if (isa<ObjCInterfaceDecl>(D)) {
3135 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3136 return true;
3137 }
3138
3139 if (isa<NamespaceDecl>(D)) {
3140 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3141 return true;
3142 }
3143
3144 return false;
3145 }
3146
3147 // Certain multiversion types should be treated as overloaded even when there is
3148 // only one result.
ShouldLookupResultBeMultiVersionOverload(const LookupResult & R)3149 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3150 assert(R.isSingleResult() && "Expected only a single result");
3151 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3152 return FD &&
3153 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3154 }
3155
BuildDeclarationNameExpr(const CXXScopeSpec & SS,LookupResult & R,bool NeedsADL,bool AcceptInvalidDecl)3156 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
3157 LookupResult &R, bool NeedsADL,
3158 bool AcceptInvalidDecl) {
3159 // If this is a single, fully-resolved result and we don't need ADL,
3160 // just build an ordinary singleton decl ref.
3161 if (!NeedsADL && R.isSingleResult() &&
3162 !R.getAsSingle<FunctionTemplateDecl>() &&
3163 !ShouldLookupResultBeMultiVersionOverload(R))
3164 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3165 R.getRepresentativeDecl(), nullptr,
3166 AcceptInvalidDecl);
3167
3168 // We only need to check the declaration if there's exactly one
3169 // result, because in the overloaded case the results can only be
3170 // functions and function templates.
3171 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3172 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
3173 return ExprError();
3174
3175 // Otherwise, just build an unresolved lookup expression. Suppress
3176 // any lookup-related diagnostics; we'll hash these out later, when
3177 // we've picked a target.
3178 R.suppressDiagnostics();
3179
3180 UnresolvedLookupExpr *ULE
3181 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3182 SS.getWithLocInContext(Context),
3183 R.getLookupNameInfo(),
3184 NeedsADL, R.isOverloadedResult(),
3185 R.begin(), R.end());
3186
3187 return ULE;
3188 }
3189
3190 static void
3191 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
3192 ValueDecl *var, DeclContext *DC);
3193
3194 /// 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)3195 ExprResult Sema::BuildDeclarationNameExpr(
3196 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3197 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3198 bool AcceptInvalidDecl) {
3199 assert(D && "Cannot refer to a NULL declaration");
3200 assert(!isa<FunctionTemplateDecl>(D) &&
3201 "Cannot refer unambiguously to a function template");
3202
3203 SourceLocation Loc = NameInfo.getLoc();
3204 if (CheckDeclInExpr(*this, Loc, D))
3205 return ExprError();
3206
3207 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3208 // Specifically diagnose references to class templates that are missing
3209 // a template argument list.
3210 diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
3211 return ExprError();
3212 }
3213
3214 // Make sure that we're referring to a value.
3215 ValueDecl *VD = dyn_cast<ValueDecl>(D);
3216 if (!VD) {
3217 Diag(Loc, diag::err_ref_non_value)
3218 << D << SS.getRange();
3219 Diag(D->getLocation(), diag::note_declared_at);
3220 return ExprError();
3221 }
3222
3223 // Check whether this declaration can be used. Note that we suppress
3224 // this check when we're going to perform argument-dependent lookup
3225 // on this function name, because this might not be the function
3226 // that overload resolution actually selects.
3227 if (DiagnoseUseOfDecl(VD, Loc))
3228 return ExprError();
3229
3230 // Only create DeclRefExpr's for valid Decl's.
3231 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3232 return ExprError();
3233
3234 // Handle members of anonymous structs and unions. If we got here,
3235 // and the reference is to a class member indirect field, then this
3236 // must be the subject of a pointer-to-member expression.
3237 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
3238 if (!indirectField->isCXXClassMember())
3239 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
3240 indirectField);
3241
3242 {
3243 QualType type = VD->getType();
3244 if (type.isNull())
3245 return ExprError();
3246 ExprValueKind valueKind = VK_RValue;
3247
3248 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3249 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3250 // is expanded by some outer '...' in the context of the use.
3251 type = type.getNonPackExpansionType();
3252
3253 switch (D->getKind()) {
3254 // Ignore all the non-ValueDecl kinds.
3255 #define ABSTRACT_DECL(kind)
3256 #define VALUE(type, base)
3257 #define DECL(type, base) \
3258 case Decl::type:
3259 #include "clang/AST/DeclNodes.inc"
3260 llvm_unreachable("invalid value decl kind");
3261
3262 // These shouldn't make it here.
3263 case Decl::ObjCAtDefsField:
3264 llvm_unreachable("forming non-member reference to ivar?");
3265
3266 // Enum constants are always r-values and never references.
3267 // Unresolved using declarations are dependent.
3268 case Decl::EnumConstant:
3269 case Decl::UnresolvedUsingValue:
3270 case Decl::OMPDeclareReduction:
3271 case Decl::OMPDeclareMapper:
3272 valueKind = VK_RValue;
3273 break;
3274
3275 // Fields and indirect fields that got here must be for
3276 // pointer-to-member expressions; we just call them l-values for
3277 // internal consistency, because this subexpression doesn't really
3278 // exist in the high-level semantics.
3279 case Decl::Field:
3280 case Decl::IndirectField:
3281 case Decl::ObjCIvar:
3282 assert(getLangOpts().CPlusPlus &&
3283 "building reference to field in C?");
3284
3285 // These can't have reference type in well-formed programs, but
3286 // for internal consistency we do this anyway.
3287 type = type.getNonReferenceType();
3288 valueKind = VK_LValue;
3289 break;
3290
3291 // Non-type template parameters are either l-values or r-values
3292 // depending on the type.
3293 case Decl::NonTypeTemplateParm: {
3294 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3295 type = reftype->getPointeeType();
3296 valueKind = VK_LValue; // even if the parameter is an r-value reference
3297 break;
3298 }
3299
3300 // [expr.prim.id.unqual]p2:
3301 // If the entity is a template parameter object for a template
3302 // parameter of type T, the type of the expression is const T.
3303 // [...] The expression is an lvalue if the entity is a [...] template
3304 // parameter object.
3305 if (type->isRecordType()) {
3306 type = type.getUnqualifiedType().withConst();
3307 valueKind = VK_LValue;
3308 break;
3309 }
3310
3311 // For non-references, we need to strip qualifiers just in case
3312 // the template parameter was declared as 'const int' or whatever.
3313 valueKind = VK_RValue;
3314 type = type.getUnqualifiedType();
3315 break;
3316 }
3317
3318 case Decl::Var:
3319 case Decl::VarTemplateSpecialization:
3320 case Decl::VarTemplatePartialSpecialization:
3321 case Decl::Decomposition:
3322 case Decl::OMPCapturedExpr:
3323 // In C, "extern void blah;" is valid and is an r-value.
3324 if (!getLangOpts().CPlusPlus &&
3325 !type.hasQualifiers() &&
3326 type->isVoidType()) {
3327 valueKind = VK_RValue;
3328 break;
3329 }
3330 LLVM_FALLTHROUGH;
3331
3332 case Decl::ImplicitParam:
3333 case Decl::ParmVar: {
3334 // These are always l-values.
3335 valueKind = VK_LValue;
3336 type = type.getNonReferenceType();
3337
3338 // FIXME: Does the addition of const really only apply in
3339 // potentially-evaluated contexts? Since the variable isn't actually
3340 // captured in an unevaluated context, it seems that the answer is no.
3341 if (!isUnevaluatedContext()) {
3342 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3343 if (!CapturedType.isNull())
3344 type = CapturedType;
3345 }
3346
3347 break;
3348 }
3349
3350 case Decl::Binding: {
3351 // These are always lvalues.
3352 valueKind = VK_LValue;
3353 type = type.getNonReferenceType();
3354 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3355 // decides how that's supposed to work.
3356 auto *BD = cast<BindingDecl>(VD);
3357 if (BD->getDeclContext() != CurContext) {
3358 auto *DD = dyn_cast_or_null<VarDecl>(BD->getDecomposedDecl());
3359 if (DD && DD->hasLocalStorage())
3360 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3361 }
3362 break;
3363 }
3364
3365 case Decl::Function: {
3366 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3367 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3368 type = Context.BuiltinFnTy;
3369 valueKind = VK_RValue;
3370 break;
3371 }
3372 }
3373
3374 const FunctionType *fty = type->castAs<FunctionType>();
3375
3376 // If we're referring to a function with an __unknown_anytype
3377 // result type, make the entire expression __unknown_anytype.
3378 if (fty->getReturnType() == Context.UnknownAnyTy) {
3379 type = Context.UnknownAnyTy;
3380 valueKind = VK_RValue;
3381 break;
3382 }
3383
3384 // Functions are l-values in C++.
3385 if (getLangOpts().CPlusPlus) {
3386 valueKind = VK_LValue;
3387 break;
3388 }
3389
3390 // C99 DR 316 says that, if a function type comes from a
3391 // function definition (without a prototype), that type is only
3392 // used for checking compatibility. Therefore, when referencing
3393 // the function, we pretend that we don't have the full function
3394 // type.
3395 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3396 isa<FunctionProtoType>(fty))
3397 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3398 fty->getExtInfo());
3399
3400 // Functions are r-values in C.
3401 valueKind = VK_RValue;
3402 break;
3403 }
3404
3405 case Decl::CXXDeductionGuide:
3406 llvm_unreachable("building reference to deduction guide");
3407
3408 case Decl::MSProperty:
3409 case Decl::MSGuid:
3410 case Decl::TemplateParamObject:
3411 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3412 // capture in OpenMP, or duplicated between host and device?
3413 valueKind = VK_LValue;
3414 break;
3415
3416 case Decl::CXXMethod:
3417 // If we're referring to a method with an __unknown_anytype
3418 // result type, make the entire expression __unknown_anytype.
3419 // This should only be possible with a type written directly.
3420 if (const FunctionProtoType *proto
3421 = dyn_cast<FunctionProtoType>(VD->getType()))
3422 if (proto->getReturnType() == Context.UnknownAnyTy) {
3423 type = Context.UnknownAnyTy;
3424 valueKind = VK_RValue;
3425 break;
3426 }
3427
3428 // C++ methods are l-values if static, r-values if non-static.
3429 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3430 valueKind = VK_LValue;
3431 break;
3432 }
3433 LLVM_FALLTHROUGH;
3434
3435 case Decl::CXXConversion:
3436 case Decl::CXXDestructor:
3437 case Decl::CXXConstructor:
3438 valueKind = VK_RValue;
3439 break;
3440 }
3441
3442 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3443 /*FIXME: TemplateKWLoc*/ SourceLocation(),
3444 TemplateArgs);
3445 }
3446 }
3447
ConvertUTF8ToWideString(unsigned CharByteWidth,StringRef Source,SmallString<32> & Target)3448 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3449 SmallString<32> &Target) {
3450 Target.resize(CharByteWidth * (Source.size() + 1));
3451 char *ResultPtr = &Target[0];
3452 const llvm::UTF8 *ErrorPtr;
3453 bool success =
3454 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3455 (void)success;
3456 assert(success);
3457 Target.resize(ResultPtr - &Target[0]);
3458 }
3459
BuildPredefinedExpr(SourceLocation Loc,PredefinedExpr::IdentKind IK)3460 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3461 PredefinedExpr::IdentKind IK) {
3462 // Pick the current block, lambda, captured statement or function.
3463 Decl *currentDecl = nullptr;
3464 if (const BlockScopeInfo *BSI = getCurBlock())
3465 currentDecl = BSI->TheDecl;
3466 else if (const LambdaScopeInfo *LSI = getCurLambda())
3467 currentDecl = LSI->CallOperator;
3468 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3469 currentDecl = CSI->TheCapturedDecl;
3470 else
3471 currentDecl = getCurFunctionOrMethodDecl();
3472
3473 if (!currentDecl) {
3474 Diag(Loc, diag::ext_predef_outside_function);
3475 currentDecl = Context.getTranslationUnitDecl();
3476 }
3477
3478 QualType ResTy;
3479 StringLiteral *SL = nullptr;
3480 if (cast<DeclContext>(currentDecl)->isDependentContext())
3481 ResTy = Context.DependentTy;
3482 else {
3483 // Pre-defined identifiers are of type char[x], where x is the length of
3484 // the string.
3485 auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3486 unsigned Length = Str.length();
3487
3488 llvm::APInt LengthI(32, Length + 1);
3489 if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3490 ResTy =
3491 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3492 SmallString<32> RawChars;
3493 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3494 Str, RawChars);
3495 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3496 ArrayType::Normal,
3497 /*IndexTypeQuals*/ 0);
3498 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3499 /*Pascal*/ false, ResTy, Loc);
3500 } else {
3501 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3502 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3503 ArrayType::Normal,
3504 /*IndexTypeQuals*/ 0);
3505 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3506 /*Pascal*/ false, ResTy, Loc);
3507 }
3508 }
3509
3510 return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3511 }
3512
ActOnPredefinedExpr(SourceLocation Loc,tok::TokenKind Kind)3513 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3514 PredefinedExpr::IdentKind IK;
3515
3516 switch (Kind) {
3517 default: llvm_unreachable("Unknown simple primary expr!");
3518 case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3519 case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3520 case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3521 case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3522 case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3523 case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3524 case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3525 }
3526
3527 return BuildPredefinedExpr(Loc, IK);
3528 }
3529
ActOnCharacterConstant(const Token & Tok,Scope * UDLScope)3530 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3531 SmallString<16> CharBuffer;
3532 bool Invalid = false;
3533 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3534 if (Invalid)
3535 return ExprError();
3536
3537 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3538 PP, Tok.getKind());
3539 if (Literal.hadError())
3540 return ExprError();
3541
3542 QualType Ty;
3543 if (Literal.isWide())
3544 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3545 else if (Literal.isUTF8() && getLangOpts().Char8)
3546 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3547 else if (Literal.isUTF16())
3548 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3549 else if (Literal.isUTF32())
3550 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3551 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3552 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3553 else
3554 Ty = Context.CharTy; // 'x' -> char in C++
3555
3556 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3557 if (Literal.isWide())
3558 Kind = CharacterLiteral::Wide;
3559 else if (Literal.isUTF16())
3560 Kind = CharacterLiteral::UTF16;
3561 else if (Literal.isUTF32())
3562 Kind = CharacterLiteral::UTF32;
3563 else if (Literal.isUTF8())
3564 Kind = CharacterLiteral::UTF8;
3565
3566 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3567 Tok.getLocation());
3568
3569 if (Literal.getUDSuffix().empty())
3570 return Lit;
3571
3572 // We're building a user-defined literal.
3573 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3574 SourceLocation UDSuffixLoc =
3575 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3576
3577 // Make sure we're allowed user-defined literals here.
3578 if (!UDLScope)
3579 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3580
3581 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3582 // operator "" X (ch)
3583 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3584 Lit, Tok.getLocation());
3585 }
3586
ActOnIntegerConstant(SourceLocation Loc,uint64_t Val)3587 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3588 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3589 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3590 Context.IntTy, Loc);
3591 }
3592
BuildFloatingLiteral(Sema & S,NumericLiteralParser & Literal,QualType Ty,SourceLocation Loc)3593 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3594 QualType Ty, SourceLocation Loc) {
3595 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3596
3597 using llvm::APFloat;
3598 APFloat Val(Format);
3599
3600 APFloat::opStatus result = Literal.GetFloatValue(Val);
3601
3602 // Overflow is always an error, but underflow is only an error if
3603 // we underflowed to zero (APFloat reports denormals as underflow).
3604 if ((result & APFloat::opOverflow) ||
3605 ((result & APFloat::opUnderflow) && Val.isZero())) {
3606 unsigned diagnostic;
3607 SmallString<20> buffer;
3608 if (result & APFloat::opOverflow) {
3609 diagnostic = diag::warn_float_overflow;
3610 APFloat::getLargest(Format).toString(buffer);
3611 } else {
3612 diagnostic = diag::warn_float_underflow;
3613 APFloat::getSmallest(Format).toString(buffer);
3614 }
3615
3616 S.Diag(Loc, diagnostic)
3617 << Ty
3618 << StringRef(buffer.data(), buffer.size());
3619 }
3620
3621 bool isExact = (result == APFloat::opOK);
3622 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3623 }
3624
CheckLoopHintExpr(Expr * E,SourceLocation Loc)3625 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3626 assert(E && "Invalid expression");
3627
3628 if (E->isValueDependent())
3629 return false;
3630
3631 QualType QT = E->getType();
3632 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3633 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3634 return true;
3635 }
3636
3637 llvm::APSInt ValueAPS;
3638 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3639
3640 if (R.isInvalid())
3641 return true;
3642
3643 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3644 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3645 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3646 << ValueAPS.toString(10) << ValueIsPositive;
3647 return true;
3648 }
3649
3650 return false;
3651 }
3652
ActOnNumericConstant(const Token & Tok,Scope * UDLScope)3653 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3654 // Fast path for a single digit (which is quite common). A single digit
3655 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3656 if (Tok.getLength() == 1) {
3657 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3658 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3659 }
3660
3661 SmallString<128> SpellingBuffer;
3662 // NumericLiteralParser wants to overread by one character. Add padding to
3663 // the buffer in case the token is copied to the buffer. If getSpelling()
3664 // returns a StringRef to the memory buffer, it should have a null char at
3665 // the EOF, so it is also safe.
3666 SpellingBuffer.resize(Tok.getLength() + 1);
3667
3668 // Get the spelling of the token, which eliminates trigraphs, etc.
3669 bool Invalid = false;
3670 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3671 if (Invalid)
3672 return ExprError();
3673
3674 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3675 PP.getSourceManager(), PP.getLangOpts(),
3676 PP.getTargetInfo(), PP.getDiagnostics());
3677 if (Literal.hadError)
3678 return ExprError();
3679
3680 if (Literal.hasUDSuffix()) {
3681 // We're building a user-defined literal.
3682 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3683 SourceLocation UDSuffixLoc =
3684 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3685
3686 // Make sure we're allowed user-defined literals here.
3687 if (!UDLScope)
3688 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3689
3690 QualType CookedTy;
3691 if (Literal.isFloatingLiteral()) {
3692 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3693 // long double, the literal is treated as a call of the form
3694 // operator "" X (f L)
3695 CookedTy = Context.LongDoubleTy;
3696 } else {
3697 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3698 // unsigned long long, the literal is treated as a call of the form
3699 // operator "" X (n ULL)
3700 CookedTy = Context.UnsignedLongLongTy;
3701 }
3702
3703 DeclarationName OpName =
3704 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3705 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3706 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3707
3708 SourceLocation TokLoc = Tok.getLocation();
3709
3710 // Perform literal operator lookup to determine if we're building a raw
3711 // literal or a cooked one.
3712 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3713 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3714 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3715 /*AllowStringTemplatePack*/ false,
3716 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3717 case LOLR_ErrorNoDiagnostic:
3718 // Lookup failure for imaginary constants isn't fatal, there's still the
3719 // GNU extension producing _Complex types.
3720 break;
3721 case LOLR_Error:
3722 return ExprError();
3723 case LOLR_Cooked: {
3724 Expr *Lit;
3725 if (Literal.isFloatingLiteral()) {
3726 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3727 } else {
3728 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3729 if (Literal.GetIntegerValue(ResultVal))
3730 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3731 << /* Unsigned */ 1;
3732 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3733 Tok.getLocation());
3734 }
3735 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3736 }
3737
3738 case LOLR_Raw: {
3739 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3740 // literal is treated as a call of the form
3741 // operator "" X ("n")
3742 unsigned Length = Literal.getUDSuffixOffset();
3743 QualType StrTy = Context.getConstantArrayType(
3744 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3745 llvm::APInt(32, Length + 1), nullptr, ArrayType::Normal, 0);
3746 Expr *Lit = StringLiteral::Create(
3747 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3748 /*Pascal*/false, StrTy, &TokLoc, 1);
3749 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3750 }
3751
3752 case LOLR_Template: {
3753 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3754 // template), L is treated as a call fo the form
3755 // operator "" X <'c1', 'c2', ... 'ck'>()
3756 // where n is the source character sequence c1 c2 ... ck.
3757 TemplateArgumentListInfo ExplicitArgs;
3758 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3759 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3760 llvm::APSInt Value(CharBits, CharIsUnsigned);
3761 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3762 Value = TokSpelling[I];
3763 TemplateArgument Arg(Context, Value, Context.CharTy);
3764 TemplateArgumentLocInfo ArgInfo;
3765 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3766 }
3767 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3768 &ExplicitArgs);
3769 }
3770 case LOLR_StringTemplatePack:
3771 llvm_unreachable("unexpected literal operator lookup result");
3772 }
3773 }
3774
3775 Expr *Res;
3776
3777 if (Literal.isFixedPointLiteral()) {
3778 QualType Ty;
3779
3780 if (Literal.isAccum) {
3781 if (Literal.isHalf) {
3782 Ty = Context.ShortAccumTy;
3783 } else if (Literal.isLong) {
3784 Ty = Context.LongAccumTy;
3785 } else {
3786 Ty = Context.AccumTy;
3787 }
3788 } else if (Literal.isFract) {
3789 if (Literal.isHalf) {
3790 Ty = Context.ShortFractTy;
3791 } else if (Literal.isLong) {
3792 Ty = Context.LongFractTy;
3793 } else {
3794 Ty = Context.FractTy;
3795 }
3796 }
3797
3798 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3799
3800 bool isSigned = !Literal.isUnsigned;
3801 unsigned scale = Context.getFixedPointScale(Ty);
3802 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3803
3804 llvm::APInt Val(bit_width, 0, isSigned);
3805 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3806 bool ValIsZero = Val.isNullValue() && !Overflowed;
3807
3808 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3809 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3810 // Clause 6.4.4 - The value of a constant shall be in the range of
3811 // representable values for its type, with exception for constants of a
3812 // fract type with a value of exactly 1; such a constant shall denote
3813 // the maximal value for the type.
3814 --Val;
3815 else if (Val.ugt(MaxVal) || Overflowed)
3816 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3817
3818 Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3819 Tok.getLocation(), scale);
3820 } else if (Literal.isFloatingLiteral()) {
3821 QualType Ty;
3822 if (Literal.isHalf){
3823 if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3824 Ty = Context.HalfTy;
3825 else {
3826 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3827 return ExprError();
3828 }
3829 } else if (Literal.isFloat)
3830 Ty = Context.FloatTy;
3831 else if (Literal.isLong)
3832 Ty = Context.LongDoubleTy;
3833 else if (Literal.isFloat16)
3834 Ty = Context.Float16Ty;
3835 else if (Literal.isFloat128)
3836 Ty = Context.Float128Ty;
3837 else
3838 Ty = Context.DoubleTy;
3839
3840 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3841
3842 if (Ty == Context.DoubleTy) {
3843 if (getLangOpts().SinglePrecisionConstants) {
3844 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3845 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3846 }
3847 } else if (getLangOpts().OpenCL &&
3848 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3849 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3850 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3851 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3852 }
3853 }
3854 } else if (!Literal.isIntegerLiteral()) {
3855 return ExprError();
3856 } else {
3857 QualType Ty;
3858
3859 // 'long long' is a C99 or C++11 feature.
3860 if (!getLangOpts().C99 && Literal.isLongLong) {
3861 if (getLangOpts().CPlusPlus)
3862 Diag(Tok.getLocation(),
3863 getLangOpts().CPlusPlus11 ?
3864 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3865 else
3866 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3867 }
3868
3869 // Get the value in the widest-possible width.
3870 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3871 llvm::APInt ResultVal(MaxWidth, 0);
3872
3873 if (Literal.GetIntegerValue(ResultVal)) {
3874 // If this value didn't fit into uintmax_t, error and force to ull.
3875 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3876 << /* Unsigned */ 1;
3877 Ty = Context.UnsignedLongLongTy;
3878 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3879 "long long is not intmax_t?");
3880 } else {
3881 // If this value fits into a ULL, try to figure out what else it fits into
3882 // according to the rules of C99 6.4.4.1p5.
3883
3884 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3885 // be an unsigned int.
3886 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3887
3888 // Check from smallest to largest, picking the smallest type we can.
3889 unsigned Width = 0;
3890
3891 // Microsoft specific integer suffixes are explicitly sized.
3892 if (Literal.MicrosoftInteger) {
3893 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3894 Width = 8;
3895 Ty = Context.CharTy;
3896 } else {
3897 Width = Literal.MicrosoftInteger;
3898 Ty = Context.getIntTypeForBitwidth(Width,
3899 /*Signed=*/!Literal.isUnsigned);
3900 }
3901 }
3902
3903 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3904 // Are int/unsigned possibilities?
3905 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3906
3907 // Does it fit in a unsigned int?
3908 if (ResultVal.isIntN(IntSize)) {
3909 // Does it fit in a signed int?
3910 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3911 Ty = Context.IntTy;
3912 else if (AllowUnsigned)
3913 Ty = Context.UnsignedIntTy;
3914 Width = IntSize;
3915 }
3916 }
3917
3918 // Are long/unsigned long possibilities?
3919 if (Ty.isNull() && !Literal.isLongLong) {
3920 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3921
3922 // Does it fit in a unsigned long?
3923 if (ResultVal.isIntN(LongSize)) {
3924 // Does it fit in a signed long?
3925 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3926 Ty = Context.LongTy;
3927 else if (AllowUnsigned)
3928 Ty = Context.UnsignedLongTy;
3929 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3930 // is compatible.
3931 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3932 const unsigned LongLongSize =
3933 Context.getTargetInfo().getLongLongWidth();
3934 Diag(Tok.getLocation(),
3935 getLangOpts().CPlusPlus
3936 ? Literal.isLong
3937 ? diag::warn_old_implicitly_unsigned_long_cxx
3938 : /*C++98 UB*/ diag::
3939 ext_old_implicitly_unsigned_long_cxx
3940 : diag::warn_old_implicitly_unsigned_long)
3941 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3942 : /*will be ill-formed*/ 1);
3943 Ty = Context.UnsignedLongTy;
3944 }
3945 Width = LongSize;
3946 }
3947 }
3948
3949 // Check long long if needed.
3950 if (Ty.isNull()) {
3951 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3952
3953 // Does it fit in a unsigned long long?
3954 if (ResultVal.isIntN(LongLongSize)) {
3955 // Does it fit in a signed long long?
3956 // To be compatible with MSVC, hex integer literals ending with the
3957 // LL or i64 suffix are always signed in Microsoft mode.
3958 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3959 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3960 Ty = Context.LongLongTy;
3961 else if (AllowUnsigned)
3962 Ty = Context.UnsignedLongLongTy;
3963 Width = LongLongSize;
3964 }
3965 }
3966
3967 // If we still couldn't decide a type, we probably have something that
3968 // does not fit in a signed long long, but has no U suffix.
3969 if (Ty.isNull()) {
3970 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3971 Ty = Context.UnsignedLongLongTy;
3972 Width = Context.getTargetInfo().getLongLongWidth();
3973 }
3974
3975 if (ResultVal.getBitWidth() != Width)
3976 ResultVal = ResultVal.trunc(Width);
3977 }
3978 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3979 }
3980
3981 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3982 if (Literal.isImaginary) {
3983 Res = new (Context) ImaginaryLiteral(Res,
3984 Context.getComplexType(Res->getType()));
3985
3986 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3987 }
3988 return Res;
3989 }
3990
ActOnParenExpr(SourceLocation L,SourceLocation R,Expr * E)3991 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3992 assert(E && "ActOnParenExpr() missing expr");
3993 return new (Context) ParenExpr(L, R, E);
3994 }
3995
CheckVecStepTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange)3996 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3997 SourceLocation Loc,
3998 SourceRange ArgRange) {
3999 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4000 // scalar or vector data type argument..."
4001 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4002 // type (C99 6.2.5p18) or void.
4003 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4004 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4005 << T << ArgRange;
4006 return true;
4007 }
4008
4009 assert((T->isVoidType() || !T->isIncompleteType()) &&
4010 "Scalar types should always be complete");
4011 return false;
4012 }
4013
CheckExtensionTraitOperandType(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)4014 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
4015 SourceLocation Loc,
4016 SourceRange ArgRange,
4017 UnaryExprOrTypeTrait TraitKind) {
4018 // Invalid types must be hard errors for SFINAE in C++.
4019 if (S.LangOpts.CPlusPlus)
4020 return true;
4021
4022 // C99 6.5.3.4p1:
4023 if (T->isFunctionType() &&
4024 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4025 TraitKind == UETT_PreferredAlignOf)) {
4026 // sizeof(function)/alignof(function) is allowed as an extension.
4027 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4028 << getTraitSpelling(TraitKind) << ArgRange;
4029 return false;
4030 }
4031
4032 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4033 // this is an error (OpenCL v1.1 s6.3.k)
4034 if (T->isVoidType()) {
4035 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4036 : diag::ext_sizeof_alignof_void_type;
4037 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4038 return false;
4039 }
4040
4041 return true;
4042 }
4043
CheckObjCTraitOperandConstraints(Sema & S,QualType T,SourceLocation Loc,SourceRange ArgRange,UnaryExprOrTypeTrait TraitKind)4044 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
4045 SourceLocation Loc,
4046 SourceRange ArgRange,
4047 UnaryExprOrTypeTrait TraitKind) {
4048 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4049 // runtime doesn't allow it.
4050 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4051 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4052 << T << (TraitKind == UETT_SizeOf)
4053 << ArgRange;
4054 return true;
4055 }
4056
4057 return false;
4058 }
4059
4060 /// Check whether E is a pointer from a decayed array type (the decayed
4061 /// pointer type is equal to T) and emit a warning if it is.
warnOnSizeofOnArrayDecay(Sema & S,SourceLocation Loc,QualType T,Expr * E)4062 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
4063 Expr *E) {
4064 // Don't warn if the operation changed the type.
4065 if (T != E->getType())
4066 return;
4067
4068 // Now look for array decays.
4069 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
4070 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4071 return;
4072
4073 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4074 << ICE->getType()
4075 << ICE->getSubExpr()->getType();
4076 }
4077
4078 /// Check the constraints on expression operands to unary type expression
4079 /// and type traits.
4080 ///
4081 /// Completes any types necessary and validates the constraints on the operand
4082 /// expression. The logic mostly mirrors the type-based overload, but may modify
4083 /// the expression as it completes the type for that expression through template
4084 /// instantiation, etc.
CheckUnaryExprOrTypeTraitOperand(Expr * E,UnaryExprOrTypeTrait ExprKind)4085 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
4086 UnaryExprOrTypeTrait ExprKind) {
4087 QualType ExprTy = E->getType();
4088 assert(!ExprTy->isReferenceType());
4089
4090 bool IsUnevaluatedOperand =
4091 (ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
4092 ExprKind == UETT_PreferredAlignOf);
4093 if (IsUnevaluatedOperand) {
4094 ExprResult Result = CheckUnevaluatedOperand(E);
4095 if (Result.isInvalid())
4096 return true;
4097 E = Result.get();
4098 }
4099
4100 if (ExprKind == UETT_VecStep)
4101 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4102 E->getSourceRange());
4103
4104 // Explicitly list some types as extensions.
4105 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4106 E->getSourceRange(), ExprKind))
4107 return false;
4108
4109 // 'alignof' applied to an expression only requires the base element type of
4110 // the expression to be complete. 'sizeof' requires the expression's type to
4111 // be complete (and will attempt to complete it if it's an array of unknown
4112 // bound).
4113 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4114 if (RequireCompleteSizedType(
4115 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4116 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4117 getTraitSpelling(ExprKind), E->getSourceRange()))
4118 return true;
4119 } else {
4120 if (RequireCompleteSizedExprType(
4121 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4122 getTraitSpelling(ExprKind), E->getSourceRange()))
4123 return true;
4124 }
4125
4126 // Completing the expression's type may have changed it.
4127 ExprTy = E->getType();
4128 assert(!ExprTy->isReferenceType());
4129
4130 if (ExprTy->isFunctionType()) {
4131 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4132 << getTraitSpelling(ExprKind) << E->getSourceRange();
4133 return true;
4134 }
4135
4136 // The operand for sizeof and alignof is in an unevaluated expression context,
4137 // so side effects could result in unintended consequences.
4138 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4139 E->HasSideEffects(Context, false))
4140 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4141
4142 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4143 E->getSourceRange(), ExprKind))
4144 return true;
4145
4146 if (ExprKind == UETT_SizeOf) {
4147 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4148 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4149 QualType OType = PVD->getOriginalType();
4150 QualType Type = PVD->getType();
4151 if (Type->isPointerType() && OType->isArrayType()) {
4152 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4153 << Type << OType;
4154 Diag(PVD->getLocation(), diag::note_declared_at);
4155 }
4156 }
4157 }
4158
4159 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4160 // decays into a pointer and returns an unintended result. This is most
4161 // likely a typo for "sizeof(array) op x".
4162 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4163 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4164 BO->getLHS());
4165 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4166 BO->getRHS());
4167 }
4168 }
4169
4170 return false;
4171 }
4172
4173 /// Check the constraints on operands to unary expression and type
4174 /// traits.
4175 ///
4176 /// This will complete any types necessary, and validate the various constraints
4177 /// on those operands.
4178 ///
4179 /// The UsualUnaryConversions() function is *not* called by this routine.
4180 /// C99 6.3.2.1p[2-4] all state:
4181 /// Except when it is the operand of the sizeof operator ...
4182 ///
4183 /// C++ [expr.sizeof]p4
4184 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4185 /// standard conversions are not applied to the operand of sizeof.
4186 ///
4187 /// This policy is followed for all of the unary trait expressions.
CheckUnaryExprOrTypeTraitOperand(QualType ExprType,SourceLocation OpLoc,SourceRange ExprRange,UnaryExprOrTypeTrait ExprKind)4188 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
4189 SourceLocation OpLoc,
4190 SourceRange ExprRange,
4191 UnaryExprOrTypeTrait ExprKind) {
4192 if (ExprType->isDependentType())
4193 return false;
4194
4195 // C++ [expr.sizeof]p2:
4196 // When applied to a reference or a reference type, the result
4197 // is the size of the referenced type.
4198 // C++11 [expr.alignof]p3:
4199 // When alignof is applied to a reference type, the result
4200 // shall be the alignment of the referenced type.
4201 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4202 ExprType = Ref->getPointeeType();
4203
4204 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4205 // When alignof or _Alignof is applied to an array type, the result
4206 // is the alignment of the element type.
4207 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4208 ExprKind == UETT_OpenMPRequiredSimdAlign)
4209 ExprType = Context.getBaseElementType(ExprType);
4210
4211 if (ExprKind == UETT_VecStep)
4212 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4213
4214 // Explicitly list some types as extensions.
4215 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4216 ExprKind))
4217 return false;
4218
4219 if (RequireCompleteSizedType(
4220 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4221 getTraitSpelling(ExprKind), ExprRange))
4222 return true;
4223
4224 if (ExprType->isFunctionType()) {
4225 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
4226 << getTraitSpelling(ExprKind) << ExprRange;
4227 return true;
4228 }
4229
4230 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4231 ExprKind))
4232 return true;
4233
4234 return false;
4235 }
4236
CheckAlignOfExpr(Sema & S,Expr * E,UnaryExprOrTypeTrait ExprKind)4237 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4238 // Cannot know anything else if the expression is dependent.
4239 if (E->isTypeDependent())
4240 return false;
4241
4242 if (E->getObjectKind() == OK_BitField) {
4243 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4244 << 1 << E->getSourceRange();
4245 return true;
4246 }
4247
4248 ValueDecl *D = nullptr;
4249 Expr *Inner = E->IgnoreParens();
4250 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4251 D = DRE->getDecl();
4252 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4253 D = ME->getMemberDecl();
4254 }
4255
4256 // If it's a field, require the containing struct to have a
4257 // complete definition so that we can compute the layout.
4258 //
4259 // This can happen in C++11 onwards, either by naming the member
4260 // in a way that is not transformed into a member access expression
4261 // (in an unevaluated operand, for instance), or by naming the member
4262 // in a trailing-return-type.
4263 //
4264 // For the record, since __alignof__ on expressions is a GCC
4265 // extension, GCC seems to permit this but always gives the
4266 // nonsensical answer 0.
4267 //
4268 // We don't really need the layout here --- we could instead just
4269 // directly check for all the appropriate alignment-lowing
4270 // attributes --- but that would require duplicating a lot of
4271 // logic that just isn't worth duplicating for such a marginal
4272 // use-case.
4273 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4274 // Fast path this check, since we at least know the record has a
4275 // definition if we can find a member of it.
4276 if (!FD->getParent()->isCompleteDefinition()) {
4277 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4278 << E->getSourceRange();
4279 return true;
4280 }
4281
4282 // Otherwise, if it's a field, and the field doesn't have
4283 // reference type, then it must have a complete type (or be a
4284 // flexible array member, which we explicitly want to
4285 // white-list anyway), which makes the following checks trivial.
4286 if (!FD->getType()->isReferenceType())
4287 return false;
4288 }
4289
4290 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4291 }
4292
CheckVecStepExpr(Expr * E)4293 bool Sema::CheckVecStepExpr(Expr *E) {
4294 E = E->IgnoreParens();
4295
4296 // Cannot know anything else if the expression is dependent.
4297 if (E->isTypeDependent())
4298 return false;
4299
4300 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4301 }
4302
captureVariablyModifiedType(ASTContext & Context,QualType T,CapturingScopeInfo * CSI)4303 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4304 CapturingScopeInfo *CSI) {
4305 assert(T->isVariablyModifiedType());
4306 assert(CSI != nullptr);
4307
4308 // We're going to walk down into the type and look for VLA expressions.
4309 do {
4310 const Type *Ty = T.getTypePtr();
4311 switch (Ty->getTypeClass()) {
4312 #define TYPE(Class, Base)
4313 #define ABSTRACT_TYPE(Class, Base)
4314 #define NON_CANONICAL_TYPE(Class, Base)
4315 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4316 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4317 #include "clang/AST/TypeNodes.inc"
4318 T = QualType();
4319 break;
4320 // These types are never variably-modified.
4321 case Type::Builtin:
4322 case Type::Complex:
4323 case Type::Vector:
4324 case Type::ExtVector:
4325 case Type::ConstantMatrix:
4326 case Type::Record:
4327 case Type::Enum:
4328 case Type::Elaborated:
4329 case Type::TemplateSpecialization:
4330 case Type::ObjCObject:
4331 case Type::ObjCInterface:
4332 case Type::ObjCObjectPointer:
4333 case Type::ObjCTypeParam:
4334 case Type::Pipe:
4335 case Type::ExtInt:
4336 llvm_unreachable("type class is never variably-modified!");
4337 case Type::Adjusted:
4338 T = cast<AdjustedType>(Ty)->getOriginalType();
4339 break;
4340 case Type::Decayed:
4341 T = cast<DecayedType>(Ty)->getPointeeType();
4342 break;
4343 case Type::Pointer:
4344 T = cast<PointerType>(Ty)->getPointeeType();
4345 break;
4346 case Type::BlockPointer:
4347 T = cast<BlockPointerType>(Ty)->getPointeeType();
4348 break;
4349 case Type::LValueReference:
4350 case Type::RValueReference:
4351 T = cast<ReferenceType>(Ty)->getPointeeType();
4352 break;
4353 case Type::MemberPointer:
4354 T = cast<MemberPointerType>(Ty)->getPointeeType();
4355 break;
4356 case Type::ConstantArray:
4357 case Type::IncompleteArray:
4358 // Losing element qualification here is fine.
4359 T = cast<ArrayType>(Ty)->getElementType();
4360 break;
4361 case Type::VariableArray: {
4362 // Losing element qualification here is fine.
4363 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4364
4365 // Unknown size indication requires no size computation.
4366 // Otherwise, evaluate and record it.
4367 auto Size = VAT->getSizeExpr();
4368 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4369 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4370 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4371
4372 T = VAT->getElementType();
4373 break;
4374 }
4375 case Type::FunctionProto:
4376 case Type::FunctionNoProto:
4377 T = cast<FunctionType>(Ty)->getReturnType();
4378 break;
4379 case Type::Paren:
4380 case Type::TypeOf:
4381 case Type::UnaryTransform:
4382 case Type::Attributed:
4383 case Type::SubstTemplateTypeParm:
4384 case Type::MacroQualified:
4385 // Keep walking after single level desugaring.
4386 T = T.getSingleStepDesugaredType(Context);
4387 break;
4388 case Type::Typedef:
4389 T = cast<TypedefType>(Ty)->desugar();
4390 break;
4391 case Type::Decltype:
4392 T = cast<DecltypeType>(Ty)->desugar();
4393 break;
4394 case Type::Auto:
4395 case Type::DeducedTemplateSpecialization:
4396 T = cast<DeducedType>(Ty)->getDeducedType();
4397 break;
4398 case Type::TypeOfExpr:
4399 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4400 break;
4401 case Type::Atomic:
4402 T = cast<AtomicType>(Ty)->getValueType();
4403 break;
4404 }
4405 } while (!T.isNull() && T->isVariablyModifiedType());
4406 }
4407
4408 /// Build a sizeof or alignof expression given a type operand.
4409 ExprResult
CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo * TInfo,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,SourceRange R)4410 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4411 SourceLocation OpLoc,
4412 UnaryExprOrTypeTrait ExprKind,
4413 SourceRange R) {
4414 if (!TInfo)
4415 return ExprError();
4416
4417 QualType T = TInfo->getType();
4418
4419 if (!T->isDependentType() &&
4420 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4421 return ExprError();
4422
4423 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4424 if (auto *TT = T->getAs<TypedefType>()) {
4425 for (auto I = FunctionScopes.rbegin(),
4426 E = std::prev(FunctionScopes.rend());
4427 I != E; ++I) {
4428 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4429 if (CSI == nullptr)
4430 break;
4431 DeclContext *DC = nullptr;
4432 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4433 DC = LSI->CallOperator;
4434 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4435 DC = CRSI->TheCapturedDecl;
4436 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4437 DC = BSI->TheDecl;
4438 if (DC) {
4439 if (DC->containsDecl(TT->getDecl()))
4440 break;
4441 captureVariablyModifiedType(Context, T, CSI);
4442 }
4443 }
4444 }
4445 }
4446
4447 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4448 return new (Context) UnaryExprOrTypeTraitExpr(
4449 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4450 }
4451
4452 /// Build a sizeof or alignof expression given an expression
4453 /// operand.
4454 ExprResult
CreateUnaryExprOrTypeTraitExpr(Expr * E,SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind)4455 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4456 UnaryExprOrTypeTrait ExprKind) {
4457 ExprResult PE = CheckPlaceholderExpr(E);
4458 if (PE.isInvalid())
4459 return ExprError();
4460
4461 E = PE.get();
4462
4463 // Verify that the operand is valid.
4464 bool isInvalid = false;
4465 if (E->isTypeDependent()) {
4466 // Delay type-checking for type-dependent expressions.
4467 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4468 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4469 } else if (ExprKind == UETT_VecStep) {
4470 isInvalid = CheckVecStepExpr(E);
4471 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4472 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4473 isInvalid = true;
4474 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4475 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4476 isInvalid = true;
4477 } else {
4478 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4479 }
4480
4481 if (isInvalid)
4482 return ExprError();
4483
4484 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4485 PE = TransformToPotentiallyEvaluated(E);
4486 if (PE.isInvalid()) return ExprError();
4487 E = PE.get();
4488 }
4489
4490 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4491 return new (Context) UnaryExprOrTypeTraitExpr(
4492 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4493 }
4494
4495 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4496 /// expr and the same for @c alignof and @c __alignof
4497 /// Note that the ArgRange is invalid if isType is false.
4498 ExprResult
ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,UnaryExprOrTypeTrait ExprKind,bool IsType,void * TyOrEx,SourceRange ArgRange)4499 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4500 UnaryExprOrTypeTrait ExprKind, bool IsType,
4501 void *TyOrEx, SourceRange ArgRange) {
4502 // If error parsing type, ignore.
4503 if (!TyOrEx) return ExprError();
4504
4505 if (IsType) {
4506 TypeSourceInfo *TInfo;
4507 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4508 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4509 }
4510
4511 Expr *ArgEx = (Expr *)TyOrEx;
4512 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4513 return Result;
4514 }
4515
CheckRealImagOperand(Sema & S,ExprResult & V,SourceLocation Loc,bool IsReal)4516 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4517 bool IsReal) {
4518 if (V.get()->isTypeDependent())
4519 return S.Context.DependentTy;
4520
4521 // _Real and _Imag are only l-values for normal l-values.
4522 if (V.get()->getObjectKind() != OK_Ordinary) {
4523 V = S.DefaultLvalueConversion(V.get());
4524 if (V.isInvalid())
4525 return QualType();
4526 }
4527
4528 // These operators return the element type of a complex type.
4529 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4530 return CT->getElementType();
4531
4532 // Otherwise they pass through real integer and floating point types here.
4533 if (V.get()->getType()->isArithmeticType())
4534 return V.get()->getType();
4535
4536 // Test for placeholders.
4537 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4538 if (PR.isInvalid()) return QualType();
4539 if (PR.get() != V.get()) {
4540 V = PR;
4541 return CheckRealImagOperand(S, V, Loc, IsReal);
4542 }
4543
4544 // Reject anything else.
4545 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4546 << (IsReal ? "__real" : "__imag");
4547 return QualType();
4548 }
4549
4550
4551
4552 ExprResult
ActOnPostfixUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Kind,Expr * Input)4553 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4554 tok::TokenKind Kind, Expr *Input) {
4555 UnaryOperatorKind Opc;
4556 switch (Kind) {
4557 default: llvm_unreachable("Unknown unary op!");
4558 case tok::plusplus: Opc = UO_PostInc; break;
4559 case tok::minusminus: Opc = UO_PostDec; break;
4560 }
4561
4562 // Since this might is a postfix expression, get rid of ParenListExprs.
4563 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4564 if (Result.isInvalid()) return ExprError();
4565 Input = Result.get();
4566
4567 return BuildUnaryOp(S, OpLoc, Opc, Input);
4568 }
4569
4570 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4571 ///
4572 /// \return true on error
checkArithmeticOnObjCPointer(Sema & S,SourceLocation opLoc,Expr * op)4573 static bool checkArithmeticOnObjCPointer(Sema &S,
4574 SourceLocation opLoc,
4575 Expr *op) {
4576 assert(op->getType()->isObjCObjectPointerType());
4577 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4578 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4579 return false;
4580
4581 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4582 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4583 << op->getSourceRange();
4584 return true;
4585 }
4586
isMSPropertySubscriptExpr(Sema & S,Expr * Base)4587 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4588 auto *BaseNoParens = Base->IgnoreParens();
4589 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4590 return MSProp->getPropertyDecl()->getType()->isArrayType();
4591 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4592 }
4593
4594 ExprResult
ActOnArraySubscriptExpr(Scope * S,Expr * base,SourceLocation lbLoc,Expr * idx,SourceLocation rbLoc)4595 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4596 Expr *idx, SourceLocation rbLoc) {
4597 if (base && !base->getType().isNull() &&
4598 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4599 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4600 SourceLocation(), /*Length*/ nullptr,
4601 /*Stride=*/nullptr, rbLoc);
4602
4603 // Since this might be a postfix expression, get rid of ParenListExprs.
4604 if (isa<ParenListExpr>(base)) {
4605 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4606 if (result.isInvalid()) return ExprError();
4607 base = result.get();
4608 }
4609
4610 // Check if base and idx form a MatrixSubscriptExpr.
4611 //
4612 // Helper to check for comma expressions, which are not allowed as indices for
4613 // matrix subscript expressions.
4614 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4615 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4616 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4617 << SourceRange(base->getBeginLoc(), rbLoc);
4618 return true;
4619 }
4620 return false;
4621 };
4622 // The matrix subscript operator ([][])is considered a single operator.
4623 // Separating the index expressions by parenthesis is not allowed.
4624 if (base->getType()->isSpecificPlaceholderType(
4625 BuiltinType::IncompleteMatrixIdx) &&
4626 !isa<MatrixSubscriptExpr>(base)) {
4627 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4628 << SourceRange(base->getBeginLoc(), rbLoc);
4629 return ExprError();
4630 }
4631 // If the base is a MatrixSubscriptExpr, try to create a new
4632 // MatrixSubscriptExpr.
4633 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4634 if (matSubscriptE) {
4635 if (CheckAndReportCommaError(idx))
4636 return ExprError();
4637
4638 assert(matSubscriptE->isIncomplete() &&
4639 "base has to be an incomplete matrix subscript");
4640 return CreateBuiltinMatrixSubscriptExpr(
4641 matSubscriptE->getBase(), matSubscriptE->getRowIdx(), idx, rbLoc);
4642 }
4643
4644 // Handle any non-overload placeholder types in the base and index
4645 // expressions. We can't handle overloads here because the other
4646 // operand might be an overloadable type, in which case the overload
4647 // resolution for the operator overload should get the first crack
4648 // at the overload.
4649 bool IsMSPropertySubscript = false;
4650 if (base->getType()->isNonOverloadPlaceholderType()) {
4651 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4652 if (!IsMSPropertySubscript) {
4653 ExprResult result = CheckPlaceholderExpr(base);
4654 if (result.isInvalid())
4655 return ExprError();
4656 base = result.get();
4657 }
4658 }
4659
4660 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4661 if (base->getType()->isMatrixType()) {
4662 if (CheckAndReportCommaError(idx))
4663 return ExprError();
4664
4665 return CreateBuiltinMatrixSubscriptExpr(base, idx, nullptr, rbLoc);
4666 }
4667
4668 // A comma-expression as the index is deprecated in C++2a onwards.
4669 if (getLangOpts().CPlusPlus20 &&
4670 ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4671 (isa<CXXOperatorCallExpr>(idx) &&
4672 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma))) {
4673 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4674 << SourceRange(base->getBeginLoc(), rbLoc);
4675 }
4676
4677 if (idx->getType()->isNonOverloadPlaceholderType()) {
4678 ExprResult result = CheckPlaceholderExpr(idx);
4679 if (result.isInvalid()) return ExprError();
4680 idx = result.get();
4681 }
4682
4683 // Build an unanalyzed expression if either operand is type-dependent.
4684 if (getLangOpts().CPlusPlus &&
4685 (base->isTypeDependent() || idx->isTypeDependent())) {
4686 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4687 VK_LValue, OK_Ordinary, rbLoc);
4688 }
4689
4690 // MSDN, property (C++)
4691 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4692 // This attribute can also be used in the declaration of an empty array in a
4693 // class or structure definition. For example:
4694 // __declspec(property(get=GetX, put=PutX)) int x[];
4695 // The above statement indicates that x[] can be used with one or more array
4696 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4697 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4698 if (IsMSPropertySubscript) {
4699 // Build MS property subscript expression if base is MS property reference
4700 // or MS property subscript.
4701 return new (Context) MSPropertySubscriptExpr(
4702 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4703 }
4704
4705 // Use C++ overloaded-operator rules if either operand has record
4706 // type. The spec says to do this if either type is *overloadable*,
4707 // but enum types can't declare subscript operators or conversion
4708 // operators, so there's nothing interesting for overload resolution
4709 // to do if there aren't any record types involved.
4710 //
4711 // ObjC pointers have their own subscripting logic that is not tied
4712 // to overload resolution and so should not take this path.
4713 if (getLangOpts().CPlusPlus &&
4714 (base->getType()->isRecordType() ||
4715 (!base->getType()->isObjCObjectPointerType() &&
4716 idx->getType()->isRecordType()))) {
4717 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4718 }
4719
4720 ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4721
4722 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4723 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4724
4725 return Res;
4726 }
4727
tryConvertExprToType(Expr * E,QualType Ty)4728 ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
4729 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);
4730 InitializationKind Kind =
4731 InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());
4732 InitializationSequence InitSeq(*this, Entity, Kind, E);
4733 return InitSeq.Perform(*this, Entity, Kind, E);
4734 }
4735
CreateBuiltinMatrixSubscriptExpr(Expr * Base,Expr * RowIdx,Expr * ColumnIdx,SourceLocation RBLoc)4736 ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
4737 Expr *ColumnIdx,
4738 SourceLocation RBLoc) {
4739 ExprResult BaseR = CheckPlaceholderExpr(Base);
4740 if (BaseR.isInvalid())
4741 return BaseR;
4742 Base = BaseR.get();
4743
4744 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4745 if (RowR.isInvalid())
4746 return RowR;
4747 RowIdx = RowR.get();
4748
4749 if (!ColumnIdx)
4750 return new (Context) MatrixSubscriptExpr(
4751 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4752
4753 // Build an unanalyzed expression if any of the operands is type-dependent.
4754 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4755 ColumnIdx->isTypeDependent())
4756 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4757 Context.DependentTy, RBLoc);
4758
4759 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4760 if (ColumnR.isInvalid())
4761 return ColumnR;
4762 ColumnIdx = ColumnR.get();
4763
4764 // Check that IndexExpr is an integer expression. If it is a constant
4765 // expression, check that it is less than Dim (= the number of elements in the
4766 // corresponding dimension).
4767 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
4768 bool IsColumnIdx) -> Expr * {
4769 if (!IndexExpr->getType()->isIntegerType() &&
4770 !IndexExpr->isTypeDependent()) {
4771 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
4772 << IsColumnIdx;
4773 return nullptr;
4774 }
4775
4776 if (Optional<llvm::APSInt> Idx =
4777 IndexExpr->getIntegerConstantExpr(Context)) {
4778 if ((*Idx < 0 || *Idx >= Dim)) {
4779 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
4780 << IsColumnIdx << Dim;
4781 return nullptr;
4782 }
4783 }
4784
4785 ExprResult ConvExpr =
4786 tryConvertExprToType(IndexExpr, Context.getSizeType());
4787 assert(!ConvExpr.isInvalid() &&
4788 "should be able to convert any integer type to size type");
4789 return ConvExpr.get();
4790 };
4791
4792 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
4793 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
4794 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
4795 if (!RowIdx || !ColumnIdx)
4796 return ExprError();
4797
4798 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4799 MTy->getElementType(), RBLoc);
4800 }
4801
CheckAddressOfNoDeref(const Expr * E)4802 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4803 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4804 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4805
4806 // For expressions like `&(*s).b`, the base is recorded and what should be
4807 // checked.
4808 const MemberExpr *Member = nullptr;
4809 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4810 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4811
4812 LastRecord.PossibleDerefs.erase(StrippedExpr);
4813 }
4814
CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr * E)4815 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4816 if (isUnevaluatedContext())
4817 return;
4818
4819 QualType ResultTy = E->getType();
4820 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4821
4822 // Bail if the element is an array since it is not memory access.
4823 if (isa<ArrayType>(ResultTy))
4824 return;
4825
4826 if (ResultTy->hasAttr(attr::NoDeref)) {
4827 LastRecord.PossibleDerefs.insert(E);
4828 return;
4829 }
4830
4831 // Check if the base type is a pointer to a member access of a struct
4832 // marked with noderef.
4833 const Expr *Base = E->getBase();
4834 QualType BaseTy = Base->getType();
4835 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4836 // Not a pointer access
4837 return;
4838
4839 const MemberExpr *Member = nullptr;
4840 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4841 Member->isArrow())
4842 Base = Member->getBase();
4843
4844 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4845 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4846 LastRecord.PossibleDerefs.insert(E);
4847 }
4848 }
4849
ActOnOMPArraySectionExpr(Expr * Base,SourceLocation LBLoc,Expr * LowerBound,SourceLocation ColonLocFirst,SourceLocation ColonLocSecond,Expr * Length,Expr * Stride,SourceLocation RBLoc)4850 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4851 Expr *LowerBound,
4852 SourceLocation ColonLocFirst,
4853 SourceLocation ColonLocSecond,
4854 Expr *Length, Expr *Stride,
4855 SourceLocation RBLoc) {
4856 if (Base->getType()->isPlaceholderType() &&
4857 !Base->getType()->isSpecificPlaceholderType(
4858 BuiltinType::OMPArraySection)) {
4859 ExprResult Result = CheckPlaceholderExpr(Base);
4860 if (Result.isInvalid())
4861 return ExprError();
4862 Base = Result.get();
4863 }
4864 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4865 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4866 if (Result.isInvalid())
4867 return ExprError();
4868 Result = DefaultLvalueConversion(Result.get());
4869 if (Result.isInvalid())
4870 return ExprError();
4871 LowerBound = Result.get();
4872 }
4873 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4874 ExprResult Result = CheckPlaceholderExpr(Length);
4875 if (Result.isInvalid())
4876 return ExprError();
4877 Result = DefaultLvalueConversion(Result.get());
4878 if (Result.isInvalid())
4879 return ExprError();
4880 Length = Result.get();
4881 }
4882 if (Stride && Stride->getType()->isNonOverloadPlaceholderType()) {
4883 ExprResult Result = CheckPlaceholderExpr(Stride);
4884 if (Result.isInvalid())
4885 return ExprError();
4886 Result = DefaultLvalueConversion(Result.get());
4887 if (Result.isInvalid())
4888 return ExprError();
4889 Stride = Result.get();
4890 }
4891
4892 // Build an unanalyzed expression if either operand is type-dependent.
4893 if (Base->isTypeDependent() ||
4894 (LowerBound &&
4895 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4896 (Length && (Length->isTypeDependent() || Length->isValueDependent())) ||
4897 (Stride && (Stride->isTypeDependent() || Stride->isValueDependent()))) {
4898 return new (Context) OMPArraySectionExpr(
4899 Base, LowerBound, Length, Stride, Context.DependentTy, VK_LValue,
4900 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
4901 }
4902
4903 // Perform default conversions.
4904 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4905 QualType ResultTy;
4906 if (OriginalTy->isAnyPointerType()) {
4907 ResultTy = OriginalTy->getPointeeType();
4908 } else if (OriginalTy->isArrayType()) {
4909 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4910 } else {
4911 return ExprError(
4912 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4913 << Base->getSourceRange());
4914 }
4915 // C99 6.5.2.1p1
4916 if (LowerBound) {
4917 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4918 LowerBound);
4919 if (Res.isInvalid())
4920 return ExprError(Diag(LowerBound->getExprLoc(),
4921 diag::err_omp_typecheck_section_not_integer)
4922 << 0 << LowerBound->getSourceRange());
4923 LowerBound = Res.get();
4924
4925 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4926 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4927 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4928 << 0 << LowerBound->getSourceRange();
4929 }
4930 if (Length) {
4931 auto Res =
4932 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4933 if (Res.isInvalid())
4934 return ExprError(Diag(Length->getExprLoc(),
4935 diag::err_omp_typecheck_section_not_integer)
4936 << 1 << Length->getSourceRange());
4937 Length = Res.get();
4938
4939 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4940 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4941 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4942 << 1 << Length->getSourceRange();
4943 }
4944 if (Stride) {
4945 ExprResult Res =
4946 PerformOpenMPImplicitIntegerConversion(Stride->getExprLoc(), Stride);
4947 if (Res.isInvalid())
4948 return ExprError(Diag(Stride->getExprLoc(),
4949 diag::err_omp_typecheck_section_not_integer)
4950 << 1 << Stride->getSourceRange());
4951 Stride = Res.get();
4952
4953 if (Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4954 Stride->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4955 Diag(Stride->getExprLoc(), diag::warn_omp_section_is_char)
4956 << 1 << Stride->getSourceRange();
4957 }
4958
4959 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4960 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4961 // type. Note that functions are not objects, and that (in C99 parlance)
4962 // incomplete types are not object types.
4963 if (ResultTy->isFunctionType()) {
4964 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4965 << ResultTy << Base->getSourceRange();
4966 return ExprError();
4967 }
4968
4969 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4970 diag::err_omp_section_incomplete_type, Base))
4971 return ExprError();
4972
4973 if (LowerBound && !OriginalTy->isAnyPointerType()) {
4974 Expr::EvalResult Result;
4975 if (LowerBound->EvaluateAsInt(Result, Context)) {
4976 // OpenMP 5.0, [2.1.5 Array Sections]
4977 // The array section must be a subset of the original array.
4978 llvm::APSInt LowerBoundValue = Result.Val.getInt();
4979 if (LowerBoundValue.isNegative()) {
4980 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4981 << LowerBound->getSourceRange();
4982 return ExprError();
4983 }
4984 }
4985 }
4986
4987 if (Length) {
4988 Expr::EvalResult Result;
4989 if (Length->EvaluateAsInt(Result, Context)) {
4990 // OpenMP 5.0, [2.1.5 Array Sections]
4991 // The length must evaluate to non-negative integers.
4992 llvm::APSInt LengthValue = Result.Val.getInt();
4993 if (LengthValue.isNegative()) {
4994 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4995 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4996 << Length->getSourceRange();
4997 return ExprError();
4998 }
4999 }
5000 } else if (ColonLocFirst.isValid() &&
5001 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
5002 !OriginalTy->isVariableArrayType()))) {
5003 // OpenMP 5.0, [2.1.5 Array Sections]
5004 // When the size of the array dimension is not known, the length must be
5005 // specified explicitly.
5006 Diag(ColonLocFirst, diag::err_omp_section_length_undefined)
5007 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
5008 return ExprError();
5009 }
5010
5011 if (Stride) {
5012 Expr::EvalResult Result;
5013 if (Stride->EvaluateAsInt(Result, Context)) {
5014 // OpenMP 5.0, [2.1.5 Array Sections]
5015 // The stride must evaluate to a positive integer.
5016 llvm::APSInt StrideValue = Result.Val.getInt();
5017 if (!StrideValue.isStrictlyPositive()) {
5018 Diag(Stride->getExprLoc(), diag::err_omp_section_stride_non_positive)
5019 << StrideValue.toString(/*Radix=*/10, /*Signed=*/true)
5020 << Stride->getSourceRange();
5021 return ExprError();
5022 }
5023 }
5024 }
5025
5026 if (!Base->getType()->isSpecificPlaceholderType(
5027 BuiltinType::OMPArraySection)) {
5028 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
5029 if (Result.isInvalid())
5030 return ExprError();
5031 Base = Result.get();
5032 }
5033 return new (Context) OMPArraySectionExpr(
5034 Base, LowerBound, Length, Stride, Context.OMPArraySectionTy, VK_LValue,
5035 OK_Ordinary, ColonLocFirst, ColonLocSecond, RBLoc);
5036 }
5037
ActOnOMPArrayShapingExpr(Expr * Base,SourceLocation LParenLoc,SourceLocation RParenLoc,ArrayRef<Expr * > Dims,ArrayRef<SourceRange> Brackets)5038 ExprResult Sema::ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5039 SourceLocation RParenLoc,
5040 ArrayRef<Expr *> Dims,
5041 ArrayRef<SourceRange> Brackets) {
5042 if (Base->getType()->isPlaceholderType()) {
5043 ExprResult Result = CheckPlaceholderExpr(Base);
5044 if (Result.isInvalid())
5045 return ExprError();
5046 Result = DefaultLvalueConversion(Result.get());
5047 if (Result.isInvalid())
5048 return ExprError();
5049 Base = Result.get();
5050 }
5051 QualType BaseTy = Base->getType();
5052 // Delay analysis of the types/expressions if instantiation/specialization is
5053 // required.
5054 if (!BaseTy->isPointerType() && Base->isTypeDependent())
5055 return OMPArrayShapingExpr::Create(Context, Context.DependentTy, Base,
5056 LParenLoc, RParenLoc, Dims, Brackets);
5057 if (!BaseTy->isPointerType() ||
5058 (!Base->isTypeDependent() &&
5059 BaseTy->getPointeeType()->isIncompleteType()))
5060 return ExprError(Diag(Base->getExprLoc(),
5061 diag::err_omp_non_pointer_type_array_shaping_base)
5062 << Base->getSourceRange());
5063
5064 SmallVector<Expr *, 4> NewDims;
5065 bool ErrorFound = false;
5066 for (Expr *Dim : Dims) {
5067 if (Dim->getType()->isPlaceholderType()) {
5068 ExprResult Result = CheckPlaceholderExpr(Dim);
5069 if (Result.isInvalid()) {
5070 ErrorFound = true;
5071 continue;
5072 }
5073 Result = DefaultLvalueConversion(Result.get());
5074 if (Result.isInvalid()) {
5075 ErrorFound = true;
5076 continue;
5077 }
5078 Dim = Result.get();
5079 }
5080 if (!Dim->isTypeDependent()) {
5081 ExprResult Result =
5082 PerformOpenMPImplicitIntegerConversion(Dim->getExprLoc(), Dim);
5083 if (Result.isInvalid()) {
5084 ErrorFound = true;
5085 Diag(Dim->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer)
5086 << Dim->getSourceRange();
5087 continue;
5088 }
5089 Dim = Result.get();
5090 Expr::EvalResult EvResult;
5091 if (!Dim->isValueDependent() && Dim->EvaluateAsInt(EvResult, Context)) {
5092 // OpenMP 5.0, [2.1.4 Array Shaping]
5093 // Each si is an integral type expression that must evaluate to a
5094 // positive integer.
5095 llvm::APSInt Value = EvResult.Val.getInt();
5096 if (!Value.isStrictlyPositive()) {
5097 Diag(Dim->getExprLoc(), diag::err_omp_shaping_dimension_not_positive)
5098 << Value.toString(/*Radix=*/10, /*Signed=*/true)
5099 << Dim->getSourceRange();
5100 ErrorFound = true;
5101 continue;
5102 }
5103 }
5104 }
5105 NewDims.push_back(Dim);
5106 }
5107 if (ErrorFound)
5108 return ExprError();
5109 return OMPArrayShapingExpr::Create(Context, Context.OMPArrayShapingTy, Base,
5110 LParenLoc, RParenLoc, NewDims, Brackets);
5111 }
5112
ActOnOMPIteratorExpr(Scope * S,SourceLocation IteratorKwLoc,SourceLocation LLoc,SourceLocation RLoc,ArrayRef<OMPIteratorData> Data)5113 ExprResult Sema::ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5114 SourceLocation LLoc, SourceLocation RLoc,
5115 ArrayRef<OMPIteratorData> Data) {
5116 SmallVector<OMPIteratorExpr::IteratorDefinition, 4> ID;
5117 bool IsCorrect = true;
5118 for (const OMPIteratorData &D : Data) {
5119 TypeSourceInfo *TInfo = nullptr;
5120 SourceLocation StartLoc;
5121 QualType DeclTy;
5122 if (!D.Type.getAsOpaquePtr()) {
5123 // OpenMP 5.0, 2.1.6 Iterators
5124 // In an iterator-specifier, if the iterator-type is not specified then
5125 // the type of that iterator is of int type.
5126 DeclTy = Context.IntTy;
5127 StartLoc = D.DeclIdentLoc;
5128 } else {
5129 DeclTy = GetTypeFromParser(D.Type, &TInfo);
5130 StartLoc = TInfo->getTypeLoc().getBeginLoc();
5131 }
5132
5133 bool IsDeclTyDependent = DeclTy->isDependentType() ||
5134 DeclTy->containsUnexpandedParameterPack() ||
5135 DeclTy->isInstantiationDependentType();
5136 if (!IsDeclTyDependent) {
5137 if (!DeclTy->isIntegralType(Context) && !DeclTy->isAnyPointerType()) {
5138 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5139 // The iterator-type must be an integral or pointer type.
5140 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5141 << DeclTy;
5142 IsCorrect = false;
5143 continue;
5144 }
5145 if (DeclTy.isConstant(Context)) {
5146 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5147 // The iterator-type must not be const qualified.
5148 Diag(StartLoc, diag::err_omp_iterator_not_integral_or_pointer)
5149 << DeclTy;
5150 IsCorrect = false;
5151 continue;
5152 }
5153 }
5154
5155 // Iterator declaration.
5156 assert(D.DeclIdent && "Identifier expected.");
5157 // Always try to create iterator declarator to avoid extra error messages
5158 // about unknown declarations use.
5159 auto *VD = VarDecl::Create(Context, CurContext, StartLoc, D.DeclIdentLoc,
5160 D.DeclIdent, DeclTy, TInfo, SC_None);
5161 VD->setImplicit();
5162 if (S) {
5163 // Check for conflicting previous declaration.
5164 DeclarationNameInfo NameInfo(VD->getDeclName(), D.DeclIdentLoc);
5165 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5166 ForVisibleRedeclaration);
5167 Previous.suppressDiagnostics();
5168 LookupName(Previous, S);
5169
5170 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
5171 /*AllowInlineNamespace=*/false);
5172 if (!Previous.empty()) {
5173 NamedDecl *Old = Previous.getRepresentativeDecl();
5174 Diag(D.DeclIdentLoc, diag::err_redefinition) << VD->getDeclName();
5175 Diag(Old->getLocation(), diag::note_previous_definition);
5176 } else {
5177 PushOnScopeChains(VD, S);
5178 }
5179 } else {
5180 CurContext->addDecl(VD);
5181 }
5182 Expr *Begin = D.Range.Begin;
5183 if (!IsDeclTyDependent && Begin && !Begin->isTypeDependent()) {
5184 ExprResult BeginRes =
5185 PerformImplicitConversion(Begin, DeclTy, AA_Converting);
5186 Begin = BeginRes.get();
5187 }
5188 Expr *End = D.Range.End;
5189 if (!IsDeclTyDependent && End && !End->isTypeDependent()) {
5190 ExprResult EndRes = PerformImplicitConversion(End, DeclTy, AA_Converting);
5191 End = EndRes.get();
5192 }
5193 Expr *Step = D.Range.Step;
5194 if (!IsDeclTyDependent && Step && !Step->isTypeDependent()) {
5195 if (!Step->getType()->isIntegralType(Context)) {
5196 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_not_integral)
5197 << Step << Step->getSourceRange();
5198 IsCorrect = false;
5199 continue;
5200 }
5201 Optional<llvm::APSInt> Result = Step->getIntegerConstantExpr(Context);
5202 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5203 // If the step expression of a range-specification equals zero, the
5204 // behavior is unspecified.
5205 if (Result && Result->isNullValue()) {
5206 Diag(Step->getExprLoc(), diag::err_omp_iterator_step_constant_zero)
5207 << Step << Step->getSourceRange();
5208 IsCorrect = false;
5209 continue;
5210 }
5211 }
5212 if (!Begin || !End || !IsCorrect) {
5213 IsCorrect = false;
5214 continue;
5215 }
5216 OMPIteratorExpr::IteratorDefinition &IDElem = ID.emplace_back();
5217 IDElem.IteratorDecl = VD;
5218 IDElem.AssignmentLoc = D.AssignLoc;
5219 IDElem.Range.Begin = Begin;
5220 IDElem.Range.End = End;
5221 IDElem.Range.Step = Step;
5222 IDElem.ColonLoc = D.ColonLoc;
5223 IDElem.SecondColonLoc = D.SecColonLoc;
5224 }
5225 if (!IsCorrect) {
5226 // Invalidate all created iterator declarations if error is found.
5227 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5228 if (Decl *ID = D.IteratorDecl)
5229 ID->setInvalidDecl();
5230 }
5231 return ExprError();
5232 }
5233 SmallVector<OMPIteratorHelperData, 4> Helpers;
5234 if (!CurContext->isDependentContext()) {
5235 // Build number of ityeration for each iteration range.
5236 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5237 // ((Begini-Stepi-1-Endi) / -Stepi);
5238 for (OMPIteratorExpr::IteratorDefinition &D : ID) {
5239 // (Endi - Begini)
5240 ExprResult Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, D.Range.End,
5241 D.Range.Begin);
5242 if(!Res.isUsable()) {
5243 IsCorrect = false;
5244 continue;
5245 }
5246 ExprResult St, St1;
5247 if (D.Range.Step) {
5248 St = D.Range.Step;
5249 // (Endi - Begini) + Stepi
5250 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res.get(), St.get());
5251 if (!Res.isUsable()) {
5252 IsCorrect = false;
5253 continue;
5254 }
5255 // (Endi - Begini) + Stepi - 1
5256 Res =
5257 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res.get(),
5258 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5259 if (!Res.isUsable()) {
5260 IsCorrect = false;
5261 continue;
5262 }
5263 // ((Endi - Begini) + Stepi - 1) / Stepi
5264 Res = CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res.get(), St.get());
5265 if (!Res.isUsable()) {
5266 IsCorrect = false;
5267 continue;
5268 }
5269 St1 = CreateBuiltinUnaryOp(D.AssignmentLoc, UO_Minus, D.Range.Step);
5270 // (Begini - Endi)
5271 ExprResult Res1 = CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub,
5272 D.Range.Begin, D.Range.End);
5273 if (!Res1.isUsable()) {
5274 IsCorrect = false;
5275 continue;
5276 }
5277 // (Begini - Endi) - Stepi
5278 Res1 =
5279 CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, Res1.get(), St1.get());
5280 if (!Res1.isUsable()) {
5281 IsCorrect = false;
5282 continue;
5283 }
5284 // (Begini - Endi) - Stepi - 1
5285 Res1 =
5286 CreateBuiltinBinOp(D.AssignmentLoc, BO_Sub, Res1.get(),
5287 ActOnIntegerConstant(D.AssignmentLoc, 1).get());
5288 if (!Res1.isUsable()) {
5289 IsCorrect = false;
5290 continue;
5291 }
5292 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5293 Res1 =
5294 CreateBuiltinBinOp(D.AssignmentLoc, BO_Div, Res1.get(), St1.get());
5295 if (!Res1.isUsable()) {
5296 IsCorrect = false;
5297 continue;
5298 }
5299 // Stepi > 0.
5300 ExprResult CmpRes =
5301 CreateBuiltinBinOp(D.AssignmentLoc, BO_GT, D.Range.Step,
5302 ActOnIntegerConstant(D.AssignmentLoc, 0).get());
5303 if (!CmpRes.isUsable()) {
5304 IsCorrect = false;
5305 continue;
5306 }
5307 Res = ActOnConditionalOp(D.AssignmentLoc, D.AssignmentLoc, CmpRes.get(),
5308 Res.get(), Res1.get());
5309 if (!Res.isUsable()) {
5310 IsCorrect = false;
5311 continue;
5312 }
5313 }
5314 Res = ActOnFinishFullExpr(Res.get(), /*DiscardedValue=*/false);
5315 if (!Res.isUsable()) {
5316 IsCorrect = false;
5317 continue;
5318 }
5319
5320 // Build counter update.
5321 // Build counter.
5322 auto *CounterVD =
5323 VarDecl::Create(Context, CurContext, D.IteratorDecl->getBeginLoc(),
5324 D.IteratorDecl->getBeginLoc(), nullptr,
5325 Res.get()->getType(), nullptr, SC_None);
5326 CounterVD->setImplicit();
5327 ExprResult RefRes =
5328 BuildDeclRefExpr(CounterVD, CounterVD->getType(), VK_LValue,
5329 D.IteratorDecl->getBeginLoc());
5330 // Build counter update.
5331 // I = Begini + counter * Stepi;
5332 ExprResult UpdateRes;
5333 if (D.Range.Step) {
5334 UpdateRes = CreateBuiltinBinOp(
5335 D.AssignmentLoc, BO_Mul,
5336 DefaultLvalueConversion(RefRes.get()).get(), St.get());
5337 } else {
5338 UpdateRes = DefaultLvalueConversion(RefRes.get());
5339 }
5340 if (!UpdateRes.isUsable()) {
5341 IsCorrect = false;
5342 continue;
5343 }
5344 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Add, D.Range.Begin,
5345 UpdateRes.get());
5346 if (!UpdateRes.isUsable()) {
5347 IsCorrect = false;
5348 continue;
5349 }
5350 ExprResult VDRes =
5351 BuildDeclRefExpr(cast<VarDecl>(D.IteratorDecl),
5352 cast<VarDecl>(D.IteratorDecl)->getType(), VK_LValue,
5353 D.IteratorDecl->getBeginLoc());
5354 UpdateRes = CreateBuiltinBinOp(D.AssignmentLoc, BO_Assign, VDRes.get(),
5355 UpdateRes.get());
5356 if (!UpdateRes.isUsable()) {
5357 IsCorrect = false;
5358 continue;
5359 }
5360 UpdateRes =
5361 ActOnFinishFullExpr(UpdateRes.get(), /*DiscardedValue=*/true);
5362 if (!UpdateRes.isUsable()) {
5363 IsCorrect = false;
5364 continue;
5365 }
5366 ExprResult CounterUpdateRes =
5367 CreateBuiltinUnaryOp(D.AssignmentLoc, UO_PreInc, RefRes.get());
5368 if (!CounterUpdateRes.isUsable()) {
5369 IsCorrect = false;
5370 continue;
5371 }
5372 CounterUpdateRes =
5373 ActOnFinishFullExpr(CounterUpdateRes.get(), /*DiscardedValue=*/true);
5374 if (!CounterUpdateRes.isUsable()) {
5375 IsCorrect = false;
5376 continue;
5377 }
5378 OMPIteratorHelperData &HD = Helpers.emplace_back();
5379 HD.CounterVD = CounterVD;
5380 HD.Upper = Res.get();
5381 HD.Update = UpdateRes.get();
5382 HD.CounterUpdate = CounterUpdateRes.get();
5383 }
5384 } else {
5385 Helpers.assign(ID.size(), {});
5386 }
5387 if (!IsCorrect) {
5388 // Invalidate all created iterator declarations if error is found.
5389 for (const OMPIteratorExpr::IteratorDefinition &D : ID) {
5390 if (Decl *ID = D.IteratorDecl)
5391 ID->setInvalidDecl();
5392 }
5393 return ExprError();
5394 }
5395 return OMPIteratorExpr::Create(Context, Context.OMPIteratorTy, IteratorKwLoc,
5396 LLoc, RLoc, ID, Helpers);
5397 }
5398
5399 ExprResult
CreateBuiltinArraySubscriptExpr(Expr * Base,SourceLocation LLoc,Expr * Idx,SourceLocation RLoc)5400 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5401 Expr *Idx, SourceLocation RLoc) {
5402 Expr *LHSExp = Base;
5403 Expr *RHSExp = Idx;
5404
5405 ExprValueKind VK = VK_LValue;
5406 ExprObjectKind OK = OK_Ordinary;
5407
5408 // Per C++ core issue 1213, the result is an xvalue if either operand is
5409 // a non-lvalue array, and an lvalue otherwise.
5410 if (getLangOpts().CPlusPlus11) {
5411 for (auto *Op : {LHSExp, RHSExp}) {
5412 Op = Op->IgnoreImplicit();
5413 if (Op->getType()->isArrayType() && !Op->isLValue())
5414 VK = VK_XValue;
5415 }
5416 }
5417
5418 // Perform default conversions.
5419 if (!LHSExp->getType()->getAs<VectorType>()) {
5420 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
5421 if (Result.isInvalid())
5422 return ExprError();
5423 LHSExp = Result.get();
5424 }
5425 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
5426 if (Result.isInvalid())
5427 return ExprError();
5428 RHSExp = Result.get();
5429
5430 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5431
5432 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5433 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5434 // in the subscript position. As a result, we need to derive the array base
5435 // and index from the expression types.
5436 Expr *BaseExpr, *IndexExpr;
5437 QualType ResultType;
5438 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5439 BaseExpr = LHSExp;
5440 IndexExpr = RHSExp;
5441 ResultType = Context.DependentTy;
5442 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5443 BaseExpr = LHSExp;
5444 IndexExpr = RHSExp;
5445 ResultType = PTy->getPointeeType();
5446 } else if (const ObjCObjectPointerType *PTy =
5447 LHSTy->getAs<ObjCObjectPointerType>()) {
5448 BaseExpr = LHSExp;
5449 IndexExpr = RHSExp;
5450
5451 // Use custom logic if this should be the pseudo-object subscript
5452 // expression.
5453 if (!LangOpts.isSubscriptPointerArithmetic())
5454 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5455 nullptr);
5456
5457 ResultType = PTy->getPointeeType();
5458 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5459 // Handle the uncommon case of "123[Ptr]".
5460 BaseExpr = RHSExp;
5461 IndexExpr = LHSExp;
5462 ResultType = PTy->getPointeeType();
5463 } else if (const ObjCObjectPointerType *PTy =
5464 RHSTy->getAs<ObjCObjectPointerType>()) {
5465 // Handle the uncommon case of "123[Ptr]".
5466 BaseExpr = RHSExp;
5467 IndexExpr = LHSExp;
5468 ResultType = PTy->getPointeeType();
5469 if (!LangOpts.isSubscriptPointerArithmetic()) {
5470 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5471 << ResultType << BaseExpr->getSourceRange();
5472 return ExprError();
5473 }
5474 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5475 BaseExpr = LHSExp; // vectors: V[123]
5476 IndexExpr = RHSExp;
5477 // We apply C++ DR1213 to vector subscripting too.
5478 if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
5479 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5480 if (Materialized.isInvalid())
5481 return ExprError();
5482 LHSExp = Materialized.get();
5483 }
5484 VK = LHSExp->getValueKind();
5485 if (VK != VK_RValue)
5486 OK = OK_VectorComponent;
5487
5488 ResultType = VTy->getElementType();
5489 QualType BaseType = BaseExpr->getType();
5490 Qualifiers BaseQuals = BaseType.getQualifiers();
5491 Qualifiers MemberQuals = ResultType.getQualifiers();
5492 Qualifiers Combined = BaseQuals + MemberQuals;
5493 if (Combined != MemberQuals)
5494 ResultType = Context.getQualifiedType(ResultType, Combined);
5495 } else if (LHSTy->isArrayType()) {
5496 // If we see an array that wasn't promoted by
5497 // DefaultFunctionArrayLvalueConversion, it must be an array that
5498 // wasn't promoted because of the C90 rule that doesn't
5499 // allow promoting non-lvalue arrays. Warn, then
5500 // force the promotion here.
5501 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5502 << LHSExp->getSourceRange();
5503 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5504 CK_ArrayToPointerDecay).get();
5505 LHSTy = LHSExp->getType();
5506
5507 BaseExpr = LHSExp;
5508 IndexExpr = RHSExp;
5509 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
5510 } else if (RHSTy->isArrayType()) {
5511 // Same as previous, except for 123[f().a] case
5512 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5513 << RHSExp->getSourceRange();
5514 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5515 CK_ArrayToPointerDecay).get();
5516 RHSTy = RHSExp->getType();
5517
5518 BaseExpr = RHSExp;
5519 IndexExpr = LHSExp;
5520 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
5521 } else {
5522 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5523 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5524 }
5525 // C99 6.5.2.1p1
5526 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5527 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5528 << IndexExpr->getSourceRange());
5529
5530 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5531 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
5532 && !IndexExpr->isTypeDependent())
5533 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5534
5535 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5536 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5537 // type. Note that Functions are not objects, and that (in C99 parlance)
5538 // incomplete types are not object types.
5539 if (ResultType->isFunctionType()) {
5540 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5541 << ResultType << BaseExpr->getSourceRange();
5542 return ExprError();
5543 }
5544
5545 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5546 // GNU extension: subscripting on pointer to void
5547 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5548 << BaseExpr->getSourceRange();
5549
5550 // C forbids expressions of unqualified void type from being l-values.
5551 // See IsCForbiddenLValueType.
5552 if (!ResultType.hasQualifiers()) VK = VK_RValue;
5553 } else if (!ResultType->isDependentType() &&
5554 RequireCompleteSizedType(
5555 LLoc, ResultType,
5556 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5557 return ExprError();
5558
5559 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
5560 !ResultType.isCForbiddenLValueType());
5561
5562 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5563 FunctionScopes.size() > 1) {
5564 if (auto *TT =
5565 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5566 for (auto I = FunctionScopes.rbegin(),
5567 E = std::prev(FunctionScopes.rend());
5568 I != E; ++I) {
5569 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5570 if (CSI == nullptr)
5571 break;
5572 DeclContext *DC = nullptr;
5573 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5574 DC = LSI->CallOperator;
5575 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5576 DC = CRSI->TheCapturedDecl;
5577 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5578 DC = BSI->TheDecl;
5579 if (DC) {
5580 if (DC->containsDecl(TT->getDecl()))
5581 break;
5582 captureVariablyModifiedType(
5583 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5584 }
5585 }
5586 }
5587 }
5588
5589 return new (Context)
5590 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5591 }
5592
CheckCXXDefaultArgExpr(SourceLocation CallLoc,FunctionDecl * FD,ParmVarDecl * Param)5593 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5594 ParmVarDecl *Param) {
5595 if (Param->hasUnparsedDefaultArg()) {
5596 // If we've already cleared out the location for the default argument,
5597 // that means we're parsing it right now.
5598 if (!UnparsedDefaultArgLocs.count(Param)) {
5599 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5600 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5601 Param->setInvalidDecl();
5602 return true;
5603 }
5604
5605 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5606 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5607 Diag(UnparsedDefaultArgLocs[Param],
5608 diag::note_default_argument_declared_here);
5609 return true;
5610 }
5611
5612 if (Param->hasUninstantiatedDefaultArg() &&
5613 InstantiateDefaultArgument(CallLoc, FD, Param))
5614 return true;
5615
5616 assert(Param->hasInit() && "default argument but no initializer?");
5617
5618 // If the default expression creates temporaries, we need to
5619 // push them to the current stack of expression temporaries so they'll
5620 // be properly destroyed.
5621 // FIXME: We should really be rebuilding the default argument with new
5622 // bound temporaries; see the comment in PR5810.
5623 // We don't need to do that with block decls, though, because
5624 // blocks in default argument expression can never capture anything.
5625 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
5626 // Set the "needs cleanups" bit regardless of whether there are
5627 // any explicit objects.
5628 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
5629
5630 // Append all the objects to the cleanup list. Right now, this
5631 // should always be a no-op, because blocks in default argument
5632 // expressions should never be able to capture anything.
5633 assert(!Init->getNumObjects() &&
5634 "default argument expression has capturing blocks?");
5635 }
5636
5637 // We already type-checked the argument, so we know it works.
5638 // Just mark all of the declarations in this potentially-evaluated expression
5639 // as being "referenced".
5640 EnterExpressionEvaluationContext EvalContext(
5641 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
5642 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
5643 /*SkipLocalVariables=*/true);
5644 return false;
5645 }
5646
BuildCXXDefaultArgExpr(SourceLocation CallLoc,FunctionDecl * FD,ParmVarDecl * Param)5647 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
5648 FunctionDecl *FD, ParmVarDecl *Param) {
5649 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5650 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
5651 return ExprError();
5652 return CXXDefaultArgExpr::Create(Context, CallLoc, Param, CurContext);
5653 }
5654
5655 Sema::VariadicCallType
getVariadicCallType(FunctionDecl * FDecl,const FunctionProtoType * Proto,Expr * Fn)5656 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5657 Expr *Fn) {
5658 if (Proto && Proto->isVariadic()) {
5659 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
5660 return VariadicConstructor;
5661 else if (Fn && Fn->getType()->isBlockPointerType())
5662 return VariadicBlock;
5663 else if (FDecl) {
5664 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5665 if (Method->isInstance())
5666 return VariadicMethod;
5667 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5668 return VariadicMethod;
5669 return VariadicFunction;
5670 }
5671 return VariadicDoesNotApply;
5672 }
5673
5674 namespace {
5675 class FunctionCallCCC final : public FunctionCallFilterCCC {
5676 public:
FunctionCallCCC(Sema & SemaRef,const IdentifierInfo * FuncName,unsigned NumArgs,MemberExpr * ME)5677 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5678 unsigned NumArgs, MemberExpr *ME)
5679 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5680 FunctionName(FuncName) {}
5681
ValidateCandidate(const TypoCorrection & candidate)5682 bool ValidateCandidate(const TypoCorrection &candidate) override {
5683 if (!candidate.getCorrectionSpecifier() ||
5684 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5685 return false;
5686 }
5687
5688 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5689 }
5690
clone()5691 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5692 return std::make_unique<FunctionCallCCC>(*this);
5693 }
5694
5695 private:
5696 const IdentifierInfo *const FunctionName;
5697 };
5698 }
5699
TryTypoCorrectionForCall(Sema & S,Expr * Fn,FunctionDecl * FDecl,ArrayRef<Expr * > Args)5700 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5701 FunctionDecl *FDecl,
5702 ArrayRef<Expr *> Args) {
5703 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5704 DeclarationName FuncName = FDecl->getDeclName();
5705 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5706
5707 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5708 if (TypoCorrection Corrected = S.CorrectTypo(
5709 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
5710 S.getScopeForContext(S.CurContext), nullptr, CCC,
5711 Sema::CTK_ErrorRecovery)) {
5712 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5713 if (Corrected.isOverloaded()) {
5714 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5715 OverloadCandidateSet::iterator Best;
5716 for (NamedDecl *CD : Corrected) {
5717 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5718 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5719 OCS);
5720 }
5721 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5722 case OR_Success:
5723 ND = Best->FoundDecl;
5724 Corrected.setCorrectionDecl(ND);
5725 break;
5726 default:
5727 break;
5728 }
5729 }
5730 ND = ND->getUnderlyingDecl();
5731 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5732 return Corrected;
5733 }
5734 }
5735 return TypoCorrection();
5736 }
5737
5738 /// ConvertArgumentsForCall - Converts the arguments specified in
5739 /// Args/NumArgs to the parameter types of the function FDecl with
5740 /// function prototype Proto. Call is the call expression itself, and
5741 /// Fn is the function expression. For a C++ member function, this
5742 /// routine does not attempt to convert the object argument. Returns
5743 /// true if the call is ill-formed.
5744 bool
ConvertArgumentsForCall(CallExpr * Call,Expr * Fn,FunctionDecl * FDecl,const FunctionProtoType * Proto,ArrayRef<Expr * > Args,SourceLocation RParenLoc,bool IsExecConfig)5745 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5746 FunctionDecl *FDecl,
5747 const FunctionProtoType *Proto,
5748 ArrayRef<Expr *> Args,
5749 SourceLocation RParenLoc,
5750 bool IsExecConfig) {
5751 // Bail out early if calling a builtin with custom typechecking.
5752 if (FDecl)
5753 if (unsigned ID = FDecl->getBuiltinID())
5754 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5755 return false;
5756
5757 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5758 // assignment, to the types of the corresponding parameter, ...
5759 unsigned NumParams = Proto->getNumParams();
5760 bool Invalid = false;
5761 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5762 unsigned FnKind = Fn->getType()->isBlockPointerType()
5763 ? 1 /* block */
5764 : (IsExecConfig ? 3 /* kernel function (exec config) */
5765 : 0 /* function */);
5766
5767 // If too few arguments are available (and we don't have default
5768 // arguments for the remaining parameters), don't make the call.
5769 if (Args.size() < NumParams) {
5770 if (Args.size() < MinArgs) {
5771 TypoCorrection TC;
5772 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5773 unsigned diag_id =
5774 MinArgs == NumParams && !Proto->isVariadic()
5775 ? diag::err_typecheck_call_too_few_args_suggest
5776 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5777 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5778 << static_cast<unsigned>(Args.size())
5779 << TC.getCorrectionRange());
5780 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5781 Diag(RParenLoc,
5782 MinArgs == NumParams && !Proto->isVariadic()
5783 ? diag::err_typecheck_call_too_few_args_one
5784 : diag::err_typecheck_call_too_few_args_at_least_one)
5785 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5786 else
5787 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5788 ? diag::err_typecheck_call_too_few_args
5789 : diag::err_typecheck_call_too_few_args_at_least)
5790 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5791 << Fn->getSourceRange();
5792
5793 // Emit the location of the prototype.
5794 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5795 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5796
5797 return true;
5798 }
5799 // We reserve space for the default arguments when we create
5800 // the call expression, before calling ConvertArgumentsForCall.
5801 assert((Call->getNumArgs() == NumParams) &&
5802 "We should have reserved space for the default arguments before!");
5803 }
5804
5805 // If too many are passed and not variadic, error on the extras and drop
5806 // them.
5807 if (Args.size() > NumParams) {
5808 if (!Proto->isVariadic()) {
5809 TypoCorrection TC;
5810 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5811 unsigned diag_id =
5812 MinArgs == NumParams && !Proto->isVariadic()
5813 ? diag::err_typecheck_call_too_many_args_suggest
5814 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5815 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5816 << static_cast<unsigned>(Args.size())
5817 << TC.getCorrectionRange());
5818 } else if (NumParams == 1 && FDecl &&
5819 FDecl->getParamDecl(0)->getDeclName())
5820 Diag(Args[NumParams]->getBeginLoc(),
5821 MinArgs == NumParams
5822 ? diag::err_typecheck_call_too_many_args_one
5823 : diag::err_typecheck_call_too_many_args_at_most_one)
5824 << FnKind << FDecl->getParamDecl(0)
5825 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5826 << SourceRange(Args[NumParams]->getBeginLoc(),
5827 Args.back()->getEndLoc());
5828 else
5829 Diag(Args[NumParams]->getBeginLoc(),
5830 MinArgs == NumParams
5831 ? diag::err_typecheck_call_too_many_args
5832 : diag::err_typecheck_call_too_many_args_at_most)
5833 << FnKind << NumParams << static_cast<unsigned>(Args.size())
5834 << Fn->getSourceRange()
5835 << SourceRange(Args[NumParams]->getBeginLoc(),
5836 Args.back()->getEndLoc());
5837
5838 // Emit the location of the prototype.
5839 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5840 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
5841
5842 // This deletes the extra arguments.
5843 Call->shrinkNumArgs(NumParams);
5844 return true;
5845 }
5846 }
5847 SmallVector<Expr *, 8> AllArgs;
5848 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5849
5850 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5851 AllArgs, CallType);
5852 if (Invalid)
5853 return true;
5854 unsigned TotalNumArgs = AllArgs.size();
5855 for (unsigned i = 0; i < TotalNumArgs; ++i)
5856 Call->setArg(i, AllArgs[i]);
5857
5858 return false;
5859 }
5860
GatherArgumentsForCall(SourceLocation CallLoc,FunctionDecl * FDecl,const FunctionProtoType * Proto,unsigned FirstParam,ArrayRef<Expr * > Args,SmallVectorImpl<Expr * > & AllArgs,VariadicCallType CallType,bool AllowExplicit,bool IsListInitialization)5861 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5862 const FunctionProtoType *Proto,
5863 unsigned FirstParam, ArrayRef<Expr *> Args,
5864 SmallVectorImpl<Expr *> &AllArgs,
5865 VariadicCallType CallType, bool AllowExplicit,
5866 bool IsListInitialization) {
5867 unsigned NumParams = Proto->getNumParams();
5868 bool Invalid = false;
5869 size_t ArgIx = 0;
5870 // Continue to check argument types (even if we have too few/many args).
5871 for (unsigned i = FirstParam; i < NumParams; i++) {
5872 QualType ProtoArgType = Proto->getParamType(i);
5873
5874 Expr *Arg;
5875 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5876 if (ArgIx < Args.size()) {
5877 Arg = Args[ArgIx++];
5878
5879 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5880 diag::err_call_incomplete_argument, Arg))
5881 return true;
5882
5883 // Strip the unbridged-cast placeholder expression off, if applicable.
5884 bool CFAudited = false;
5885 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5886 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5887 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5888 Arg = stripARCUnbridgedCast(Arg);
5889 else if (getLangOpts().ObjCAutoRefCount &&
5890 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5891 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5892 CFAudited = true;
5893
5894 if (Proto->getExtParameterInfo(i).isNoEscape())
5895 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5896 BE->getBlockDecl()->setDoesNotEscape();
5897
5898 InitializedEntity Entity =
5899 Param ? InitializedEntity::InitializeParameter(Context, Param,
5900 ProtoArgType)
5901 : InitializedEntity::InitializeParameter(
5902 Context, ProtoArgType, Proto->isParamConsumed(i));
5903
5904 // Remember that parameter belongs to a CF audited API.
5905 if (CFAudited)
5906 Entity.setParameterCFAudited();
5907
5908 ExprResult ArgE = PerformCopyInitialization(
5909 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5910 if (ArgE.isInvalid())
5911 return true;
5912
5913 Arg = ArgE.getAs<Expr>();
5914 } else {
5915 assert(Param && "can't use default arguments without a known callee");
5916
5917 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5918 if (ArgExpr.isInvalid())
5919 return true;
5920
5921 Arg = ArgExpr.getAs<Expr>();
5922 }
5923
5924 // Check for array bounds violations for each argument to the call. This
5925 // check only triggers warnings when the argument isn't a more complex Expr
5926 // with its own checking, such as a BinaryOperator.
5927 CheckArrayAccess(Arg);
5928
5929 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5930 CheckStaticArrayArgument(CallLoc, Param, Arg);
5931
5932 AllArgs.push_back(Arg);
5933 }
5934
5935 // If this is a variadic call, handle args passed through "...".
5936 if (CallType != VariadicDoesNotApply) {
5937 // Assume that extern "C" functions with variadic arguments that
5938 // return __unknown_anytype aren't *really* variadic.
5939 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5940 FDecl->isExternC()) {
5941 for (Expr *A : Args.slice(ArgIx)) {
5942 QualType paramType; // ignored
5943 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5944 Invalid |= arg.isInvalid();
5945 AllArgs.push_back(arg.get());
5946 }
5947
5948 // Otherwise do argument promotion, (C99 6.5.2.2p7).
5949 } else {
5950 for (Expr *A : Args.slice(ArgIx)) {
5951 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5952 Invalid |= Arg.isInvalid();
5953 AllArgs.push_back(Arg.get());
5954 }
5955 }
5956
5957 // Check for array bounds violations.
5958 for (Expr *A : Args.slice(ArgIx))
5959 CheckArrayAccess(A);
5960 }
5961 return Invalid;
5962 }
5963
DiagnoseCalleeStaticArrayParam(Sema & S,ParmVarDecl * PVD)5964 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5965 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5966 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5967 TL = DTL.getOriginalLoc();
5968 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5969 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5970 << ATL.getLocalSourceRange();
5971 }
5972
5973 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5974 /// array parameter, check that it is non-null, and that if it is formed by
5975 /// array-to-pointer decay, the underlying array is sufficiently large.
5976 ///
5977 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5978 /// array type derivation, then for each call to the function, the value of the
5979 /// corresponding actual argument shall provide access to the first element of
5980 /// an array with at least as many elements as specified by the size expression.
5981 void
CheckStaticArrayArgument(SourceLocation CallLoc,ParmVarDecl * Param,const Expr * ArgExpr)5982 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5983 ParmVarDecl *Param,
5984 const Expr *ArgExpr) {
5985 // Static array parameters are not supported in C++.
5986 if (!Param || getLangOpts().CPlusPlus)
5987 return;
5988
5989 QualType OrigTy = Param->getOriginalType();
5990
5991 const ArrayType *AT = Context.getAsArrayType(OrigTy);
5992 if (!AT || AT->getSizeModifier() != ArrayType::Static)
5993 return;
5994
5995 if (ArgExpr->isNullPointerConstant(Context,
5996 Expr::NPC_NeverValueDependent)) {
5997 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5998 DiagnoseCalleeStaticArrayParam(*this, Param);
5999 return;
6000 }
6001
6002 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6003 if (!CAT)
6004 return;
6005
6006 const ConstantArrayType *ArgCAT =
6007 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6008 if (!ArgCAT)
6009 return;
6010
6011 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6012 ArgCAT->getElementType())) {
6013 if (ArgCAT->getSize().ult(CAT->getSize())) {
6014 Diag(CallLoc, diag::warn_static_array_too_small)
6015 << ArgExpr->getSourceRange()
6016 << (unsigned)ArgCAT->getSize().getZExtValue()
6017 << (unsigned)CAT->getSize().getZExtValue() << 0;
6018 DiagnoseCalleeStaticArrayParam(*this, Param);
6019 }
6020 return;
6021 }
6022
6023 Optional<CharUnits> ArgSize =
6024 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6025 Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
6026 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6027 Diag(CallLoc, diag::warn_static_array_too_small)
6028 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6029 << (unsigned)ParmSize->getQuantity() << 1;
6030 DiagnoseCalleeStaticArrayParam(*this, Param);
6031 }
6032 }
6033
6034 /// Given a function expression of unknown-any type, try to rebuild it
6035 /// to have a function type.
6036 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6037
6038 /// Is the given type a placeholder that we need to lower out
6039 /// immediately during argument processing?
isPlaceholderToRemoveAsArg(QualType type)6040 static bool isPlaceholderToRemoveAsArg(QualType type) {
6041 // Placeholders are never sugared.
6042 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6043 if (!placeholder) return false;
6044
6045 switch (placeholder->getKind()) {
6046 // Ignore all the non-placeholder types.
6047 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6048 case BuiltinType::Id:
6049 #include "clang/Basic/OpenCLImageTypes.def"
6050 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6051 case BuiltinType::Id:
6052 #include "clang/Basic/OpenCLExtensionTypes.def"
6053 // In practice we'll never use this, since all SVE types are sugared
6054 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6055 #define SVE_TYPE(Name, Id, SingletonId) \
6056 case BuiltinType::Id:
6057 #include "clang/Basic/AArch64SVEACLETypes.def"
6058 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \
6059 case BuiltinType::Id:
6060 #include "clang/Basic/PPCTypes.def"
6061 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6062 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6063 #include "clang/AST/BuiltinTypes.def"
6064 return false;
6065
6066 // We cannot lower out overload sets; they might validly be resolved
6067 // by the call machinery.
6068 case BuiltinType::Overload:
6069 return false;
6070
6071 // Unbridged casts in ARC can be handled in some call positions and
6072 // should be left in place.
6073 case BuiltinType::ARCUnbridgedCast:
6074 return false;
6075
6076 // Pseudo-objects should be converted as soon as possible.
6077 case BuiltinType::PseudoObject:
6078 return true;
6079
6080 // The debugger mode could theoretically but currently does not try
6081 // to resolve unknown-typed arguments based on known parameter types.
6082 case BuiltinType::UnknownAny:
6083 return true;
6084
6085 // These are always invalid as call arguments and should be reported.
6086 case BuiltinType::BoundMember:
6087 case BuiltinType::BuiltinFn:
6088 case BuiltinType::IncompleteMatrixIdx:
6089 case BuiltinType::OMPArraySection:
6090 case BuiltinType::OMPArrayShaping:
6091 case BuiltinType::OMPIterator:
6092 return true;
6093
6094 }
6095 llvm_unreachable("bad builtin type kind");
6096 }
6097
6098 /// Check an argument list for placeholders that we won't try to
6099 /// handle later.
checkArgsForPlaceholders(Sema & S,MultiExprArg args)6100 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
6101 // Apply this processing to all the arguments at once instead of
6102 // dying at the first failure.
6103 bool hasInvalid = false;
6104 for (size_t i = 0, e = args.size(); i != e; i++) {
6105 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6106 ExprResult result = S.CheckPlaceholderExpr(args[i]);
6107 if (result.isInvalid()) hasInvalid = true;
6108 else args[i] = result.get();
6109 }
6110 }
6111 return hasInvalid;
6112 }
6113
6114 /// If a builtin function has a pointer argument with no explicit address
6115 /// space, then it should be able to accept a pointer to any address
6116 /// space as input. In order to do this, we need to replace the
6117 /// standard builtin declaration with one that uses the same address space
6118 /// as the call.
6119 ///
6120 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6121 /// it does not contain any pointer arguments without
6122 /// an address space qualifer. Otherwise the rewritten
6123 /// FunctionDecl is returned.
6124 /// TODO: Handle pointer return types.
rewriteBuiltinFunctionDecl(Sema * Sema,ASTContext & Context,FunctionDecl * FDecl,MultiExprArg ArgExprs)6125 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6126 FunctionDecl *FDecl,
6127 MultiExprArg ArgExprs) {
6128
6129 QualType DeclType = FDecl->getType();
6130 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6131
6132 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6133 ArgExprs.size() < FT->getNumParams())
6134 return nullptr;
6135
6136 bool NeedsNewDecl = false;
6137 unsigned i = 0;
6138 SmallVector<QualType, 8> OverloadParams;
6139
6140 for (QualType ParamType : FT->param_types()) {
6141
6142 // Convert array arguments to pointer to simplify type lookup.
6143 ExprResult ArgRes =
6144 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
6145 if (ArgRes.isInvalid())
6146 return nullptr;
6147 Expr *Arg = ArgRes.get();
6148 QualType ArgType = Arg->getType();
6149 if (!ParamType->isPointerType() ||
6150 ParamType.hasAddressSpace() ||
6151 !ArgType->isPointerType() ||
6152 !ArgType->getPointeeType().hasAddressSpace()) {
6153 OverloadParams.push_back(ParamType);
6154 continue;
6155 }
6156
6157 QualType PointeeType = ParamType->getPointeeType();
6158 if (PointeeType.hasAddressSpace())
6159 continue;
6160
6161 NeedsNewDecl = true;
6162 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6163
6164 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6165 OverloadParams.push_back(Context.getPointerType(PointeeType));
6166 }
6167
6168 if (!NeedsNewDecl)
6169 return nullptr;
6170
6171 FunctionProtoType::ExtProtoInfo EPI;
6172 EPI.Variadic = FT->isVariadic();
6173 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6174 OverloadParams, EPI);
6175 DeclContext *Parent = FDecl->getParent();
6176 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
6177 FDecl->getLocation(),
6178 FDecl->getLocation(),
6179 FDecl->getIdentifier(),
6180 OverloadTy,
6181 /*TInfo=*/nullptr,
6182 SC_Extern, false,
6183 /*hasPrototype=*/true);
6184 SmallVector<ParmVarDecl*, 16> Params;
6185 FT = cast<FunctionProtoType>(OverloadTy);
6186 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6187 QualType ParamType = FT->getParamType(i);
6188 ParmVarDecl *Parm =
6189 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6190 SourceLocation(), nullptr, ParamType,
6191 /*TInfo=*/nullptr, SC_None, nullptr);
6192 Parm->setScopeInfo(0, i);
6193 Params.push_back(Parm);
6194 }
6195 OverloadDecl->setParams(Params);
6196 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6197 return OverloadDecl;
6198 }
6199
checkDirectCallValidity(Sema & S,const Expr * Fn,FunctionDecl * Callee,MultiExprArg ArgExprs)6200 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6201 FunctionDecl *Callee,
6202 MultiExprArg ArgExprs) {
6203 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6204 // similar attributes) really don't like it when functions are called with an
6205 // invalid number of args.
6206 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6207 /*PartialOverloading=*/false) &&
6208 !Callee->isVariadic())
6209 return;
6210 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6211 return;
6212
6213 if (const EnableIfAttr *Attr =
6214 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6215 S.Diag(Fn->getBeginLoc(),
6216 isa<CXXMethodDecl>(Callee)
6217 ? diag::err_ovl_no_viable_member_function_in_call
6218 : diag::err_ovl_no_viable_function_in_call)
6219 << Callee << Callee->getSourceRange();
6220 S.Diag(Callee->getLocation(),
6221 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6222 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6223 return;
6224 }
6225 }
6226
enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr * const UME,Sema & S)6227 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6228 const UnresolvedMemberExpr *const UME, Sema &S) {
6229
6230 const auto GetFunctionLevelDCIfCXXClass =
6231 [](Sema &S) -> const CXXRecordDecl * {
6232 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6233 if (!DC || !DC->getParent())
6234 return nullptr;
6235
6236 // If the call to some member function was made from within a member
6237 // function body 'M' return return 'M's parent.
6238 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6239 return MD->getParent()->getCanonicalDecl();
6240 // else the call was made from within a default member initializer of a
6241 // class, so return the class.
6242 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6243 return RD->getCanonicalDecl();
6244 return nullptr;
6245 };
6246 // If our DeclContext is neither a member function nor a class (in the
6247 // case of a lambda in a default member initializer), we can't have an
6248 // enclosing 'this'.
6249
6250 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6251 if (!CurParentClass)
6252 return false;
6253
6254 // The naming class for implicit member functions call is the class in which
6255 // name lookup starts.
6256 const CXXRecordDecl *const NamingClass =
6257 UME->getNamingClass()->getCanonicalDecl();
6258 assert(NamingClass && "Must have naming class even for implicit access");
6259
6260 // If the unresolved member functions were found in a 'naming class' that is
6261 // related (either the same or derived from) to the class that contains the
6262 // member function that itself contained the implicit member access.
6263
6264 return CurParentClass == NamingClass ||
6265 CurParentClass->isDerivedFrom(NamingClass);
6266 }
6267
6268 static void
tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema & S,const UnresolvedMemberExpr * const UME,SourceLocation CallLoc)6269 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6270 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6271
6272 if (!UME)
6273 return;
6274
6275 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6276 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6277 // already been captured, or if this is an implicit member function call (if
6278 // it isn't, an attempt to capture 'this' should already have been made).
6279 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6280 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6281 return;
6282
6283 // Check if the naming class in which the unresolved members were found is
6284 // related (same as or is a base of) to the enclosing class.
6285
6286 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
6287 return;
6288
6289
6290 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6291 // If the enclosing function is not dependent, then this lambda is
6292 // capture ready, so if we can capture this, do so.
6293 if (!EnclosingFunctionCtx->isDependentContext()) {
6294 // If the current lambda and all enclosing lambdas can capture 'this' -
6295 // then go ahead and capture 'this' (since our unresolved overload set
6296 // contains at least one non-static member function).
6297 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6298 S.CheckCXXThisCapture(CallLoc);
6299 } else if (S.CurContext->isDependentContext()) {
6300 // ... since this is an implicit member reference, that might potentially
6301 // involve a 'this' capture, mark 'this' for potential capture in
6302 // enclosing lambdas.
6303 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6304 CurLSI->addPotentialThisCapture(CallLoc);
6305 }
6306 }
6307
ActOnCallExpr(Scope * Scope,Expr * Fn,SourceLocation LParenLoc,MultiExprArg ArgExprs,SourceLocation RParenLoc,Expr * ExecConfig)6308 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6309 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6310 Expr *ExecConfig) {
6311 ExprResult Call =
6312 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig);
6313 if (Call.isInvalid())
6314 return Call;
6315
6316 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6317 // language modes.
6318 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn)) {
6319 if (ULE->hasExplicitTemplateArgs() &&
6320 ULE->decls_begin() == ULE->decls_end()) {
6321 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6322 ? diag::warn_cxx17_compat_adl_only_template_id
6323 : diag::ext_adl_only_template_id)
6324 << ULE->getName();
6325 }
6326 }
6327
6328 if (LangOpts.OpenMP)
6329 Call = ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6330 ExecConfig);
6331
6332 return Call;
6333 }
6334
6335 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6336 /// This provides the location of the left/right parens and a list of comma
6337 /// locations.
BuildCallExpr(Scope * Scope,Expr * Fn,SourceLocation LParenLoc,MultiExprArg ArgExprs,SourceLocation RParenLoc,Expr * ExecConfig,bool IsExecConfig)6338 ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6339 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6340 Expr *ExecConfig, bool IsExecConfig) {
6341 // Since this might be a postfix expression, get rid of ParenListExprs.
6342 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
6343 if (Result.isInvalid()) return ExprError();
6344 Fn = Result.get();
6345
6346 if (checkArgsForPlaceholders(*this, ArgExprs))
6347 return ExprError();
6348
6349 if (getLangOpts().CPlusPlus) {
6350 // If this is a pseudo-destructor expression, build the call immediately.
6351 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6352 if (!ArgExprs.empty()) {
6353 // Pseudo-destructor calls should not have any arguments.
6354 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6355 << FixItHint::CreateRemoval(
6356 SourceRange(ArgExprs.front()->getBeginLoc(),
6357 ArgExprs.back()->getEndLoc()));
6358 }
6359
6360 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6361 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6362 }
6363 if (Fn->getType() == Context.PseudoObjectTy) {
6364 ExprResult result = CheckPlaceholderExpr(Fn);
6365 if (result.isInvalid()) return ExprError();
6366 Fn = result.get();
6367 }
6368
6369 // Determine whether this is a dependent call inside a C++ template,
6370 // in which case we won't do any semantic analysis now.
6371 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6372 if (ExecConfig) {
6373 return CUDAKernelCallExpr::Create(
6374 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
6375 Context.DependentTy, VK_RValue, RParenLoc, CurFPFeatureOverrides());
6376 } else {
6377
6378 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6379 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6380 Fn->getBeginLoc());
6381
6382 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6383 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6384 }
6385 }
6386
6387 // Determine whether this is a call to an object (C++ [over.call.object]).
6388 if (Fn->getType()->isRecordType())
6389 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6390 RParenLoc);
6391
6392 if (Fn->getType() == Context.UnknownAnyTy) {
6393 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6394 if (result.isInvalid()) return ExprError();
6395 Fn = result.get();
6396 }
6397
6398 if (Fn->getType() == Context.BoundMemberTy) {
6399 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6400 RParenLoc);
6401 }
6402 }
6403
6404 // Check for overloaded calls. This can happen even in C due to extensions.
6405 if (Fn->getType() == Context.OverloadTy) {
6406 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
6407
6408 // We aren't supposed to apply this logic if there's an '&' involved.
6409 if (!find.HasFormOfMemberPointer) {
6410 if (Expr::hasAnyTypeDependentArguments(ArgExprs))
6411 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6412 VK_RValue, RParenLoc, CurFPFeatureOverrides());
6413 OverloadExpr *ovl = find.Expression;
6414 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6415 return BuildOverloadedCallExpr(
6416 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6417 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6418 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6419 RParenLoc);
6420 }
6421 }
6422
6423 // If we're directly calling a function, get the appropriate declaration.
6424 if (Fn->getType() == Context.UnknownAnyTy) {
6425 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6426 if (result.isInvalid()) return ExprError();
6427 Fn = result.get();
6428 }
6429
6430 Expr *NakedFn = Fn->IgnoreParens();
6431
6432 bool CallingNDeclIndirectly = false;
6433 NamedDecl *NDecl = nullptr;
6434 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6435 if (UnOp->getOpcode() == UO_AddrOf) {
6436 CallingNDeclIndirectly = true;
6437 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6438 }
6439 }
6440
6441 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6442 NDecl = DRE->getDecl();
6443
6444 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6445 if (FDecl && FDecl->getBuiltinID()) {
6446 // Rewrite the function decl for this builtin by replacing parameters
6447 // with no explicit address space with the address space of the arguments
6448 // in ArgExprs.
6449 if ((FDecl =
6450 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6451 NDecl = FDecl;
6452 Fn = DeclRefExpr::Create(
6453 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6454 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6455 nullptr, DRE->isNonOdrUse());
6456 }
6457 }
6458 } else if (isa<MemberExpr>(NakedFn))
6459 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
6460
6461 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6462 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6463 FD, /*Complain=*/true, Fn->getBeginLoc()))
6464 return ExprError();
6465
6466 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
6467 return ExprError();
6468
6469 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6470 }
6471
6472 if (Context.isDependenceAllowed() &&
6473 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6474 assert(!getLangOpts().CPlusPlus);
6475 assert((Fn->containsErrors() ||
6476 llvm::any_of(ArgExprs,
6477 [](clang::Expr *E) { return E->containsErrors(); })) &&
6478 "should only occur in error-recovery path.");
6479 QualType ReturnType =
6480 llvm::isa_and_nonnull<FunctionDecl>(NDecl)
6481 ? dyn_cast<FunctionDecl>(NDecl)->getCallResultType()
6482 : Context.DependentTy;
6483 return CallExpr::Create(Context, Fn, ArgExprs, ReturnType,
6484 Expr::getValueKindForType(ReturnType), RParenLoc,
6485 CurFPFeatureOverrides());
6486 }
6487 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6488 ExecConfig, IsExecConfig);
6489 }
6490
6491 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
6492 ///
6493 /// __builtin_astype( value, dst type )
6494 ///
ActOnAsTypeExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)6495 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6496 SourceLocation BuiltinLoc,
6497 SourceLocation RParenLoc) {
6498 ExprValueKind VK = VK_RValue;
6499 ExprObjectKind OK = OK_Ordinary;
6500 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6501 QualType SrcTy = E->getType();
6502 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
6503 return ExprError(Diag(BuiltinLoc,
6504 diag::err_invalid_astype_of_different_size)
6505 << DstTy
6506 << SrcTy
6507 << E->getSourceRange());
6508 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6509 }
6510
6511 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
6512 /// provided arguments.
6513 ///
6514 /// __builtin_convertvector( value, dst type )
6515 ///
ActOnConvertVectorExpr(Expr * E,ParsedType ParsedDestTy,SourceLocation BuiltinLoc,SourceLocation RParenLoc)6516 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6517 SourceLocation BuiltinLoc,
6518 SourceLocation RParenLoc) {
6519 TypeSourceInfo *TInfo;
6520 GetTypeFromParser(ParsedDestTy, &TInfo);
6521 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6522 }
6523
6524 /// BuildResolvedCallExpr - Build a call to a resolved expression,
6525 /// i.e. an expression not of \p OverloadTy. The expression should
6526 /// unary-convert to an expression of function-pointer or
6527 /// block-pointer type.
6528 ///
6529 /// \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)6530 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
6531 SourceLocation LParenLoc,
6532 ArrayRef<Expr *> Args,
6533 SourceLocation RParenLoc, Expr *Config,
6534 bool IsExecConfig, ADLCallKind UsesADL) {
6535 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6536 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6537
6538 // Functions with 'interrupt' attribute cannot be called directly.
6539 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6540 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6541 return ExprError();
6542 }
6543
6544 // Interrupt handlers don't save off the VFP regs automatically on ARM,
6545 // so there's some risk when calling out to non-interrupt handler functions
6546 // that the callee might not preserve them. This is easy to diagnose here,
6547 // but can be very challenging to debug.
6548 if (auto *Caller = getCurFunctionDecl())
6549 if (Caller->hasAttr<ARMInterruptAttr>()) {
6550 bool VFP = Context.getTargetInfo().hasFeature("vfp");
6551 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
6552 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6553 }
6554
6555 // Promote the function operand.
6556 // We special-case function promotion here because we only allow promoting
6557 // builtin functions to function pointers in the callee of a call.
6558 ExprResult Result;
6559 QualType ResultTy;
6560 if (BuiltinID &&
6561 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6562 // Extract the return type from the (builtin) function pointer type.
6563 // FIXME Several builtins still have setType in
6564 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6565 // Builtins.def to ensure they are correct before removing setType calls.
6566 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6567 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6568 ResultTy = FDecl->getCallResultType();
6569 } else {
6570 Result = CallExprUnaryConversions(Fn);
6571 ResultTy = Context.BoolTy;
6572 }
6573 if (Result.isInvalid())
6574 return ExprError();
6575 Fn = Result.get();
6576
6577 // Check for a valid function type, but only if it is not a builtin which
6578 // requires custom type checking. These will be handled by
6579 // CheckBuiltinFunctionCall below just after creation of the call expression.
6580 const FunctionType *FuncT = nullptr;
6581 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6582 retry:
6583 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6584 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6585 // have type pointer to function".
6586 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6587 if (!FuncT)
6588 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6589 << Fn->getType() << Fn->getSourceRange());
6590 } else if (const BlockPointerType *BPT =
6591 Fn->getType()->getAs<BlockPointerType>()) {
6592 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6593 } else {
6594 // Handle calls to expressions of unknown-any type.
6595 if (Fn->getType() == Context.UnknownAnyTy) {
6596 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6597 if (rewrite.isInvalid())
6598 return ExprError();
6599 Fn = rewrite.get();
6600 goto retry;
6601 }
6602
6603 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6604 << Fn->getType() << Fn->getSourceRange());
6605 }
6606 }
6607
6608 // Get the number of parameters in the function prototype, if any.
6609 // We will allocate space for max(Args.size(), NumParams) arguments
6610 // in the call expression.
6611 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6612 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6613
6614 CallExpr *TheCall;
6615 if (Config) {
6616 assert(UsesADL == ADLCallKind::NotADL &&
6617 "CUDAKernelCallExpr should not use ADL");
6618 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6619 Args, ResultTy, VK_RValue, RParenLoc,
6620 CurFPFeatureOverrides(), NumParams);
6621 } else {
6622 TheCall =
6623 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6624 CurFPFeatureOverrides(), NumParams, UsesADL);
6625 }
6626
6627 if (!Context.isDependenceAllowed()) {
6628 // Forget about the nulled arguments since typo correction
6629 // do not handle them well.
6630 TheCall->shrinkNumArgs(Args.size());
6631 // C cannot always handle TypoExpr nodes in builtin calls and direct
6632 // function calls as their argument checking don't necessarily handle
6633 // dependent types properly, so make sure any TypoExprs have been
6634 // dealt with.
6635 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
6636 if (!Result.isUsable()) return ExprError();
6637 CallExpr *TheOldCall = TheCall;
6638 TheCall = dyn_cast<CallExpr>(Result.get());
6639 bool CorrectedTypos = TheCall != TheOldCall;
6640 if (!TheCall) return Result;
6641 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6642
6643 // A new call expression node was created if some typos were corrected.
6644 // However it may not have been constructed with enough storage. In this
6645 // case, rebuild the node with enough storage. The waste of space is
6646 // immaterial since this only happens when some typos were corrected.
6647 if (CorrectedTypos && Args.size() < NumParams) {
6648 if (Config)
6649 TheCall = CUDAKernelCallExpr::Create(
6650 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
6651 RParenLoc, CurFPFeatureOverrides(), NumParams);
6652 else
6653 TheCall =
6654 CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue, RParenLoc,
6655 CurFPFeatureOverrides(), NumParams, UsesADL);
6656 }
6657 // We can now handle the nulled arguments for the default arguments.
6658 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6659 }
6660
6661 // Bail out early if calling a builtin with custom type checking.
6662 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
6663 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6664
6665 if (getLangOpts().CUDA) {
6666 if (Config) {
6667 // CUDA: Kernel calls must be to global functions
6668 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6669 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6670 << FDecl << Fn->getSourceRange());
6671
6672 // CUDA: Kernel function must have 'void' return type
6673 if (!FuncT->getReturnType()->isVoidType() &&
6674 !FuncT->getReturnType()->getAs<AutoType>() &&
6675 !FuncT->getReturnType()->isInstantiationDependentType())
6676 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6677 << Fn->getType() << Fn->getSourceRange());
6678 } else {
6679 // CUDA: Calls to global functions must be configured
6680 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6681 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6682 << FDecl << Fn->getSourceRange());
6683 }
6684 }
6685
6686 // Check for a valid return type
6687 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6688 FDecl))
6689 return ExprError();
6690
6691 // We know the result type of the call, set it.
6692 TheCall->setType(FuncT->getCallResultType(Context));
6693 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
6694
6695 if (Proto) {
6696 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6697 IsExecConfig))
6698 return ExprError();
6699 } else {
6700 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6701
6702 if (FDecl) {
6703 // Check if we have too few/too many template arguments, based
6704 // on our knowledge of the function definition.
6705 const FunctionDecl *Def = nullptr;
6706 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6707 Proto = Def->getType()->getAs<FunctionProtoType>();
6708 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6709 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6710 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6711 }
6712
6713 // If the function we're calling isn't a function prototype, but we have
6714 // a function prototype from a prior declaratiom, use that prototype.
6715 if (!FDecl->hasPrototype())
6716 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6717 }
6718
6719 // Promote the arguments (C99 6.5.2.2p6).
6720 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6721 Expr *Arg = Args[i];
6722
6723 if (Proto && i < Proto->getNumParams()) {
6724 InitializedEntity Entity = InitializedEntity::InitializeParameter(
6725 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6726 ExprResult ArgE =
6727 PerformCopyInitialization(Entity, SourceLocation(), Arg);
6728 if (ArgE.isInvalid())
6729 return true;
6730
6731 Arg = ArgE.getAs<Expr>();
6732
6733 } else {
6734 ExprResult ArgE = DefaultArgumentPromotion(Arg);
6735
6736 if (ArgE.isInvalid())
6737 return true;
6738
6739 Arg = ArgE.getAs<Expr>();
6740 }
6741
6742 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6743 diag::err_call_incomplete_argument, Arg))
6744 return ExprError();
6745
6746 TheCall->setArg(i, Arg);
6747 }
6748 }
6749
6750 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6751 if (!Method->isStatic())
6752 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6753 << Fn->getSourceRange());
6754
6755 // Check for sentinels
6756 if (NDecl)
6757 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6758
6759 // Warn for unions passing across security boundary (CMSE).
6760 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6761 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6762 if (const auto *RT =
6763 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6764 if (RT->getDecl()->isOrContainsUnion())
6765 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6766 << 0 << i;
6767 }
6768 }
6769 }
6770
6771 // Do special checking on direct calls to functions.
6772 if (FDecl) {
6773 if (CheckFunctionCall(FDecl, TheCall, Proto))
6774 return ExprError();
6775
6776 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6777
6778 if (BuiltinID)
6779 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6780 } else if (NDecl) {
6781 if (CheckPointerCall(NDecl, TheCall, Proto))
6782 return ExprError();
6783 } else {
6784 if (CheckOtherCall(TheCall, Proto))
6785 return ExprError();
6786 }
6787
6788 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6789 }
6790
6791 ExprResult
ActOnCompoundLiteral(SourceLocation LParenLoc,ParsedType Ty,SourceLocation RParenLoc,Expr * InitExpr)6792 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
6793 SourceLocation RParenLoc, Expr *InitExpr) {
6794 assert(Ty && "ActOnCompoundLiteral(): missing type");
6795 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6796
6797 TypeSourceInfo *TInfo;
6798 QualType literalType = GetTypeFromParser(Ty, &TInfo);
6799 if (!TInfo)
6800 TInfo = Context.getTrivialTypeSourceInfo(literalType);
6801
6802 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6803 }
6804
6805 ExprResult
BuildCompoundLiteralExpr(SourceLocation LParenLoc,TypeSourceInfo * TInfo,SourceLocation RParenLoc,Expr * LiteralExpr)6806 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
6807 SourceLocation RParenLoc, Expr *LiteralExpr) {
6808 QualType literalType = TInfo->getType();
6809
6810 if (literalType->isArrayType()) {
6811 if (RequireCompleteSizedType(
6812 LParenLoc, Context.getBaseElementType(literalType),
6813 diag::err_array_incomplete_or_sizeless_type,
6814 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6815 return ExprError();
6816 if (literalType->isVariableArrayType())
6817 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
6818 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
6819 } else if (!literalType->isDependentType() &&
6820 RequireCompleteType(LParenLoc, literalType,
6821 diag::err_typecheck_decl_incomplete_type,
6822 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6823 return ExprError();
6824
6825 InitializedEntity Entity
6826 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
6827 InitializationKind Kind
6828 = InitializationKind::CreateCStyleCast(LParenLoc,
6829 SourceRange(LParenLoc, RParenLoc),
6830 /*InitList=*/true);
6831 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
6832 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
6833 &literalType);
6834 if (Result.isInvalid())
6835 return ExprError();
6836 LiteralExpr = Result.get();
6837
6838 bool isFileScope = !CurContext->isFunctionOrMethod();
6839
6840 // In C, compound literals are l-values for some reason.
6841 // For GCC compatibility, in C++, file-scope array compound literals with
6842 // constant initializers are also l-values, and compound literals are
6843 // otherwise prvalues.
6844 //
6845 // (GCC also treats C++ list-initialized file-scope array prvalues with
6846 // constant initializers as l-values, but that's non-conforming, so we don't
6847 // follow it there.)
6848 //
6849 // FIXME: It would be better to handle the lvalue cases as materializing and
6850 // lifetime-extending a temporary object, but our materialized temporaries
6851 // representation only supports lifetime extension from a variable, not "out
6852 // of thin air".
6853 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6854 // is bound to the result of applying array-to-pointer decay to the compound
6855 // literal.
6856 // FIXME: GCC supports compound literals of reference type, which should
6857 // obviously have a value kind derived from the kind of reference involved.
6858 ExprValueKind VK =
6859 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6860 ? VK_RValue
6861 : VK_LValue;
6862
6863 if (isFileScope)
6864 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6865 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6866 Expr *Init = ILE->getInit(i);
6867 ILE->setInit(i, ConstantExpr::Create(Context, Init));
6868 }
6869
6870 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6871 VK, LiteralExpr, isFileScope);
6872 if (isFileScope) {
6873 if (!LiteralExpr->isTypeDependent() &&
6874 !LiteralExpr->isValueDependent() &&
6875 !literalType->isDependentType()) // C99 6.5.2.5p3
6876 if (CheckForConstantInitializer(LiteralExpr, literalType))
6877 return ExprError();
6878 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6879 literalType.getAddressSpace() != LangAS::Default) {
6880 // Embedded-C extensions to C99 6.5.2.5:
6881 // "If the compound literal occurs inside the body of a function, the
6882 // type name shall not be qualified by an address-space qualifier."
6883 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6884 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6885 return ExprError();
6886 }
6887
6888 if (!isFileScope && !getLangOpts().CPlusPlus) {
6889 // Compound literals that have automatic storage duration are destroyed at
6890 // the end of the scope in C; in C++, they're just temporaries.
6891
6892 // Emit diagnostics if it is or contains a C union type that is non-trivial
6893 // to destruct.
6894 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
6895 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
6896 NTCUC_CompoundLiteral, NTCUK_Destruct);
6897
6898 // Diagnose jumps that enter or exit the lifetime of the compound literal.
6899 if (literalType.isDestructedType()) {
6900 Cleanup.setExprNeedsCleanups(true);
6901 ExprCleanupObjects.push_back(E);
6902 getCurFunction()->setHasBranchProtectedScope();
6903 }
6904 }
6905
6906 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
6907 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
6908 checkNonTrivialCUnionInInitializer(E->getInitializer(),
6909 E->getInitializer()->getExprLoc());
6910
6911 return MaybeBindToTemporary(E);
6912 }
6913
6914 ExprResult
ActOnInitList(SourceLocation LBraceLoc,MultiExprArg InitArgList,SourceLocation RBraceLoc)6915 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6916 SourceLocation RBraceLoc) {
6917 // Only produce each kind of designated initialization diagnostic once.
6918 SourceLocation FirstDesignator;
6919 bool DiagnosedArrayDesignator = false;
6920 bool DiagnosedNestedDesignator = false;
6921 bool DiagnosedMixedDesignator = false;
6922
6923 // Check that any designated initializers are syntactically valid in the
6924 // current language mode.
6925 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6926 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
6927 if (FirstDesignator.isInvalid())
6928 FirstDesignator = DIE->getBeginLoc();
6929
6930 if (!getLangOpts().CPlusPlus)
6931 break;
6932
6933 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
6934 DiagnosedNestedDesignator = true;
6935 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
6936 << DIE->getDesignatorsSourceRange();
6937 }
6938
6939 for (auto &Desig : DIE->designators()) {
6940 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
6941 DiagnosedArrayDesignator = true;
6942 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
6943 << Desig.getSourceRange();
6944 }
6945 }
6946
6947 if (!DiagnosedMixedDesignator &&
6948 !isa<DesignatedInitExpr>(InitArgList[0])) {
6949 DiagnosedMixedDesignator = true;
6950 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6951 << DIE->getSourceRange();
6952 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
6953 << InitArgList[0]->getSourceRange();
6954 }
6955 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
6956 isa<DesignatedInitExpr>(InitArgList[0])) {
6957 DiagnosedMixedDesignator = true;
6958 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
6959 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
6960 << DIE->getSourceRange();
6961 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
6962 << InitArgList[I]->getSourceRange();
6963 }
6964 }
6965
6966 if (FirstDesignator.isValid()) {
6967 // Only diagnose designated initiaization as a C++20 extension if we didn't
6968 // already diagnose use of (non-C++20) C99 designator syntax.
6969 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
6970 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
6971 Diag(FirstDesignator, getLangOpts().CPlusPlus20
6972 ? diag::warn_cxx17_compat_designated_init
6973 : diag::ext_cxx_designated_init);
6974 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
6975 Diag(FirstDesignator, diag::ext_designated_init);
6976 }
6977 }
6978
6979 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
6980 }
6981
6982 ExprResult
BuildInitList(SourceLocation LBraceLoc,MultiExprArg InitArgList,SourceLocation RBraceLoc)6983 Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6984 SourceLocation RBraceLoc) {
6985 // Semantic analysis for initializers is done by ActOnDeclarator() and
6986 // CheckInitializer() - it requires knowledge of the object being initialized.
6987
6988 // Immediately handle non-overload placeholders. Overloads can be
6989 // resolved contextually, but everything else here can't.
6990 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6991 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6992 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6993
6994 // Ignore failures; dropping the entire initializer list because
6995 // of one failure would be terrible for indexing/etc.
6996 if (result.isInvalid()) continue;
6997
6998 InitArgList[I] = result.get();
6999 }
7000 }
7001
7002 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7003 RBraceLoc);
7004 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7005 return E;
7006 }
7007
7008 /// Do an explicit extend of the given block pointer if we're in ARC.
maybeExtendBlockObject(ExprResult & E)7009 void Sema::maybeExtendBlockObject(ExprResult &E) {
7010 assert(E.get()->getType()->isBlockPointerType());
7011 assert(E.get()->isRValue());
7012
7013 // Only do this in an r-value context.
7014 if (!getLangOpts().ObjCAutoRefCount) return;
7015
7016 E = ImplicitCastExpr::Create(
7017 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7018 /*base path*/ nullptr, VK_RValue, FPOptionsOverride());
7019 Cleanup.setExprNeedsCleanups(true);
7020 }
7021
7022 /// Prepare a conversion of the given expression to an ObjC object
7023 /// pointer type.
PrepareCastToObjCObjectPointer(ExprResult & E)7024 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7025 QualType type = E.get()->getType();
7026 if (type->isObjCObjectPointerType()) {
7027 return CK_BitCast;
7028 } else if (type->isBlockPointerType()) {
7029 maybeExtendBlockObject(E);
7030 return CK_BlockPointerToObjCPointerCast;
7031 } else {
7032 assert(type->isPointerType());
7033 return CK_CPointerToObjCPointerCast;
7034 }
7035 }
7036
7037 /// Prepares for a scalar cast, performing all the necessary stages
7038 /// except the final cast and returning the kind required.
PrepareScalarCast(ExprResult & Src,QualType DestTy)7039 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
7040 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7041 // Also, callers should have filtered out the invalid cases with
7042 // pointers. Everything else should be possible.
7043
7044 QualType SrcTy = Src.get()->getType();
7045 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7046 return CK_NoOp;
7047
7048 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7049 case Type::STK_MemberPointer:
7050 llvm_unreachable("member pointer type in C");
7051
7052 case Type::STK_CPointer:
7053 case Type::STK_BlockPointer:
7054 case Type::STK_ObjCObjectPointer:
7055 switch (DestTy->getScalarTypeKind()) {
7056 case Type::STK_CPointer: {
7057 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7058 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7059 if (SrcAS != DestAS)
7060 return CK_AddressSpaceConversion;
7061 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7062 return CK_NoOp;
7063 return CK_BitCast;
7064 }
7065 case Type::STK_BlockPointer:
7066 return (SrcKind == Type::STK_BlockPointer
7067 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7068 case Type::STK_ObjCObjectPointer:
7069 if (SrcKind == Type::STK_ObjCObjectPointer)
7070 return CK_BitCast;
7071 if (SrcKind == Type::STK_CPointer)
7072 return CK_CPointerToObjCPointerCast;
7073 maybeExtendBlockObject(Src);
7074 return CK_BlockPointerToObjCPointerCast;
7075 case Type::STK_Bool:
7076 return CK_PointerToBoolean;
7077 case Type::STK_Integral:
7078 return CK_PointerToIntegral;
7079 case Type::STK_Floating:
7080 case Type::STK_FloatingComplex:
7081 case Type::STK_IntegralComplex:
7082 case Type::STK_MemberPointer:
7083 case Type::STK_FixedPoint:
7084 llvm_unreachable("illegal cast from pointer");
7085 }
7086 llvm_unreachable("Should have returned before this");
7087
7088 case Type::STK_FixedPoint:
7089 switch (DestTy->getScalarTypeKind()) {
7090 case Type::STK_FixedPoint:
7091 return CK_FixedPointCast;
7092 case Type::STK_Bool:
7093 return CK_FixedPointToBoolean;
7094 case Type::STK_Integral:
7095 return CK_FixedPointToIntegral;
7096 case Type::STK_Floating:
7097 return CK_FixedPointToFloating;
7098 case Type::STK_IntegralComplex:
7099 case Type::STK_FloatingComplex:
7100 Diag(Src.get()->getExprLoc(),
7101 diag::err_unimplemented_conversion_with_fixed_point_type)
7102 << DestTy;
7103 return CK_IntegralCast;
7104 case Type::STK_CPointer:
7105 case Type::STK_ObjCObjectPointer:
7106 case Type::STK_BlockPointer:
7107 case Type::STK_MemberPointer:
7108 llvm_unreachable("illegal cast to pointer type");
7109 }
7110 llvm_unreachable("Should have returned before this");
7111
7112 case Type::STK_Bool: // casting from bool is like casting from an integer
7113 case Type::STK_Integral:
7114 switch (DestTy->getScalarTypeKind()) {
7115 case Type::STK_CPointer:
7116 case Type::STK_ObjCObjectPointer:
7117 case Type::STK_BlockPointer:
7118 if (Src.get()->isNullPointerConstant(Context,
7119 Expr::NPC_ValueDependentIsNull))
7120 return CK_NullToPointer;
7121 return CK_IntegralToPointer;
7122 case Type::STK_Bool:
7123 return CK_IntegralToBoolean;
7124 case Type::STK_Integral:
7125 return CK_IntegralCast;
7126 case Type::STK_Floating:
7127 return CK_IntegralToFloating;
7128 case Type::STK_IntegralComplex:
7129 Src = ImpCastExprToType(Src.get(),
7130 DestTy->castAs<ComplexType>()->getElementType(),
7131 CK_IntegralCast);
7132 return CK_IntegralRealToComplex;
7133 case Type::STK_FloatingComplex:
7134 Src = ImpCastExprToType(Src.get(),
7135 DestTy->castAs<ComplexType>()->getElementType(),
7136 CK_IntegralToFloating);
7137 return CK_FloatingRealToComplex;
7138 case Type::STK_MemberPointer:
7139 llvm_unreachable("member pointer type in C");
7140 case Type::STK_FixedPoint:
7141 return CK_IntegralToFixedPoint;
7142 }
7143 llvm_unreachable("Should have returned before this");
7144
7145 case Type::STK_Floating:
7146 switch (DestTy->getScalarTypeKind()) {
7147 case Type::STK_Floating:
7148 return CK_FloatingCast;
7149 case Type::STK_Bool:
7150 return CK_FloatingToBoolean;
7151 case Type::STK_Integral:
7152 return CK_FloatingToIntegral;
7153 case Type::STK_FloatingComplex:
7154 Src = ImpCastExprToType(Src.get(),
7155 DestTy->castAs<ComplexType>()->getElementType(),
7156 CK_FloatingCast);
7157 return CK_FloatingRealToComplex;
7158 case Type::STK_IntegralComplex:
7159 Src = ImpCastExprToType(Src.get(),
7160 DestTy->castAs<ComplexType>()->getElementType(),
7161 CK_FloatingToIntegral);
7162 return CK_IntegralRealToComplex;
7163 case Type::STK_CPointer:
7164 case Type::STK_ObjCObjectPointer:
7165 case Type::STK_BlockPointer:
7166 llvm_unreachable("valid float->pointer cast?");
7167 case Type::STK_MemberPointer:
7168 llvm_unreachable("member pointer type in C");
7169 case Type::STK_FixedPoint:
7170 return CK_FloatingToFixedPoint;
7171 }
7172 llvm_unreachable("Should have returned before this");
7173
7174 case Type::STK_FloatingComplex:
7175 switch (DestTy->getScalarTypeKind()) {
7176 case Type::STK_FloatingComplex:
7177 return CK_FloatingComplexCast;
7178 case Type::STK_IntegralComplex:
7179 return CK_FloatingComplexToIntegralComplex;
7180 case Type::STK_Floating: {
7181 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7182 if (Context.hasSameType(ET, DestTy))
7183 return CK_FloatingComplexToReal;
7184 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7185 return CK_FloatingCast;
7186 }
7187 case Type::STK_Bool:
7188 return CK_FloatingComplexToBoolean;
7189 case Type::STK_Integral:
7190 Src = ImpCastExprToType(Src.get(),
7191 SrcTy->castAs<ComplexType>()->getElementType(),
7192 CK_FloatingComplexToReal);
7193 return CK_FloatingToIntegral;
7194 case Type::STK_CPointer:
7195 case Type::STK_ObjCObjectPointer:
7196 case Type::STK_BlockPointer:
7197 llvm_unreachable("valid complex float->pointer cast?");
7198 case Type::STK_MemberPointer:
7199 llvm_unreachable("member pointer type in C");
7200 case Type::STK_FixedPoint:
7201 Diag(Src.get()->getExprLoc(),
7202 diag::err_unimplemented_conversion_with_fixed_point_type)
7203 << SrcTy;
7204 return CK_IntegralCast;
7205 }
7206 llvm_unreachable("Should have returned before this");
7207
7208 case Type::STK_IntegralComplex:
7209 switch (DestTy->getScalarTypeKind()) {
7210 case Type::STK_FloatingComplex:
7211 return CK_IntegralComplexToFloatingComplex;
7212 case Type::STK_IntegralComplex:
7213 return CK_IntegralComplexCast;
7214 case Type::STK_Integral: {
7215 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7216 if (Context.hasSameType(ET, DestTy))
7217 return CK_IntegralComplexToReal;
7218 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7219 return CK_IntegralCast;
7220 }
7221 case Type::STK_Bool:
7222 return CK_IntegralComplexToBoolean;
7223 case Type::STK_Floating:
7224 Src = ImpCastExprToType(Src.get(),
7225 SrcTy->castAs<ComplexType>()->getElementType(),
7226 CK_IntegralComplexToReal);
7227 return CK_IntegralToFloating;
7228 case Type::STK_CPointer:
7229 case Type::STK_ObjCObjectPointer:
7230 case Type::STK_BlockPointer:
7231 llvm_unreachable("valid complex int->pointer cast?");
7232 case Type::STK_MemberPointer:
7233 llvm_unreachable("member pointer type in C");
7234 case Type::STK_FixedPoint:
7235 Diag(Src.get()->getExprLoc(),
7236 diag::err_unimplemented_conversion_with_fixed_point_type)
7237 << SrcTy;
7238 return CK_IntegralCast;
7239 }
7240 llvm_unreachable("Should have returned before this");
7241 }
7242
7243 llvm_unreachable("Unhandled scalar cast");
7244 }
7245
breakDownVectorType(QualType type,uint64_t & len,QualType & eltType)7246 static bool breakDownVectorType(QualType type, uint64_t &len,
7247 QualType &eltType) {
7248 // Vectors are simple.
7249 if (const VectorType *vecType = type->getAs<VectorType>()) {
7250 len = vecType->getNumElements();
7251 eltType = vecType->getElementType();
7252 assert(eltType->isScalarType());
7253 return true;
7254 }
7255
7256 // We allow lax conversion to and from non-vector types, but only if
7257 // they're real types (i.e. non-complex, non-pointer scalar types).
7258 if (!type->isRealType()) return false;
7259
7260 len = 1;
7261 eltType = type;
7262 return true;
7263 }
7264
7265 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7266 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7267 /// allowed?
7268 ///
7269 /// This will also return false if the two given types do not make sense from
7270 /// the perspective of SVE bitcasts.
isValidSveBitcast(QualType srcTy,QualType destTy)7271 bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
7272 assert(srcTy->isVectorType() || destTy->isVectorType());
7273
7274 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7275 if (!FirstType->isSizelessBuiltinType())
7276 return false;
7277
7278 const auto *VecTy = SecondType->getAs<VectorType>();
7279 return VecTy &&
7280 VecTy->getVectorKind() == VectorType::SveFixedLengthDataVector;
7281 };
7282
7283 return ValidScalableConversion(srcTy, destTy) ||
7284 ValidScalableConversion(destTy, srcTy);
7285 }
7286
7287 /// Are the two types lax-compatible vector types? That is, given
7288 /// that one of them is a vector, do they have equal storage sizes,
7289 /// where the storage size is the number of elements times the element
7290 /// size?
7291 ///
7292 /// This will also return false if either of the types is neither a
7293 /// vector nor a real type.
areLaxCompatibleVectorTypes(QualType srcTy,QualType destTy)7294 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
7295 assert(destTy->isVectorType() || srcTy->isVectorType());
7296
7297 // Disallow lax conversions between scalars and ExtVectors (these
7298 // conversions are allowed for other vector types because common headers
7299 // depend on them). Most scalar OP ExtVector cases are handled by the
7300 // splat path anyway, which does what we want (convert, not bitcast).
7301 // What this rules out for ExtVectors is crazy things like char4*float.
7302 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7303 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7304
7305 uint64_t srcLen, destLen;
7306 QualType srcEltTy, destEltTy;
7307 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
7308 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
7309
7310 // ASTContext::getTypeSize will return the size rounded up to a
7311 // power of 2, so instead of using that, we need to use the raw
7312 // element size multiplied by the element count.
7313 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
7314 uint64_t destEltSize = Context.getTypeSize(destEltTy);
7315
7316 return (srcLen * srcEltSize == destLen * destEltSize);
7317 }
7318
7319 /// Is this a legal conversion between two types, one of which is
7320 /// known to be a vector type?
isLaxVectorConversion(QualType srcTy,QualType destTy)7321 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7322 assert(destTy->isVectorType() || srcTy->isVectorType());
7323
7324 switch (Context.getLangOpts().getLaxVectorConversions()) {
7325 case LangOptions::LaxVectorConversionKind::None:
7326 return false;
7327
7328 case LangOptions::LaxVectorConversionKind::Integer:
7329 if (!srcTy->isIntegralOrEnumerationType()) {
7330 auto *Vec = srcTy->getAs<VectorType>();
7331 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7332 return false;
7333 }
7334 if (!destTy->isIntegralOrEnumerationType()) {
7335 auto *Vec = destTy->getAs<VectorType>();
7336 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7337 return false;
7338 }
7339 // OK, integer (vector) -> integer (vector) bitcast.
7340 break;
7341
7342 case LangOptions::LaxVectorConversionKind::All:
7343 break;
7344 }
7345
7346 return areLaxCompatibleVectorTypes(srcTy, destTy);
7347 }
7348
CheckVectorCast(SourceRange R,QualType VectorTy,QualType Ty,CastKind & Kind)7349 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7350 CastKind &Kind) {
7351 assert(VectorTy->isVectorType() && "Not a vector type!");
7352
7353 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7354 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7355 return Diag(R.getBegin(),
7356 Ty->isVectorType() ?
7357 diag::err_invalid_conversion_between_vectors :
7358 diag::err_invalid_conversion_between_vector_and_integer)
7359 << VectorTy << Ty << R;
7360 } else
7361 return Diag(R.getBegin(),
7362 diag::err_invalid_conversion_between_vector_and_scalar)
7363 << VectorTy << Ty << R;
7364
7365 Kind = CK_BitCast;
7366 return false;
7367 }
7368
prepareVectorSplat(QualType VectorTy,Expr * SplattedExpr)7369 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
7370 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7371
7372 if (DestElemTy == SplattedExpr->getType())
7373 return SplattedExpr;
7374
7375 assert(DestElemTy->isFloatingType() ||
7376 DestElemTy->isIntegralOrEnumerationType());
7377
7378 CastKind CK;
7379 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7380 // OpenCL requires that we convert `true` boolean expressions to -1, but
7381 // only when splatting vectors.
7382 if (DestElemTy->isFloatingType()) {
7383 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7384 // in two steps: boolean to signed integral, then to floating.
7385 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7386 CK_BooleanToSignedIntegral);
7387 SplattedExpr = CastExprRes.get();
7388 CK = CK_IntegralToFloating;
7389 } else {
7390 CK = CK_BooleanToSignedIntegral;
7391 }
7392 } else {
7393 ExprResult CastExprRes = SplattedExpr;
7394 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7395 if (CastExprRes.isInvalid())
7396 return ExprError();
7397 SplattedExpr = CastExprRes.get();
7398 }
7399 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7400 }
7401
CheckExtVectorCast(SourceRange R,QualType DestTy,Expr * CastExpr,CastKind & Kind)7402 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
7403 Expr *CastExpr, CastKind &Kind) {
7404 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7405
7406 QualType SrcTy = CastExpr->getType();
7407
7408 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7409 // an ExtVectorType.
7410 // In OpenCL, casts between vectors of different types are not allowed.
7411 // (See OpenCL 6.2).
7412 if (SrcTy->isVectorType()) {
7413 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7414 (getLangOpts().OpenCL &&
7415 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7416 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7417 << DestTy << SrcTy << R;
7418 return ExprError();
7419 }
7420 Kind = CK_BitCast;
7421 return CastExpr;
7422 }
7423
7424 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7425 // conversion will take place first from scalar to elt type, and then
7426 // splat from elt type to vector.
7427 if (SrcTy->isPointerType())
7428 return Diag(R.getBegin(),
7429 diag::err_invalid_conversion_between_vector_and_scalar)
7430 << DestTy << SrcTy << R;
7431
7432 Kind = CK_VectorSplat;
7433 return prepareVectorSplat(DestTy, CastExpr);
7434 }
7435
7436 ExprResult
ActOnCastExpr(Scope * S,SourceLocation LParenLoc,Declarator & D,ParsedType & Ty,SourceLocation RParenLoc,Expr * CastExpr)7437 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7438 Declarator &D, ParsedType &Ty,
7439 SourceLocation RParenLoc, Expr *CastExpr) {
7440 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7441 "ActOnCastExpr(): missing type or expr");
7442
7443 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
7444 if (D.isInvalidType())
7445 return ExprError();
7446
7447 if (getLangOpts().CPlusPlus) {
7448 // Check that there are no default arguments (C++ only).
7449 CheckExtraCXXDefaultArguments(D);
7450 } else {
7451 // Make sure any TypoExprs have been dealt with.
7452 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
7453 if (!Res.isUsable())
7454 return ExprError();
7455 CastExpr = Res.get();
7456 }
7457
7458 checkUnusedDeclAttributes(D);
7459
7460 QualType castType = castTInfo->getType();
7461 Ty = CreateParsedType(castType, castTInfo);
7462
7463 bool isVectorLiteral = false;
7464
7465 // Check for an altivec or OpenCL literal,
7466 // i.e. all the elements are integer constants.
7467 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7468 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7469 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7470 && castType->isVectorType() && (PE || PLE)) {
7471 if (PLE && PLE->getNumExprs() == 0) {
7472 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7473 return ExprError();
7474 }
7475 if (PE || PLE->getNumExprs() == 1) {
7476 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7477 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7478 isVectorLiteral = true;
7479 }
7480 else
7481 isVectorLiteral = true;
7482 }
7483
7484 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7485 // then handle it as such.
7486 if (isVectorLiteral)
7487 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7488
7489 // If the Expr being casted is a ParenListExpr, handle it specially.
7490 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7491 // sequence of BinOp comma operators.
7492 if (isa<ParenListExpr>(CastExpr)) {
7493 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
7494 if (Result.isInvalid()) return ExprError();
7495 CastExpr = Result.get();
7496 }
7497
7498 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
7499 !getSourceManager().isInSystemMacro(LParenLoc))
7500 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7501
7502 CheckTollFreeBridgeCast(castType, CastExpr);
7503
7504 CheckObjCBridgeRelatedCast(castType, CastExpr);
7505
7506 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
7507
7508 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7509 }
7510
BuildVectorLiteral(SourceLocation LParenLoc,SourceLocation RParenLoc,Expr * E,TypeSourceInfo * TInfo)7511 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
7512 SourceLocation RParenLoc, Expr *E,
7513 TypeSourceInfo *TInfo) {
7514 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7515 "Expected paren or paren list expression");
7516
7517 Expr **exprs;
7518 unsigned numExprs;
7519 Expr *subExpr;
7520 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7521 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7522 LiteralLParenLoc = PE->getLParenLoc();
7523 LiteralRParenLoc = PE->getRParenLoc();
7524 exprs = PE->getExprs();
7525 numExprs = PE->getNumExprs();
7526 } else { // isa<ParenExpr> by assertion at function entrance
7527 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7528 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7529 subExpr = cast<ParenExpr>(E)->getSubExpr();
7530 exprs = &subExpr;
7531 numExprs = 1;
7532 }
7533
7534 QualType Ty = TInfo->getType();
7535 assert(Ty->isVectorType() && "Expected vector type");
7536
7537 SmallVector<Expr *, 8> initExprs;
7538 const VectorType *VTy = Ty->castAs<VectorType>();
7539 unsigned numElems = VTy->getNumElements();
7540
7541 // '(...)' form of vector initialization in AltiVec: the number of
7542 // initializers must be one or must match the size of the vector.
7543 // If a single value is specified in the initializer then it will be
7544 // replicated to all the components of the vector
7545 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
7546 // The number of initializers must be one or must match the size of the
7547 // vector. If a single value is specified in the initializer then it will
7548 // be replicated to all the components of the vector
7549 if (numExprs == 1) {
7550 QualType ElemTy = VTy->getElementType();
7551 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7552 if (Literal.isInvalid())
7553 return ExprError();
7554 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7555 PrepareScalarCast(Literal, ElemTy));
7556 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7557 }
7558 else if (numExprs < numElems) {
7559 Diag(E->getExprLoc(),
7560 diag::err_incorrect_number_of_vector_initializers);
7561 return ExprError();
7562 }
7563 else
7564 initExprs.append(exprs, exprs + numExprs);
7565 }
7566 else {
7567 // For OpenCL, when the number of initializers is a single value,
7568 // it will be replicated to all components of the vector.
7569 if (getLangOpts().OpenCL &&
7570 VTy->getVectorKind() == VectorType::GenericVector &&
7571 numExprs == 1) {
7572 QualType ElemTy = VTy->getElementType();
7573 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7574 if (Literal.isInvalid())
7575 return ExprError();
7576 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7577 PrepareScalarCast(Literal, ElemTy));
7578 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7579 }
7580
7581 initExprs.append(exprs, exprs + numExprs);
7582 }
7583 // FIXME: This means that pretty-printing the final AST will produce curly
7584 // braces instead of the original commas.
7585 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7586 initExprs, LiteralRParenLoc);
7587 initE->setType(Ty);
7588 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7589 }
7590
7591 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
7592 /// the ParenListExpr into a sequence of comma binary operators.
7593 ExprResult
MaybeConvertParenListExprToParenExpr(Scope * S,Expr * OrigExpr)7594 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
7595 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7596 if (!E)
7597 return OrigExpr;
7598
7599 ExprResult Result(E->getExpr(0));
7600
7601 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7602 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7603 E->getExpr(i));
7604
7605 if (Result.isInvalid()) return ExprError();
7606
7607 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7608 }
7609
ActOnParenListExpr(SourceLocation L,SourceLocation R,MultiExprArg Val)7610 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
7611 SourceLocation R,
7612 MultiExprArg Val) {
7613 return ParenListExpr::Create(Context, L, Val, R);
7614 }
7615
7616 /// Emit a specialized diagnostic when one expression is a null pointer
7617 /// constant and the other is not a pointer. Returns true if a diagnostic is
7618 /// emitted.
DiagnoseConditionalForNull(Expr * LHSExpr,Expr * RHSExpr,SourceLocation QuestionLoc)7619 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
7620 SourceLocation QuestionLoc) {
7621 Expr *NullExpr = LHSExpr;
7622 Expr *NonPointerExpr = RHSExpr;
7623 Expr::NullPointerConstantKind NullKind =
7624 NullExpr->isNullPointerConstant(Context,
7625 Expr::NPC_ValueDependentIsNotNull);
7626
7627 if (NullKind == Expr::NPCK_NotNull) {
7628 NullExpr = RHSExpr;
7629 NonPointerExpr = LHSExpr;
7630 NullKind =
7631 NullExpr->isNullPointerConstant(Context,
7632 Expr::NPC_ValueDependentIsNotNull);
7633 }
7634
7635 if (NullKind == Expr::NPCK_NotNull)
7636 return false;
7637
7638 if (NullKind == Expr::NPCK_ZeroExpression)
7639 return false;
7640
7641 if (NullKind == Expr::NPCK_ZeroLiteral) {
7642 // In this case, check to make sure that we got here from a "NULL"
7643 // string in the source code.
7644 NullExpr = NullExpr->IgnoreParenImpCasts();
7645 SourceLocation loc = NullExpr->getExprLoc();
7646 if (!findMacroSpelling(loc, "NULL"))
7647 return false;
7648 }
7649
7650 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7651 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7652 << NonPointerExpr->getType() << DiagType
7653 << NonPointerExpr->getSourceRange();
7654 return true;
7655 }
7656
7657 /// Return false if the condition expression is valid, true otherwise.
checkCondition(Sema & S,Expr * Cond,SourceLocation QuestionLoc)7658 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
7659 QualType CondTy = Cond->getType();
7660
7661 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7662 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7663 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7664 << CondTy << Cond->getSourceRange();
7665 return true;
7666 }
7667
7668 // C99 6.5.15p2
7669 if (CondTy->isScalarType()) return false;
7670
7671 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7672 << CondTy << Cond->getSourceRange();
7673 return true;
7674 }
7675
7676 /// Handle when one or both operands are void type.
checkConditionalVoidType(Sema & S,ExprResult & LHS,ExprResult & RHS)7677 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
7678 ExprResult &RHS) {
7679 Expr *LHSExpr = LHS.get();
7680 Expr *RHSExpr = RHS.get();
7681
7682 if (!LHSExpr->getType()->isVoidType())
7683 S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7684 << RHSExpr->getSourceRange();
7685 if (!RHSExpr->getType()->isVoidType())
7686 S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
7687 << LHSExpr->getSourceRange();
7688 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
7689 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
7690 return S.Context.VoidTy;
7691 }
7692
7693 /// Return false if the NullExpr can be promoted to PointerTy,
7694 /// true otherwise.
checkConditionalNullPointer(Sema & S,ExprResult & NullExpr,QualType PointerTy)7695 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
7696 QualType PointerTy) {
7697 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7698 !NullExpr.get()->isNullPointerConstant(S.Context,
7699 Expr::NPC_ValueDependentIsNull))
7700 return true;
7701
7702 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7703 return false;
7704 }
7705
7706 /// Checks compatibility between two pointers and return the resulting
7707 /// type.
checkConditionalPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)7708 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
7709 ExprResult &RHS,
7710 SourceLocation Loc) {
7711 QualType LHSTy = LHS.get()->getType();
7712 QualType RHSTy = RHS.get()->getType();
7713
7714 if (S.Context.hasSameType(LHSTy, RHSTy)) {
7715 // Two identical pointers types are always compatible.
7716 return LHSTy;
7717 }
7718
7719 QualType lhptee, rhptee;
7720
7721 // Get the pointee types.
7722 bool IsBlockPointer = false;
7723 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7724 lhptee = LHSBTy->getPointeeType();
7725 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7726 IsBlockPointer = true;
7727 } else {
7728 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7729 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7730 }
7731
7732 // C99 6.5.15p6: If both operands are pointers to compatible types or to
7733 // differently qualified versions of compatible types, the result type is
7734 // a pointer to an appropriately qualified version of the composite
7735 // type.
7736
7737 // Only CVR-qualifiers exist in the standard, and the differently-qualified
7738 // clause doesn't make sense for our extensions. E.g. address space 2 should
7739 // be incompatible with address space 3: they may live on different devices or
7740 // anything.
7741 Qualifiers lhQual = lhptee.getQualifiers();
7742 Qualifiers rhQual = rhptee.getQualifiers();
7743
7744 LangAS ResultAddrSpace = LangAS::Default;
7745 LangAS LAddrSpace = lhQual.getAddressSpace();
7746 LangAS RAddrSpace = rhQual.getAddressSpace();
7747
7748 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7749 // spaces is disallowed.
7750 if (lhQual.isAddressSpaceSupersetOf(rhQual))
7751 ResultAddrSpace = LAddrSpace;
7752 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7753 ResultAddrSpace = RAddrSpace;
7754 else {
7755 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7756 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7757 << RHS.get()->getSourceRange();
7758 return QualType();
7759 }
7760
7761 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7762 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7763 lhQual.removeCVRQualifiers();
7764 rhQual.removeCVRQualifiers();
7765
7766 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7767 // (C99 6.7.3) for address spaces. We assume that the check should behave in
7768 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7769 // qual types are compatible iff
7770 // * corresponded types are compatible
7771 // * CVR qualifiers are equal
7772 // * address spaces are equal
7773 // Thus for conditional operator we merge CVR and address space unqualified
7774 // pointees and if there is a composite type we return a pointer to it with
7775 // merged qualifiers.
7776 LHSCastKind =
7777 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7778 RHSCastKind =
7779 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7780 lhQual.removeAddressSpace();
7781 rhQual.removeAddressSpace();
7782
7783 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7784 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7785
7786 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
7787
7788 if (CompositeTy.isNull()) {
7789 // In this situation, we assume void* type. No especially good
7790 // reason, but this is what gcc does, and we do have to pick
7791 // to get a consistent AST.
7792 QualType incompatTy;
7793 incompatTy = S.Context.getPointerType(
7794 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7795 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7796 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7797
7798 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7799 // for casts between types with incompatible address space qualifiers.
7800 // For the following code the compiler produces casts between global and
7801 // local address spaces of the corresponded innermost pointees:
7802 // local int *global *a;
7803 // global int *global *b;
7804 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
7805 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
7806 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7807 << RHS.get()->getSourceRange();
7808
7809 return incompatTy;
7810 }
7811
7812 // The pointer types are compatible.
7813 // In case of OpenCL ResultTy should have the address space qualifier
7814 // which is a superset of address spaces of both the 2nd and the 3rd
7815 // operands of the conditional operator.
7816 QualType ResultTy = [&, ResultAddrSpace]() {
7817 if (S.getLangOpts().OpenCL) {
7818 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
7819 CompositeQuals.setAddressSpace(ResultAddrSpace);
7820 return S.Context
7821 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
7822 .withCVRQualifiers(MergedCVRQual);
7823 }
7824 return CompositeTy.withCVRQualifiers(MergedCVRQual);
7825 }();
7826 if (IsBlockPointer)
7827 ResultTy = S.Context.getBlockPointerType(ResultTy);
7828 else
7829 ResultTy = S.Context.getPointerType(ResultTy);
7830
7831 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
7832 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
7833 return ResultTy;
7834 }
7835
7836 /// Return the resulting type when the operands are both block pointers.
checkConditionalBlockPointerCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)7837 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
7838 ExprResult &LHS,
7839 ExprResult &RHS,
7840 SourceLocation Loc) {
7841 QualType LHSTy = LHS.get()->getType();
7842 QualType RHSTy = RHS.get()->getType();
7843
7844 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
7845 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
7846 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
7847 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7848 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7849 return destType;
7850 }
7851 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
7852 << LHSTy << RHSTy << LHS.get()->getSourceRange()
7853 << RHS.get()->getSourceRange();
7854 return QualType();
7855 }
7856
7857 // We have 2 block pointer types.
7858 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7859 }
7860
7861 /// Return the resulting type when the operands are both pointers.
7862 static QualType
checkConditionalObjectPointersCompatibility(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)7863 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
7864 ExprResult &RHS,
7865 SourceLocation Loc) {
7866 // get the pointer types
7867 QualType LHSTy = LHS.get()->getType();
7868 QualType RHSTy = RHS.get()->getType();
7869
7870 // get the "pointed to" types
7871 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7872 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7873
7874 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
7875 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
7876 // Figure out necessary qualifiers (C99 6.5.15p6)
7877 QualType destPointee
7878 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7879 QualType destType = S.Context.getPointerType(destPointee);
7880 // Add qualifiers if necessary.
7881 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7882 // Promote to void*.
7883 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7884 return destType;
7885 }
7886 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
7887 QualType destPointee
7888 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7889 QualType destType = S.Context.getPointerType(destPointee);
7890 // Add qualifiers if necessary.
7891 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7892 // Promote to void*.
7893 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7894 return destType;
7895 }
7896
7897 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
7898 }
7899
7900 /// Return false if the first expression is not an integer and the second
7901 /// expression is not a pointer, true otherwise.
checkPointerIntegerMismatch(Sema & S,ExprResult & Int,Expr * PointerExpr,SourceLocation Loc,bool IsIntFirstExpr)7902 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
7903 Expr* PointerExpr, SourceLocation Loc,
7904 bool IsIntFirstExpr) {
7905 if (!PointerExpr->getType()->isPointerType() ||
7906 !Int.get()->getType()->isIntegerType())
7907 return false;
7908
7909 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
7910 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
7911
7912 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
7913 << Expr1->getType() << Expr2->getType()
7914 << Expr1->getSourceRange() << Expr2->getSourceRange();
7915 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
7916 CK_IntegralToPointer);
7917 return true;
7918 }
7919
7920 /// Simple conversion between integer and floating point types.
7921 ///
7922 /// Used when handling the OpenCL conditional operator where the
7923 /// condition is a vector while the other operands are scalar.
7924 ///
7925 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
7926 /// types are either integer or floating type. Between the two
7927 /// operands, the type with the higher rank is defined as the "result
7928 /// type". The other operand needs to be promoted to the same type. No
7929 /// other type promotion is allowed. We cannot use
7930 /// UsualArithmeticConversions() for this purpose, since it always
7931 /// promotes promotable types.
OpenCLArithmeticConversions(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)7932 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
7933 ExprResult &RHS,
7934 SourceLocation QuestionLoc) {
7935 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
7936 if (LHS.isInvalid())
7937 return QualType();
7938 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
7939 if (RHS.isInvalid())
7940 return QualType();
7941
7942 // For conversion purposes, we ignore any qualifiers.
7943 // For example, "const float" and "float" are equivalent.
7944 QualType LHSType =
7945 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
7946 QualType RHSType =
7947 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
7948
7949 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
7950 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7951 << LHSType << LHS.get()->getSourceRange();
7952 return QualType();
7953 }
7954
7955 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
7956 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
7957 << RHSType << RHS.get()->getSourceRange();
7958 return QualType();
7959 }
7960
7961 // If both types are identical, no conversion is needed.
7962 if (LHSType == RHSType)
7963 return LHSType;
7964
7965 // Now handle "real" floating types (i.e. float, double, long double).
7966 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
7967 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
7968 /*IsCompAssign = */ false);
7969
7970 // Finally, we have two differing integer types.
7971 return handleIntegerConversion<doIntegralCast, doIntegralCast>
7972 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
7973 }
7974
7975 /// Convert scalar operands to a vector that matches the
7976 /// condition in length.
7977 ///
7978 /// Used when handling the OpenCL conditional operator where the
7979 /// condition is a vector while the other operands are scalar.
7980 ///
7981 /// We first compute the "result type" for the scalar operands
7982 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7983 /// into a vector of that type where the length matches the condition
7984 /// vector type. s6.11.6 requires that the element types of the result
7985 /// and the condition must have the same number of bits.
7986 static QualType
OpenCLConvertScalarsToVectors(Sema & S,ExprResult & LHS,ExprResult & RHS,QualType CondTy,SourceLocation QuestionLoc)7987 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7988 QualType CondTy, SourceLocation QuestionLoc) {
7989 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7990 if (ResTy.isNull()) return QualType();
7991
7992 const VectorType *CV = CondTy->getAs<VectorType>();
7993 assert(CV);
7994
7995 // Determine the vector result type
7996 unsigned NumElements = CV->getNumElements();
7997 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7998
7999 // Ensure that all types have the same number of bits
8000 if (S.Context.getTypeSize(CV->getElementType())
8001 != S.Context.getTypeSize(ResTy)) {
8002 // Since VectorTy is created internally, it does not pretty print
8003 // with an OpenCL name. Instead, we just print a description.
8004 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8005 SmallString<64> Str;
8006 llvm::raw_svector_ostream OS(Str);
8007 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8008 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8009 << CondTy << OS.str();
8010 return QualType();
8011 }
8012
8013 // Convert operands to the vector result type
8014 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8015 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8016
8017 return VectorTy;
8018 }
8019
8020 /// Return false if this is a valid OpenCL condition vector
checkOpenCLConditionVector(Sema & S,Expr * Cond,SourceLocation QuestionLoc)8021 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
8022 SourceLocation QuestionLoc) {
8023 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8024 // integral type.
8025 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8026 assert(CondTy);
8027 QualType EleTy = CondTy->getElementType();
8028 if (EleTy->isIntegerType()) return false;
8029
8030 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8031 << Cond->getType() << Cond->getSourceRange();
8032 return true;
8033 }
8034
8035 /// Return false if the vector condition type and the vector
8036 /// result type are compatible.
8037 ///
8038 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8039 /// number of elements, and their element types have the same number
8040 /// of bits.
checkVectorResult(Sema & S,QualType CondTy,QualType VecResTy,SourceLocation QuestionLoc)8041 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8042 SourceLocation QuestionLoc) {
8043 const VectorType *CV = CondTy->getAs<VectorType>();
8044 const VectorType *RV = VecResTy->getAs<VectorType>();
8045 assert(CV && RV);
8046
8047 if (CV->getNumElements() != RV->getNumElements()) {
8048 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8049 << CondTy << VecResTy;
8050 return true;
8051 }
8052
8053 QualType CVE = CV->getElementType();
8054 QualType RVE = RV->getElementType();
8055
8056 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8057 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8058 << CondTy << VecResTy;
8059 return true;
8060 }
8061
8062 return false;
8063 }
8064
8065 /// Return the resulting type for the conditional operator in
8066 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
8067 /// s6.3.i) when the condition is a vector type.
8068 static QualType
OpenCLCheckVectorConditional(Sema & S,ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)8069 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8070 ExprResult &LHS, ExprResult &RHS,
8071 SourceLocation QuestionLoc) {
8072 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
8073 if (Cond.isInvalid())
8074 return QualType();
8075 QualType CondTy = Cond.get()->getType();
8076
8077 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8078 return QualType();
8079
8080 // If either operand is a vector then find the vector type of the
8081 // result as specified in OpenCL v1.1 s6.3.i.
8082 if (LHS.get()->getType()->isVectorType() ||
8083 RHS.get()->getType()->isVectorType()) {
8084 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8085 /*isCompAssign*/false,
8086 /*AllowBothBool*/true,
8087 /*AllowBoolConversions*/false);
8088 if (VecResTy.isNull()) return QualType();
8089 // The result type must match the condition type as specified in
8090 // OpenCL v1.1 s6.11.6.
8091 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8092 return QualType();
8093 return VecResTy;
8094 }
8095
8096 // Both operands are scalar.
8097 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8098 }
8099
8100 /// Return true if the Expr is block type
checkBlockType(Sema & S,const Expr * E)8101 static bool checkBlockType(Sema &S, const Expr *E) {
8102 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8103 QualType Ty = CE->getCallee()->getType();
8104 if (Ty->isBlockPointerType()) {
8105 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8106 return true;
8107 }
8108 }
8109 return false;
8110 }
8111
8112 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8113 /// In that case, LHS = cond.
8114 /// C99 6.5.15
CheckConditionalOperands(ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation QuestionLoc)8115 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8116 ExprResult &RHS, ExprValueKind &VK,
8117 ExprObjectKind &OK,
8118 SourceLocation QuestionLoc) {
8119
8120 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8121 if (!LHSResult.isUsable()) return QualType();
8122 LHS = LHSResult;
8123
8124 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8125 if (!RHSResult.isUsable()) return QualType();
8126 RHS = RHSResult;
8127
8128 // C++ is sufficiently different to merit its own checker.
8129 if (getLangOpts().CPlusPlus)
8130 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8131
8132 VK = VK_RValue;
8133 OK = OK_Ordinary;
8134
8135 if (Context.isDependenceAllowed() &&
8136 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8137 RHS.get()->isTypeDependent())) {
8138 assert(!getLangOpts().CPlusPlus);
8139 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8140 RHS.get()->containsErrors()) &&
8141 "should only occur in error-recovery path.");
8142 return Context.DependentTy;
8143 }
8144
8145 // The OpenCL operator with a vector condition is sufficiently
8146 // different to merit its own checker.
8147 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8148 Cond.get()->getType()->isExtVectorType())
8149 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8150
8151 // First, check the condition.
8152 Cond = UsualUnaryConversions(Cond.get());
8153 if (Cond.isInvalid())
8154 return QualType();
8155 if (checkCondition(*this, Cond.get(), QuestionLoc))
8156 return QualType();
8157
8158 // Now check the two expressions.
8159 if (LHS.get()->getType()->isVectorType() ||
8160 RHS.get()->getType()->isVectorType())
8161 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
8162 /*AllowBothBool*/true,
8163 /*AllowBoolConversions*/false);
8164
8165 QualType ResTy =
8166 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8167 if (LHS.isInvalid() || RHS.isInvalid())
8168 return QualType();
8169
8170 QualType LHSTy = LHS.get()->getType();
8171 QualType RHSTy = RHS.get()->getType();
8172
8173 // Diagnose attempts to convert between __float128 and long double where
8174 // such conversions currently can't be handled.
8175 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8176 Diag(QuestionLoc,
8177 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8178 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8179 return QualType();
8180 }
8181
8182 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8183 // selection operator (?:).
8184 if (getLangOpts().OpenCL &&
8185 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
8186 return QualType();
8187 }
8188
8189 // If both operands have arithmetic type, do the usual arithmetic conversions
8190 // to find a common type: C99 6.5.15p3,5.
8191 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8192 // Disallow invalid arithmetic conversions, such as those between ExtInts of
8193 // different sizes, or between ExtInts and other types.
8194 if (ResTy.isNull() && (LHSTy->isExtIntType() || RHSTy->isExtIntType())) {
8195 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8196 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8197 << RHS.get()->getSourceRange();
8198 return QualType();
8199 }
8200
8201 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8202 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8203
8204 return ResTy;
8205 }
8206
8207 // And if they're both bfloat (which isn't arithmetic), that's fine too.
8208 if (LHSTy->isBFloat16Type() && RHSTy->isBFloat16Type()) {
8209 return LHSTy;
8210 }
8211
8212 // If both operands are the same structure or union type, the result is that
8213 // type.
8214 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8215 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8216 if (LHSRT->getDecl() == RHSRT->getDecl())
8217 // "If both the operands have structure or union type, the result has
8218 // that type." This implies that CV qualifiers are dropped.
8219 return LHSTy.getUnqualifiedType();
8220 // FIXME: Type of conditional expression must be complete in C mode.
8221 }
8222
8223 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8224 // The following || allows only one side to be void (a GCC-ism).
8225 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8226 return checkConditionalVoidType(*this, LHS, RHS);
8227 }
8228
8229 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8230 // the type of the other operand."
8231 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8232 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8233
8234 // All objective-c pointer type analysis is done here.
8235 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8236 QuestionLoc);
8237 if (LHS.isInvalid() || RHS.isInvalid())
8238 return QualType();
8239 if (!compositeType.isNull())
8240 return compositeType;
8241
8242
8243 // Handle block pointer types.
8244 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8245 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8246 QuestionLoc);
8247
8248 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8249 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8250 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8251 QuestionLoc);
8252
8253 // GCC compatibility: soften pointer/integer mismatch. Note that
8254 // null pointers have been filtered out by this point.
8255 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8256 /*IsIntFirstExpr=*/true))
8257 return RHSTy;
8258 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8259 /*IsIntFirstExpr=*/false))
8260 return LHSTy;
8261
8262 // Allow ?: operations in which both operands have the same
8263 // built-in sizeless type.
8264 if (LHSTy->isSizelessBuiltinType() && LHSTy == RHSTy)
8265 return LHSTy;
8266
8267 // Emit a better diagnostic if one of the expressions is a null pointer
8268 // constant and the other is not a pointer type. In this case, the user most
8269 // likely forgot to take the address of the other expression.
8270 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8271 return QualType();
8272
8273 // Otherwise, the operands are not compatible.
8274 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8275 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8276 << RHS.get()->getSourceRange();
8277 return QualType();
8278 }
8279
8280 /// FindCompositeObjCPointerType - Helper method to find composite type of
8281 /// two objective-c pointer types of the two input expressions.
FindCompositeObjCPointerType(ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)8282 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
8283 SourceLocation QuestionLoc) {
8284 QualType LHSTy = LHS.get()->getType();
8285 QualType RHSTy = RHS.get()->getType();
8286
8287 // Handle things like Class and struct objc_class*. Here we case the result
8288 // to the pseudo-builtin, because that will be implicitly cast back to the
8289 // redefinition type if an attempt is made to access its fields.
8290 if (LHSTy->isObjCClassType() &&
8291 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
8292 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8293 return LHSTy;
8294 }
8295 if (RHSTy->isObjCClassType() &&
8296 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
8297 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8298 return RHSTy;
8299 }
8300 // And the same for struct objc_object* / id
8301 if (LHSTy->isObjCIdType() &&
8302 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
8303 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8304 return LHSTy;
8305 }
8306 if (RHSTy->isObjCIdType() &&
8307 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
8308 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8309 return RHSTy;
8310 }
8311 // And the same for struct objc_selector* / SEL
8312 if (Context.isObjCSelType(LHSTy) &&
8313 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
8314 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8315 return LHSTy;
8316 }
8317 if (Context.isObjCSelType(RHSTy) &&
8318 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
8319 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8320 return RHSTy;
8321 }
8322 // Check constraints for Objective-C object pointers types.
8323 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8324
8325 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8326 // Two identical object pointer types are always compatible.
8327 return LHSTy;
8328 }
8329 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8330 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8331 QualType compositeType = LHSTy;
8332
8333 // If both operands are interfaces and either operand can be
8334 // assigned to the other, use that type as the composite
8335 // type. This allows
8336 // xxx ? (A*) a : (B*) b
8337 // where B is a subclass of A.
8338 //
8339 // Additionally, as for assignment, if either type is 'id'
8340 // allow silent coercion. Finally, if the types are
8341 // incompatible then make sure to use 'id' as the composite
8342 // type so the result is acceptable for sending messages to.
8343
8344 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8345 // It could return the composite type.
8346 if (!(compositeType =
8347 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8348 // Nothing more to do.
8349 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8350 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8351 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8352 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8353 } else if ((LHSOPT->isObjCQualifiedIdType() ||
8354 RHSOPT->isObjCQualifiedIdType()) &&
8355 Context.ObjCQualifiedIdTypesAreCompatible(LHSOPT, RHSOPT,
8356 true)) {
8357 // Need to handle "id<xx>" explicitly.
8358 // GCC allows qualified id and any Objective-C type to devolve to
8359 // id. Currently localizing to here until clear this should be
8360 // part of ObjCQualifiedIdTypesAreCompatible.
8361 compositeType = Context.getObjCIdType();
8362 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8363 compositeType = Context.getObjCIdType();
8364 } else {
8365 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8366 << LHSTy << RHSTy
8367 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8368 QualType incompatTy = Context.getObjCIdType();
8369 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8370 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8371 return incompatTy;
8372 }
8373 // The object pointer types are compatible.
8374 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8375 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8376 return compositeType;
8377 }
8378 // Check Objective-C object pointer types and 'void *'
8379 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8380 if (getLangOpts().ObjCAutoRefCount) {
8381 // ARC forbids the implicit conversion of object pointers to 'void *',
8382 // so these types are not compatible.
8383 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8384 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8385 LHS = RHS = true;
8386 return QualType();
8387 }
8388 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8389 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8390 QualType destPointee
8391 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8392 QualType destType = Context.getPointerType(destPointee);
8393 // Add qualifiers if necessary.
8394 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8395 // Promote to void*.
8396 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8397 return destType;
8398 }
8399 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8400 if (getLangOpts().ObjCAutoRefCount) {
8401 // ARC forbids the implicit conversion of object pointers to 'void *',
8402 // so these types are not compatible.
8403 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8404 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8405 LHS = RHS = true;
8406 return QualType();
8407 }
8408 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8409 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8410 QualType destPointee
8411 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8412 QualType destType = Context.getPointerType(destPointee);
8413 // Add qualifiers if necessary.
8414 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8415 // Promote to void*.
8416 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8417 return destType;
8418 }
8419 return QualType();
8420 }
8421
8422 /// SuggestParentheses - Emit a note with a fixit hint that wraps
8423 /// ParenRange in parentheses.
SuggestParentheses(Sema & Self,SourceLocation Loc,const PartialDiagnostic & Note,SourceRange ParenRange)8424 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8425 const PartialDiagnostic &Note,
8426 SourceRange ParenRange) {
8427 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8428 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8429 EndLoc.isValid()) {
8430 Self.Diag(Loc, Note)
8431 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8432 << FixItHint::CreateInsertion(EndLoc, ")");
8433 } else {
8434 // We can't display the parentheses, so just show the bare note.
8435 Self.Diag(Loc, Note) << ParenRange;
8436 }
8437 }
8438
IsArithmeticOp(BinaryOperatorKind Opc)8439 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8440 return BinaryOperator::isAdditiveOp(Opc) ||
8441 BinaryOperator::isMultiplicativeOp(Opc) ||
8442 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8443 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8444 // not any of the logical operators. Bitwise-xor is commonly used as a
8445 // logical-xor because there is no logical-xor operator. The logical
8446 // operators, including uses of xor, have a high false positive rate for
8447 // precedence warnings.
8448 }
8449
8450 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8451 /// expression, either using a built-in or overloaded operator,
8452 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8453 /// expression.
IsArithmeticBinaryExpr(Expr * E,BinaryOperatorKind * Opcode,Expr ** RHSExprs)8454 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
8455 Expr **RHSExprs) {
8456 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8457 E = E->IgnoreImpCasts();
8458 E = E->IgnoreConversionOperatorSingleStep();
8459 E = E->IgnoreImpCasts();
8460 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8461 E = MTE->getSubExpr();
8462 E = E->IgnoreImpCasts();
8463 }
8464
8465 // Built-in binary operator.
8466 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
8467 if (IsArithmeticOp(OP->getOpcode())) {
8468 *Opcode = OP->getOpcode();
8469 *RHSExprs = OP->getRHS();
8470 return true;
8471 }
8472 }
8473
8474 // Overloaded operator.
8475 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8476 if (Call->getNumArgs() != 2)
8477 return false;
8478
8479 // Make sure this is really a binary operator that is safe to pass into
8480 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8481 OverloadedOperatorKind OO = Call->getOperator();
8482 if (OO < OO_Plus || OO > OO_Arrow ||
8483 OO == OO_PlusPlus || OO == OO_MinusMinus)
8484 return false;
8485
8486 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
8487 if (IsArithmeticOp(OpKind)) {
8488 *Opcode = OpKind;
8489 *RHSExprs = Call->getArg(1);
8490 return true;
8491 }
8492 }
8493
8494 return false;
8495 }
8496
8497 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8498 /// or is a logical expression such as (x==y) which has int type, but is
8499 /// commonly interpreted as boolean.
ExprLooksBoolean(Expr * E)8500 static bool ExprLooksBoolean(Expr *E) {
8501 E = E->IgnoreParenImpCasts();
8502
8503 if (E->getType()->isBooleanType())
8504 return true;
8505 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
8506 return OP->isComparisonOp() || OP->isLogicalOp();
8507 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
8508 return OP->getOpcode() == UO_LNot;
8509 if (E->getType()->isPointerType())
8510 return true;
8511 // FIXME: What about overloaded operator calls returning "unspecified boolean
8512 // type"s (commonly pointer-to-members)?
8513
8514 return false;
8515 }
8516
8517 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8518 /// and binary operator are mixed in a way that suggests the programmer assumed
8519 /// the conditional operator has higher precedence, for example:
8520 /// "int x = a + someBinaryCondition ? 1 : 2".
DiagnoseConditionalPrecedence(Sema & Self,SourceLocation OpLoc,Expr * Condition,Expr * LHSExpr,Expr * RHSExpr)8521 static void DiagnoseConditionalPrecedence(Sema &Self,
8522 SourceLocation OpLoc,
8523 Expr *Condition,
8524 Expr *LHSExpr,
8525 Expr *RHSExpr) {
8526 BinaryOperatorKind CondOpcode;
8527 Expr *CondRHS;
8528
8529 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8530 return;
8531 if (!ExprLooksBoolean(CondRHS))
8532 return;
8533
8534 // The condition is an arithmetic binary expression, with a right-
8535 // hand side that looks boolean, so warn.
8536
8537 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8538 ? diag::warn_precedence_bitwise_conditional
8539 : diag::warn_precedence_conditional;
8540
8541 Self.Diag(OpLoc, DiagID)
8542 << Condition->getSourceRange()
8543 << BinaryOperator::getOpcodeStr(CondOpcode);
8544
8545 SuggestParentheses(
8546 Self, OpLoc,
8547 Self.PDiag(diag::note_precedence_silence)
8548 << BinaryOperator::getOpcodeStr(CondOpcode),
8549 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8550
8551 SuggestParentheses(Self, OpLoc,
8552 Self.PDiag(diag::note_precedence_conditional_first),
8553 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8554 }
8555
8556 /// Compute the nullability of a conditional expression.
computeConditionalNullability(QualType ResTy,bool IsBin,QualType LHSTy,QualType RHSTy,ASTContext & Ctx)8557 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
8558 QualType LHSTy, QualType RHSTy,
8559 ASTContext &Ctx) {
8560 if (!ResTy->isAnyPointerType())
8561 return ResTy;
8562
8563 auto GetNullability = [&Ctx](QualType Ty) {
8564 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
8565 if (Kind) {
8566 // For our purposes, treat _Nullable_result as _Nullable.
8567 if (*Kind == NullabilityKind::NullableResult)
8568 return NullabilityKind::Nullable;
8569 return *Kind;
8570 }
8571 return NullabilityKind::Unspecified;
8572 };
8573
8574 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8575 NullabilityKind MergedKind;
8576
8577 // Compute nullability of a binary conditional expression.
8578 if (IsBin) {
8579 if (LHSKind == NullabilityKind::NonNull)
8580 MergedKind = NullabilityKind::NonNull;
8581 else
8582 MergedKind = RHSKind;
8583 // Compute nullability of a normal conditional expression.
8584 } else {
8585 if (LHSKind == NullabilityKind::Nullable ||
8586 RHSKind == NullabilityKind::Nullable)
8587 MergedKind = NullabilityKind::Nullable;
8588 else if (LHSKind == NullabilityKind::NonNull)
8589 MergedKind = RHSKind;
8590 else if (RHSKind == NullabilityKind::NonNull)
8591 MergedKind = LHSKind;
8592 else
8593 MergedKind = NullabilityKind::Unspecified;
8594 }
8595
8596 // Return if ResTy already has the correct nullability.
8597 if (GetNullability(ResTy) == MergedKind)
8598 return ResTy;
8599
8600 // Strip all nullability from ResTy.
8601 while (ResTy->getNullability(Ctx))
8602 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8603
8604 // Create a new AttributedType with the new nullability kind.
8605 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8606 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8607 }
8608
8609 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
8610 /// in the case of a the GNU conditional expr extension.
ActOnConditionalOp(SourceLocation QuestionLoc,SourceLocation ColonLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr)8611 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
8612 SourceLocation ColonLoc,
8613 Expr *CondExpr, Expr *LHSExpr,
8614 Expr *RHSExpr) {
8615 if (!Context.isDependenceAllowed()) {
8616 // C cannot handle TypoExpr nodes in the condition because it
8617 // doesn't handle dependent types properly, so make sure any TypoExprs have
8618 // been dealt with before checking the operands.
8619 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8620 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8621 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8622
8623 if (!CondResult.isUsable())
8624 return ExprError();
8625
8626 if (LHSExpr) {
8627 if (!LHSResult.isUsable())
8628 return ExprError();
8629 }
8630
8631 if (!RHSResult.isUsable())
8632 return ExprError();
8633
8634 CondExpr = CondResult.get();
8635 LHSExpr = LHSResult.get();
8636 RHSExpr = RHSResult.get();
8637 }
8638
8639 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8640 // was the condition.
8641 OpaqueValueExpr *opaqueValue = nullptr;
8642 Expr *commonExpr = nullptr;
8643 if (!LHSExpr) {
8644 commonExpr = CondExpr;
8645 // Lower out placeholder types first. This is important so that we don't
8646 // try to capture a placeholder. This happens in few cases in C++; such
8647 // as Objective-C++'s dictionary subscripting syntax.
8648 if (commonExpr->hasPlaceholderType()) {
8649 ExprResult result = CheckPlaceholderExpr(commonExpr);
8650 if (!result.isUsable()) return ExprError();
8651 commonExpr = result.get();
8652 }
8653 // We usually want to apply unary conversions *before* saving, except
8654 // in the special case of a C++ l-value conditional.
8655 if (!(getLangOpts().CPlusPlus
8656 && !commonExpr->isTypeDependent()
8657 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8658 && commonExpr->isGLValue()
8659 && commonExpr->isOrdinaryOrBitFieldObject()
8660 && RHSExpr->isOrdinaryOrBitFieldObject()
8661 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8662 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8663 if (commonRes.isInvalid())
8664 return ExprError();
8665 commonExpr = commonRes.get();
8666 }
8667
8668 // If the common expression is a class or array prvalue, materialize it
8669 // so that we can safely refer to it multiple times.
8670 if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
8671 commonExpr->getType()->isArrayType())) {
8672 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8673 if (MatExpr.isInvalid())
8674 return ExprError();
8675 commonExpr = MatExpr.get();
8676 }
8677
8678 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8679 commonExpr->getType(),
8680 commonExpr->getValueKind(),
8681 commonExpr->getObjectKind(),
8682 commonExpr);
8683 LHSExpr = CondExpr = opaqueValue;
8684 }
8685
8686 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8687 ExprValueKind VK = VK_RValue;
8688 ExprObjectKind OK = OK_Ordinary;
8689 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8690 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8691 VK, OK, QuestionLoc);
8692 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8693 RHS.isInvalid())
8694 return ExprError();
8695
8696 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8697 RHS.get());
8698
8699 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8700
8701 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8702 Context);
8703
8704 if (!commonExpr)
8705 return new (Context)
8706 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8707 RHS.get(), result, VK, OK);
8708
8709 return new (Context) BinaryConditionalOperator(
8710 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8711 ColonLoc, result, VK, OK);
8712 }
8713
8714 // Check if we have a conversion between incompatible cmse function pointer
8715 // types, that is, a conversion between a function pointer with the
8716 // cmse_nonsecure_call attribute and one without.
IsInvalidCmseNSCallConversion(Sema & S,QualType FromType,QualType ToType)8717 static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
8718 QualType ToType) {
8719 if (const auto *ToFn =
8720 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8721 if (const auto *FromFn =
8722 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8723 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8724 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8725
8726 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8727 }
8728 }
8729 return false;
8730 }
8731
8732 // checkPointerTypesForAssignment - This is a very tricky routine (despite
8733 // being closely modeled after the C99 spec:-). The odd characteristic of this
8734 // routine is it effectively iqnores the qualifiers on the top level pointee.
8735 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8736 // FIXME: add a couple examples in this comment.
8737 static Sema::AssignConvertType
checkPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)8738 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
8739 assert(LHSType.isCanonical() && "LHS not canonicalized!");
8740 assert(RHSType.isCanonical() && "RHS not canonicalized!");
8741
8742 // get the "pointed to" type (ignoring qualifiers at the top level)
8743 const Type *lhptee, *rhptee;
8744 Qualifiers lhq, rhq;
8745 std::tie(lhptee, lhq) =
8746 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8747 std::tie(rhptee, rhq) =
8748 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8749
8750 Sema::AssignConvertType ConvTy = Sema::Compatible;
8751
8752 // C99 6.5.16.1p1: This following citation is common to constraints
8753 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8754 // qualifiers of the type *pointed to* by the right;
8755
8756 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8757 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8758 lhq.compatiblyIncludesObjCLifetime(rhq)) {
8759 // Ignore lifetime for further calculation.
8760 lhq.removeObjCLifetime();
8761 rhq.removeObjCLifetime();
8762 }
8763
8764 if (!lhq.compatiblyIncludes(rhq)) {
8765 // Treat address-space mismatches as fatal.
8766 if (!lhq.isAddressSpaceSupersetOf(rhq))
8767 return Sema::IncompatiblePointerDiscardsQualifiers;
8768
8769 // It's okay to add or remove GC or lifetime qualifiers when converting to
8770 // and from void*.
8771 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8772 .compatiblyIncludes(
8773 rhq.withoutObjCGCAttr().withoutObjCLifetime())
8774 && (lhptee->isVoidType() || rhptee->isVoidType()))
8775 ; // keep old
8776
8777 // Treat lifetime mismatches as fatal.
8778 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8779 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
8780
8781 // For GCC/MS compatibility, other qualifier mismatches are treated
8782 // as still compatible in C.
8783 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8784 }
8785
8786 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8787 // incomplete type and the other is a pointer to a qualified or unqualified
8788 // version of void...
8789 if (lhptee->isVoidType()) {
8790 if (rhptee->isIncompleteOrObjectType())
8791 return ConvTy;
8792
8793 // As an extension, we allow cast to/from void* to function pointer.
8794 assert(rhptee->isFunctionType());
8795 return Sema::FunctionVoidPointer;
8796 }
8797
8798 if (rhptee->isVoidType()) {
8799 if (lhptee->isIncompleteOrObjectType())
8800 return ConvTy;
8801
8802 // As an extension, we allow cast to/from void* to function pointer.
8803 assert(lhptee->isFunctionType());
8804 return Sema::FunctionVoidPointer;
8805 }
8806
8807 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8808 // unqualified versions of compatible types, ...
8809 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8810 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8811 // Check if the pointee types are compatible ignoring the sign.
8812 // We explicitly check for char so that we catch "char" vs
8813 // "unsigned char" on systems where "char" is unsigned.
8814 if (lhptee->isCharType())
8815 ltrans = S.Context.UnsignedCharTy;
8816 else if (lhptee->hasSignedIntegerRepresentation())
8817 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8818
8819 if (rhptee->isCharType())
8820 rtrans = S.Context.UnsignedCharTy;
8821 else if (rhptee->hasSignedIntegerRepresentation())
8822 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8823
8824 if (ltrans == rtrans) {
8825 // Types are compatible ignoring the sign. Qualifier incompatibility
8826 // takes priority over sign incompatibility because the sign
8827 // warning can be disabled.
8828 if (ConvTy != Sema::Compatible)
8829 return ConvTy;
8830
8831 return Sema::IncompatiblePointerSign;
8832 }
8833
8834 // If we are a multi-level pointer, it's possible that our issue is simply
8835 // one of qualification - e.g. char ** -> const char ** is not allowed. If
8836 // the eventual target type is the same and the pointers have the same
8837 // level of indirection, this must be the issue.
8838 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8839 do {
8840 std::tie(lhptee, lhq) =
8841 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8842 std::tie(rhptee, rhq) =
8843 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8844
8845 // Inconsistent address spaces at this point is invalid, even if the
8846 // address spaces would be compatible.
8847 // FIXME: This doesn't catch address space mismatches for pointers of
8848 // different nesting levels, like:
8849 // __local int *** a;
8850 // int ** b = a;
8851 // It's not clear how to actually determine when such pointers are
8852 // invalidly incompatible.
8853 if (lhq.getAddressSpace() != rhq.getAddressSpace())
8854 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
8855
8856 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8857
8858 if (lhptee == rhptee)
8859 return Sema::IncompatibleNestedPointerQualifiers;
8860 }
8861
8862 // General pointer incompatibility takes priority over qualifiers.
8863 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8864 return Sema::IncompatibleFunctionPointer;
8865 return Sema::IncompatiblePointer;
8866 }
8867 if (!S.getLangOpts().CPlusPlus &&
8868 S.IsFunctionConversion(ltrans, rtrans, ltrans))
8869 return Sema::IncompatibleFunctionPointer;
8870 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8871 return Sema::IncompatibleFunctionPointer;
8872 return ConvTy;
8873 }
8874
8875 /// checkBlockPointerTypesForAssignment - This routine determines whether two
8876 /// block pointer types are compatible or whether a block and normal pointer
8877 /// are compatible. It is more restrict than comparing two function pointer
8878 // types.
8879 static Sema::AssignConvertType
checkBlockPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)8880 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
8881 QualType RHSType) {
8882 assert(LHSType.isCanonical() && "LHS not canonicalized!");
8883 assert(RHSType.isCanonical() && "RHS not canonicalized!");
8884
8885 QualType lhptee, rhptee;
8886
8887 // get the "pointed to" type (ignoring qualifiers at the top level)
8888 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8889 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8890
8891 // In C++, the types have to match exactly.
8892 if (S.getLangOpts().CPlusPlus)
8893 return Sema::IncompatibleBlockPointer;
8894
8895 Sema::AssignConvertType ConvTy = Sema::Compatible;
8896
8897 // For blocks we enforce that qualifiers are identical.
8898 Qualifiers LQuals = lhptee.getLocalQualifiers();
8899 Qualifiers RQuals = rhptee.getLocalQualifiers();
8900 if (S.getLangOpts().OpenCL) {
8901 LQuals.removeAddressSpace();
8902 RQuals.removeAddressSpace();
8903 }
8904 if (LQuals != RQuals)
8905 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
8906
8907 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
8908 // assignment.
8909 // The current behavior is similar to C++ lambdas. A block might be
8910 // assigned to a variable iff its return type and parameters are compatible
8911 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
8912 // an assignment. Presumably it should behave in way that a function pointer
8913 // assignment does in C, so for each parameter and return type:
8914 // * CVR and address space of LHS should be a superset of CVR and address
8915 // space of RHS.
8916 // * unqualified types should be compatible.
8917 if (S.getLangOpts().OpenCL) {
8918 if (!S.Context.typesAreBlockPointerCompatible(
8919 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
8920 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
8921 return Sema::IncompatibleBlockPointer;
8922 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
8923 return Sema::IncompatibleBlockPointer;
8924
8925 return ConvTy;
8926 }
8927
8928 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
8929 /// for assignment compatibility.
8930 static Sema::AssignConvertType
checkObjCPointerTypesForAssignment(Sema & S,QualType LHSType,QualType RHSType)8931 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
8932 QualType RHSType) {
8933 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
8934 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
8935
8936 if (LHSType->isObjCBuiltinType()) {
8937 // Class is not compatible with ObjC object pointers.
8938 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
8939 !RHSType->isObjCQualifiedClassType())
8940 return Sema::IncompatiblePointer;
8941 return Sema::Compatible;
8942 }
8943 if (RHSType->isObjCBuiltinType()) {
8944 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
8945 !LHSType->isObjCQualifiedClassType())
8946 return Sema::IncompatiblePointer;
8947 return Sema::Compatible;
8948 }
8949 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8950 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
8951
8952 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
8953 // make an exception for id<P>
8954 !LHSType->isObjCQualifiedIdType())
8955 return Sema::CompatiblePointerDiscardsQualifiers;
8956
8957 if (S.Context.typesAreCompatible(LHSType, RHSType))
8958 return Sema::Compatible;
8959 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
8960 return Sema::IncompatibleObjCQualifiedId;
8961 return Sema::IncompatiblePointer;
8962 }
8963
8964 Sema::AssignConvertType
CheckAssignmentConstraints(SourceLocation Loc,QualType LHSType,QualType RHSType)8965 Sema::CheckAssignmentConstraints(SourceLocation Loc,
8966 QualType LHSType, QualType RHSType) {
8967 // Fake up an opaque expression. We don't actually care about what
8968 // cast operations are required, so if CheckAssignmentConstraints
8969 // adds casts to this they'll be wasted, but fortunately that doesn't
8970 // usually happen on valid code.
8971 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
8972 ExprResult RHSPtr = &RHSExpr;
8973 CastKind K;
8974
8975 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
8976 }
8977
8978 /// This helper function returns true if QT is a vector type that has element
8979 /// type ElementType.
isVector(QualType QT,QualType ElementType)8980 static bool isVector(QualType QT, QualType ElementType) {
8981 if (const VectorType *VT = QT->getAs<VectorType>())
8982 return VT->getElementType().getCanonicalType() == ElementType;
8983 return false;
8984 }
8985
8986 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
8987 /// has code to accommodate several GCC extensions when type checking
8988 /// pointers. Here are some objectionable examples that GCC considers warnings:
8989 ///
8990 /// int a, *pint;
8991 /// short *pshort;
8992 /// struct foo *pfoo;
8993 ///
8994 /// pint = pshort; // warning: assignment from incompatible pointer type
8995 /// a = pint; // warning: assignment makes integer from pointer without a cast
8996 /// pint = a; // warning: assignment makes pointer from integer without a cast
8997 /// pint = pfoo; // warning: assignment from incompatible pointer type
8998 ///
8999 /// As a result, the code for dealing with pointers is more complex than the
9000 /// C99 spec dictates.
9001 ///
9002 /// Sets 'Kind' for any result kind except Incompatible.
9003 Sema::AssignConvertType
CheckAssignmentConstraints(QualType LHSType,ExprResult & RHS,CastKind & Kind,bool ConvertRHS)9004 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
9005 CastKind &Kind, bool ConvertRHS) {
9006 QualType RHSType = RHS.get()->getType();
9007 QualType OrigLHSType = LHSType;
9008
9009 // Get canonical types. We're not formatting these types, just comparing
9010 // them.
9011 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9012 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9013
9014 // Common case: no conversion required.
9015 if (LHSType == RHSType) {
9016 Kind = CK_NoOp;
9017 return Compatible;
9018 }
9019
9020 // If we have an atomic type, try a non-atomic assignment, then just add an
9021 // atomic qualification step.
9022 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9023 Sema::AssignConvertType result =
9024 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9025 if (result != Compatible)
9026 return result;
9027 if (Kind != CK_NoOp && ConvertRHS)
9028 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9029 Kind = CK_NonAtomicToAtomic;
9030 return Compatible;
9031 }
9032
9033 // If the left-hand side is a reference type, then we are in a
9034 // (rare!) case where we've allowed the use of references in C,
9035 // e.g., as a parameter type in a built-in function. In this case,
9036 // just make sure that the type referenced is compatible with the
9037 // right-hand side type. The caller is responsible for adjusting
9038 // LHSType so that the resulting expression does not have reference
9039 // type.
9040 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9041 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9042 Kind = CK_LValueBitCast;
9043 return Compatible;
9044 }
9045 return Incompatible;
9046 }
9047
9048 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9049 // to the same ExtVector type.
9050 if (LHSType->isExtVectorType()) {
9051 if (RHSType->isExtVectorType())
9052 return Incompatible;
9053 if (RHSType->isArithmeticType()) {
9054 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9055 if (ConvertRHS)
9056 RHS = prepareVectorSplat(LHSType, RHS.get());
9057 Kind = CK_VectorSplat;
9058 return Compatible;
9059 }
9060 }
9061
9062 // Conversions to or from vector type.
9063 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9064 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9065 // Allow assignments of an AltiVec vector type to an equivalent GCC
9066 // vector type and vice versa
9067 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9068 Kind = CK_BitCast;
9069 return Compatible;
9070 }
9071
9072 // If we are allowing lax vector conversions, and LHS and RHS are both
9073 // vectors, the total size only needs to be the same. This is a bitcast;
9074 // no bits are changed but the result type is different.
9075 if (isLaxVectorConversion(RHSType, LHSType)) {
9076 Kind = CK_BitCast;
9077 return IncompatibleVectors;
9078 }
9079 }
9080
9081 // When the RHS comes from another lax conversion (e.g. binops between
9082 // scalars and vectors) the result is canonicalized as a vector. When the
9083 // LHS is also a vector, the lax is allowed by the condition above. Handle
9084 // the case where LHS is a scalar.
9085 if (LHSType->isScalarType()) {
9086 const VectorType *VecType = RHSType->getAs<VectorType>();
9087 if (VecType && VecType->getNumElements() == 1 &&
9088 isLaxVectorConversion(RHSType, LHSType)) {
9089 ExprResult *VecExpr = &RHS;
9090 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9091 Kind = CK_BitCast;
9092 return Compatible;
9093 }
9094 }
9095
9096 // Allow assignments between fixed-length and sizeless SVE vectors.
9097 if ((LHSType->isSizelessBuiltinType() && RHSType->isVectorType()) ||
9098 (LHSType->isVectorType() && RHSType->isSizelessBuiltinType()))
9099 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9100 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9101 Kind = CK_BitCast;
9102 return Compatible;
9103 }
9104
9105 return Incompatible;
9106 }
9107
9108 // Diagnose attempts to convert between __float128 and long double where
9109 // such conversions currently can't be handled.
9110 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9111 return Incompatible;
9112
9113 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9114 // discards the imaginary part.
9115 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9116 !LHSType->getAs<ComplexType>())
9117 return Incompatible;
9118
9119 // Arithmetic conversions.
9120 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9121 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9122 if (ConvertRHS)
9123 Kind = PrepareScalarCast(RHS, LHSType);
9124 return Compatible;
9125 }
9126
9127 // Conversions to normal pointers.
9128 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9129 // U* -> T*
9130 if (isa<PointerType>(RHSType)) {
9131 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9132 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9133 if (AddrSpaceL != AddrSpaceR)
9134 Kind = CK_AddressSpaceConversion;
9135 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9136 Kind = CK_NoOp;
9137 else
9138 Kind = CK_BitCast;
9139 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
9140 }
9141
9142 // int -> T*
9143 if (RHSType->isIntegerType()) {
9144 Kind = CK_IntegralToPointer; // FIXME: null?
9145 return IntToPointer;
9146 }
9147
9148 // C pointers are not compatible with ObjC object pointers,
9149 // with two exceptions:
9150 if (isa<ObjCObjectPointerType>(RHSType)) {
9151 // - conversions to void*
9152 if (LHSPointer->getPointeeType()->isVoidType()) {
9153 Kind = CK_BitCast;
9154 return Compatible;
9155 }
9156
9157 // - conversions from 'Class' to the redefinition type
9158 if (RHSType->isObjCClassType() &&
9159 Context.hasSameType(LHSType,
9160 Context.getObjCClassRedefinitionType())) {
9161 Kind = CK_BitCast;
9162 return Compatible;
9163 }
9164
9165 Kind = CK_BitCast;
9166 return IncompatiblePointer;
9167 }
9168
9169 // U^ -> void*
9170 if (RHSType->getAs<BlockPointerType>()) {
9171 if (LHSPointer->getPointeeType()->isVoidType()) {
9172 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9173 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9174 ->getPointeeType()
9175 .getAddressSpace();
9176 Kind =
9177 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9178 return Compatible;
9179 }
9180 }
9181
9182 return Incompatible;
9183 }
9184
9185 // Conversions to block pointers.
9186 if (isa<BlockPointerType>(LHSType)) {
9187 // U^ -> T^
9188 if (RHSType->isBlockPointerType()) {
9189 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9190 ->getPointeeType()
9191 .getAddressSpace();
9192 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9193 ->getPointeeType()
9194 .getAddressSpace();
9195 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9196 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9197 }
9198
9199 // int or null -> T^
9200 if (RHSType->isIntegerType()) {
9201 Kind = CK_IntegralToPointer; // FIXME: null
9202 return IntToBlockPointer;
9203 }
9204
9205 // id -> T^
9206 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9207 Kind = CK_AnyPointerToBlockPointerCast;
9208 return Compatible;
9209 }
9210
9211 // void* -> T^
9212 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9213 if (RHSPT->getPointeeType()->isVoidType()) {
9214 Kind = CK_AnyPointerToBlockPointerCast;
9215 return Compatible;
9216 }
9217
9218 return Incompatible;
9219 }
9220
9221 // Conversions to Objective-C pointers.
9222 if (isa<ObjCObjectPointerType>(LHSType)) {
9223 // A* -> B*
9224 if (RHSType->isObjCObjectPointerType()) {
9225 Kind = CK_BitCast;
9226 Sema::AssignConvertType result =
9227 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9228 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9229 result == Compatible &&
9230 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9231 result = IncompatibleObjCWeakRef;
9232 return result;
9233 }
9234
9235 // int or null -> A*
9236 if (RHSType->isIntegerType()) {
9237 Kind = CK_IntegralToPointer; // FIXME: null
9238 return IntToPointer;
9239 }
9240
9241 // In general, C pointers are not compatible with ObjC object pointers,
9242 // with two exceptions:
9243 if (isa<PointerType>(RHSType)) {
9244 Kind = CK_CPointerToObjCPointerCast;
9245
9246 // - conversions from 'void*'
9247 if (RHSType->isVoidPointerType()) {
9248 return Compatible;
9249 }
9250
9251 // - conversions to 'Class' from its redefinition type
9252 if (LHSType->isObjCClassType() &&
9253 Context.hasSameType(RHSType,
9254 Context.getObjCClassRedefinitionType())) {
9255 return Compatible;
9256 }
9257
9258 return IncompatiblePointer;
9259 }
9260
9261 // Only under strict condition T^ is compatible with an Objective-C pointer.
9262 if (RHSType->isBlockPointerType() &&
9263 LHSType->isBlockCompatibleObjCPointerType(Context)) {
9264 if (ConvertRHS)
9265 maybeExtendBlockObject(RHS);
9266 Kind = CK_BlockPointerToObjCPointerCast;
9267 return Compatible;
9268 }
9269
9270 return Incompatible;
9271 }
9272
9273 // Conversions from pointers that are not covered by the above.
9274 if (isa<PointerType>(RHSType)) {
9275 // T* -> _Bool
9276 if (LHSType == Context.BoolTy) {
9277 Kind = CK_PointerToBoolean;
9278 return Compatible;
9279 }
9280
9281 // T* -> int
9282 if (LHSType->isIntegerType()) {
9283 Kind = CK_PointerToIntegral;
9284 return PointerToInt;
9285 }
9286
9287 return Incompatible;
9288 }
9289
9290 // Conversions from Objective-C pointers that are not covered by the above.
9291 if (isa<ObjCObjectPointerType>(RHSType)) {
9292 // T* -> _Bool
9293 if (LHSType == Context.BoolTy) {
9294 Kind = CK_PointerToBoolean;
9295 return Compatible;
9296 }
9297
9298 // T* -> int
9299 if (LHSType->isIntegerType()) {
9300 Kind = CK_PointerToIntegral;
9301 return PointerToInt;
9302 }
9303
9304 return Incompatible;
9305 }
9306
9307 // struct A -> struct B
9308 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9309 if (Context.typesAreCompatible(LHSType, RHSType)) {
9310 Kind = CK_NoOp;
9311 return Compatible;
9312 }
9313 }
9314
9315 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9316 Kind = CK_IntToOCLSampler;
9317 return Compatible;
9318 }
9319
9320 return Incompatible;
9321 }
9322
9323 /// Constructs a transparent union from an expression that is
9324 /// used to initialize the transparent union.
ConstructTransparentUnion(Sema & S,ASTContext & C,ExprResult & EResult,QualType UnionType,FieldDecl * Field)9325 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
9326 ExprResult &EResult, QualType UnionType,
9327 FieldDecl *Field) {
9328 // Build an initializer list that designates the appropriate member
9329 // of the transparent union.
9330 Expr *E = EResult.get();
9331 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
9332 E, SourceLocation());
9333 Initializer->setType(UnionType);
9334 Initializer->setInitializedFieldInUnion(Field);
9335
9336 // Build a compound literal constructing a value of the transparent
9337 // union type from this initializer list.
9338 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9339 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9340 VK_RValue, Initializer, false);
9341 }
9342
9343 Sema::AssignConvertType
CheckTransparentUnionArgumentConstraints(QualType ArgType,ExprResult & RHS)9344 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
9345 ExprResult &RHS) {
9346 QualType RHSType = RHS.get()->getType();
9347
9348 // If the ArgType is a Union type, we want to handle a potential
9349 // transparent_union GCC extension.
9350 const RecordType *UT = ArgType->getAsUnionType();
9351 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9352 return Incompatible;
9353
9354 // The field to initialize within the transparent union.
9355 RecordDecl *UD = UT->getDecl();
9356 FieldDecl *InitField = nullptr;
9357 // It's compatible if the expression matches any of the fields.
9358 for (auto *it : UD->fields()) {
9359 if (it->getType()->isPointerType()) {
9360 // If the transparent union contains a pointer type, we allow:
9361 // 1) void pointer
9362 // 2) null pointer constant
9363 if (RHSType->isPointerType())
9364 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9365 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9366 InitField = it;
9367 break;
9368 }
9369
9370 if (RHS.get()->isNullPointerConstant(Context,
9371 Expr::NPC_ValueDependentIsNull)) {
9372 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9373 CK_NullToPointer);
9374 InitField = it;
9375 break;
9376 }
9377 }
9378
9379 CastKind Kind;
9380 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9381 == Compatible) {
9382 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9383 InitField = it;
9384 break;
9385 }
9386 }
9387
9388 if (!InitField)
9389 return Incompatible;
9390
9391 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9392 return Compatible;
9393 }
9394
9395 Sema::AssignConvertType
CheckSingleAssignmentConstraints(QualType LHSType,ExprResult & CallerRHS,bool Diagnose,bool DiagnoseCFAudited,bool ConvertRHS)9396 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
9397 bool Diagnose,
9398 bool DiagnoseCFAudited,
9399 bool ConvertRHS) {
9400 // We need to be able to tell the caller whether we diagnosed a problem, if
9401 // they ask us to issue diagnostics.
9402 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9403
9404 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9405 // we can't avoid *all* modifications at the moment, so we need some somewhere
9406 // to put the updated value.
9407 ExprResult LocalRHS = CallerRHS;
9408 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9409
9410 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9411 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9412 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9413 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9414 Diag(RHS.get()->getExprLoc(),
9415 diag::warn_noderef_to_dereferenceable_pointer)
9416 << RHS.get()->getSourceRange();
9417 }
9418 }
9419 }
9420
9421 if (getLangOpts().CPlusPlus) {
9422 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9423 // C++ 5.17p3: If the left operand is not of class type, the
9424 // expression is implicitly converted (C++ 4) to the
9425 // cv-unqualified type of the left operand.
9426 QualType RHSType = RHS.get()->getType();
9427 if (Diagnose) {
9428 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9429 AA_Assigning);
9430 } else {
9431 ImplicitConversionSequence ICS =
9432 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9433 /*SuppressUserConversions=*/false,
9434 AllowedExplicit::None,
9435 /*InOverloadResolution=*/false,
9436 /*CStyle=*/false,
9437 /*AllowObjCWritebackConversion=*/false);
9438 if (ICS.isFailure())
9439 return Incompatible;
9440 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9441 ICS, AA_Assigning);
9442 }
9443 if (RHS.isInvalid())
9444 return Incompatible;
9445 Sema::AssignConvertType result = Compatible;
9446 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9447 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9448 result = IncompatibleObjCWeakRef;
9449 return result;
9450 }
9451
9452 // FIXME: Currently, we fall through and treat C++ classes like C
9453 // structures.
9454 // FIXME: We also fall through for atomics; not sure what should
9455 // happen there, though.
9456 } else if (RHS.get()->getType() == Context.OverloadTy) {
9457 // As a set of extensions to C, we support overloading on functions. These
9458 // functions need to be resolved here.
9459 DeclAccessPair DAP;
9460 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
9461 RHS.get(), LHSType, /*Complain=*/false, DAP))
9462 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9463 else
9464 return Incompatible;
9465 }
9466
9467 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9468 // a null pointer constant.
9469 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
9470 LHSType->isBlockPointerType()) &&
9471 RHS.get()->isNullPointerConstant(Context,
9472 Expr::NPC_ValueDependentIsNull)) {
9473 if (Diagnose || ConvertRHS) {
9474 CastKind Kind;
9475 CXXCastPath Path;
9476 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9477 /*IgnoreBaseAccess=*/false, Diagnose);
9478 if (ConvertRHS)
9479 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
9480 }
9481 return Compatible;
9482 }
9483
9484 // OpenCL queue_t type assignment.
9485 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9486 Context, Expr::NPC_ValueDependentIsNull)) {
9487 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9488 return Compatible;
9489 }
9490
9491 // This check seems unnatural, however it is necessary to ensure the proper
9492 // conversion of functions/arrays. If the conversion were done for all
9493 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9494 // expressions that suppress this implicit conversion (&, sizeof).
9495 //
9496 // Suppress this for references: C++ 8.5.3p5.
9497 if (!LHSType->isReferenceType()) {
9498 // FIXME: We potentially allocate here even if ConvertRHS is false.
9499 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
9500 if (RHS.isInvalid())
9501 return Incompatible;
9502 }
9503 CastKind Kind;
9504 Sema::AssignConvertType result =
9505 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9506
9507 // C99 6.5.16.1p2: The value of the right operand is converted to the
9508 // type of the assignment expression.
9509 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9510 // so that we can use references in built-in functions even in C.
9511 // The getNonReferenceType() call makes sure that the resulting expression
9512 // does not have reference type.
9513 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9514 QualType Ty = LHSType.getNonLValueExprType(Context);
9515 Expr *E = RHS.get();
9516
9517 // Check for various Objective-C errors. If we are not reporting
9518 // diagnostics and just checking for errors, e.g., during overload
9519 // resolution, return Incompatible to indicate the failure.
9520 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9521 CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
9522 Diagnose, DiagnoseCFAudited) != ACR_okay) {
9523 if (!Diagnose)
9524 return Incompatible;
9525 }
9526 if (getLangOpts().ObjC &&
9527 (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9528 E->getType(), E, Diagnose) ||
9529 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9530 if (!Diagnose)
9531 return Incompatible;
9532 // Replace the expression with a corrected version and continue so we
9533 // can find further errors.
9534 RHS = E;
9535 return Compatible;
9536 }
9537
9538 if (ConvertRHS)
9539 RHS = ImpCastExprToType(E, Ty, Kind);
9540 }
9541
9542 return result;
9543 }
9544
9545 namespace {
9546 /// The original operand to an operator, prior to the application of the usual
9547 /// arithmetic conversions and converting the arguments of a builtin operator
9548 /// candidate.
9549 struct OriginalOperand {
OriginalOperand__anona30d30eb0c11::OriginalOperand9550 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9551 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9552 Op = MTE->getSubExpr();
9553 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9554 Op = BTE->getSubExpr();
9555 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9556 Orig = ICE->getSubExprAsWritten();
9557 Conversion = ICE->getConversionFunction();
9558 }
9559 }
9560
getType__anona30d30eb0c11::OriginalOperand9561 QualType getType() const { return Orig->getType(); }
9562
9563 Expr *Orig;
9564 NamedDecl *Conversion;
9565 };
9566 }
9567
InvalidOperands(SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)9568 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
9569 ExprResult &RHS) {
9570 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9571
9572 Diag(Loc, diag::err_typecheck_invalid_operands)
9573 << OrigLHS.getType() << OrigRHS.getType()
9574 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9575
9576 // If a user-defined conversion was applied to either of the operands prior
9577 // to applying the built-in operator rules, tell the user about it.
9578 if (OrigLHS.Conversion) {
9579 Diag(OrigLHS.Conversion->getLocation(),
9580 diag::note_typecheck_invalid_operands_converted)
9581 << 0 << LHS.get()->getType();
9582 }
9583 if (OrigRHS.Conversion) {
9584 Diag(OrigRHS.Conversion->getLocation(),
9585 diag::note_typecheck_invalid_operands_converted)
9586 << 1 << RHS.get()->getType();
9587 }
9588
9589 return QualType();
9590 }
9591
9592 // Diagnose cases where a scalar was implicitly converted to a vector and
9593 // diagnose the underlying types. Otherwise, diagnose the error
9594 // as invalid vector logical operands for non-C++ cases.
InvalidLogicalVectorOperands(SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)9595 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
9596 ExprResult &RHS) {
9597 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9598 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9599
9600 bool LHSNatVec = LHSType->isVectorType();
9601 bool RHSNatVec = RHSType->isVectorType();
9602
9603 if (!(LHSNatVec && RHSNatVec)) {
9604 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9605 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9606 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9607 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9608 << Vector->getSourceRange();
9609 return QualType();
9610 }
9611
9612 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9613 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9614 << RHS.get()->getSourceRange();
9615
9616 return QualType();
9617 }
9618
9619 /// Try to convert a value of non-vector type to a vector type by converting
9620 /// the type to the element type of the vector and then performing a splat.
9621 /// If the language is OpenCL, we only use conversions that promote scalar
9622 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9623 /// for float->int.
9624 ///
9625 /// OpenCL V2.0 6.2.6.p2:
9626 /// An error shall occur if any scalar operand type has greater rank
9627 /// than the type of the vector element.
9628 ///
9629 /// \param scalar - if non-null, actually perform the conversions
9630 /// \return true if the operation fails (but without diagnosing the failure)
tryVectorConvertAndSplat(Sema & S,ExprResult * scalar,QualType scalarTy,QualType vectorEltTy,QualType vectorTy,unsigned & DiagID)9631 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
9632 QualType scalarTy,
9633 QualType vectorEltTy,
9634 QualType vectorTy,
9635 unsigned &DiagID) {
9636 // The conversion to apply to the scalar before splatting it,
9637 // if necessary.
9638 CastKind scalarCast = CK_NoOp;
9639
9640 if (vectorEltTy->isIntegralType(S.Context)) {
9641 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9642 (scalarTy->isIntegerType() &&
9643 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9644 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9645 return true;
9646 }
9647 if (!scalarTy->isIntegralType(S.Context))
9648 return true;
9649 scalarCast = CK_IntegralCast;
9650 } else if (vectorEltTy->isRealFloatingType()) {
9651 if (scalarTy->isRealFloatingType()) {
9652 if (S.getLangOpts().OpenCL &&
9653 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9654 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9655 return true;
9656 }
9657 scalarCast = CK_FloatingCast;
9658 }
9659 else if (scalarTy->isIntegralType(S.Context))
9660 scalarCast = CK_IntegralToFloating;
9661 else
9662 return true;
9663 } else {
9664 return true;
9665 }
9666
9667 // Adjust scalar if desired.
9668 if (scalar) {
9669 if (scalarCast != CK_NoOp)
9670 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9671 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9672 }
9673 return false;
9674 }
9675
9676 /// Convert vector E to a vector with the same number of elements but different
9677 /// element type.
convertVector(Expr * E,QualType ElementType,Sema & S)9678 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9679 const auto *VecTy = E->getType()->getAs<VectorType>();
9680 assert(VecTy && "Expression E must be a vector");
9681 QualType NewVecTy = S.Context.getVectorType(ElementType,
9682 VecTy->getNumElements(),
9683 VecTy->getVectorKind());
9684
9685 // Look through the implicit cast. Return the subexpression if its type is
9686 // NewVecTy.
9687 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9688 if (ICE->getSubExpr()->getType() == NewVecTy)
9689 return ICE->getSubExpr();
9690
9691 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9692 return S.ImpCastExprToType(E, NewVecTy, Cast);
9693 }
9694
9695 /// Test if a (constant) integer Int can be casted to another integer type
9696 /// IntTy without losing precision.
canConvertIntToOtherIntTy(Sema & S,ExprResult * Int,QualType OtherIntTy)9697 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
9698 QualType OtherIntTy) {
9699 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9700
9701 // Reject cases where the value of the Int is unknown as that would
9702 // possibly cause truncation, but accept cases where the scalar can be
9703 // demoted without loss of precision.
9704 Expr::EvalResult EVResult;
9705 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9706 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9707 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9708 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9709
9710 if (CstInt) {
9711 // If the scalar is constant and is of a higher order and has more active
9712 // bits that the vector element type, reject it.
9713 llvm::APSInt Result = EVResult.Val.getInt();
9714 unsigned NumBits = IntSigned
9715 ? (Result.isNegative() ? Result.getMinSignedBits()
9716 : Result.getActiveBits())
9717 : Result.getActiveBits();
9718 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9719 return true;
9720
9721 // If the signedness of the scalar type and the vector element type
9722 // differs and the number of bits is greater than that of the vector
9723 // element reject it.
9724 return (IntSigned != OtherIntSigned &&
9725 NumBits > S.Context.getIntWidth(OtherIntTy));
9726 }
9727
9728 // Reject cases where the value of the scalar is not constant and it's
9729 // order is greater than that of the vector element type.
9730 return (Order < 0);
9731 }
9732
9733 /// Test if a (constant) integer Int can be casted to floating point type
9734 /// FloatTy without losing precision.
canConvertIntTyToFloatTy(Sema & S,ExprResult * Int,QualType FloatTy)9735 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
9736 QualType FloatTy) {
9737 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9738
9739 // Determine if the integer constant can be expressed as a floating point
9740 // number of the appropriate type.
9741 Expr::EvalResult EVResult;
9742 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9743
9744 uint64_t Bits = 0;
9745 if (CstInt) {
9746 // Reject constants that would be truncated if they were converted to
9747 // the floating point type. Test by simple to/from conversion.
9748 // FIXME: Ideally the conversion to an APFloat and from an APFloat
9749 // could be avoided if there was a convertFromAPInt method
9750 // which could signal back if implicit truncation occurred.
9751 llvm::APSInt Result = EVResult.Val.getInt();
9752 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9753 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9754 llvm::APFloat::rmTowardZero);
9755 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9756 !IntTy->hasSignedIntegerRepresentation());
9757 bool Ignored = false;
9758 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9759 &Ignored);
9760 if (Result != ConvertBack)
9761 return true;
9762 } else {
9763 // Reject types that cannot be fully encoded into the mantissa of
9764 // the float.
9765 Bits = S.Context.getTypeSize(IntTy);
9766 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9767 S.Context.getFloatTypeSemantics(FloatTy));
9768 if (Bits > FloatPrec)
9769 return true;
9770 }
9771
9772 return false;
9773 }
9774
9775 /// Attempt to convert and splat Scalar into a vector whose types matches
9776 /// Vector following GCC conversion rules. The rule is that implicit
9777 /// conversion can occur when Scalar can be casted to match Vector's element
9778 /// type without causing truncation of Scalar.
tryGCCVectorConvertAndSplat(Sema & S,ExprResult * Scalar,ExprResult * Vector)9779 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
9780 ExprResult *Vector) {
9781 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9782 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9783 const VectorType *VT = VectorTy->getAs<VectorType>();
9784
9785 assert(!isa<ExtVectorType>(VT) &&
9786 "ExtVectorTypes should not be handled here!");
9787
9788 QualType VectorEltTy = VT->getElementType();
9789
9790 // Reject cases where the vector element type or the scalar element type are
9791 // not integral or floating point types.
9792 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9793 return true;
9794
9795 // The conversion to apply to the scalar before splatting it,
9796 // if necessary.
9797 CastKind ScalarCast = CK_NoOp;
9798
9799 // Accept cases where the vector elements are integers and the scalar is
9800 // an integer.
9801 // FIXME: Notionally if the scalar was a floating point value with a precise
9802 // integral representation, we could cast it to an appropriate integer
9803 // type and then perform the rest of the checks here. GCC will perform
9804 // this conversion in some cases as determined by the input language.
9805 // We should accept it on a language independent basis.
9806 if (VectorEltTy->isIntegralType(S.Context) &&
9807 ScalarTy->isIntegralType(S.Context) &&
9808 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9809
9810 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9811 return true;
9812
9813 ScalarCast = CK_IntegralCast;
9814 } else if (VectorEltTy->isIntegralType(S.Context) &&
9815 ScalarTy->isRealFloatingType()) {
9816 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
9817 ScalarCast = CK_FloatingToIntegral;
9818 else
9819 return true;
9820 } else if (VectorEltTy->isRealFloatingType()) {
9821 if (ScalarTy->isRealFloatingType()) {
9822
9823 // Reject cases where the scalar type is not a constant and has a higher
9824 // Order than the vector element type.
9825 llvm::APFloat Result(0.0);
9826
9827 // Determine whether this is a constant scalar. In the event that the
9828 // value is dependent (and thus cannot be evaluated by the constant
9829 // evaluator), skip the evaluation. This will then diagnose once the
9830 // expression is instantiated.
9831 bool CstScalar = Scalar->get()->isValueDependent() ||
9832 Scalar->get()->EvaluateAsFloat(Result, S.Context);
9833 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
9834 if (!CstScalar && Order < 0)
9835 return true;
9836
9837 // If the scalar cannot be safely casted to the vector element type,
9838 // reject it.
9839 if (CstScalar) {
9840 bool Truncated = false;
9841 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
9842 llvm::APFloat::rmNearestTiesToEven, &Truncated);
9843 if (Truncated)
9844 return true;
9845 }
9846
9847 ScalarCast = CK_FloatingCast;
9848 } else if (ScalarTy->isIntegralType(S.Context)) {
9849 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
9850 return true;
9851
9852 ScalarCast = CK_IntegralToFloating;
9853 } else
9854 return true;
9855 } else if (ScalarTy->isEnumeralType())
9856 return true;
9857
9858 // Adjust scalar if desired.
9859 if (Scalar) {
9860 if (ScalarCast != CK_NoOp)
9861 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
9862 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
9863 }
9864 return false;
9865 }
9866
CheckVectorOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign,bool AllowBothBool,bool AllowBoolConversions)9867 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
9868 SourceLocation Loc, bool IsCompAssign,
9869 bool AllowBothBool,
9870 bool AllowBoolConversions) {
9871 if (!IsCompAssign) {
9872 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9873 if (LHS.isInvalid())
9874 return QualType();
9875 }
9876 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9877 if (RHS.isInvalid())
9878 return QualType();
9879
9880 // For conversion purposes, we ignore any qualifiers.
9881 // For example, "const float" and "float" are equivalent.
9882 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
9883 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
9884
9885 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
9886 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
9887 assert(LHSVecType || RHSVecType);
9888
9889 if ((LHSVecType && LHSVecType->getElementType()->isBFloat16Type()) ||
9890 (RHSVecType && RHSVecType->getElementType()->isBFloat16Type()))
9891 return InvalidOperands(Loc, LHS, RHS);
9892
9893 // AltiVec-style "vector bool op vector bool" combinations are allowed
9894 // for some operators but not others.
9895 if (!AllowBothBool &&
9896 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9897 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9898 return InvalidOperands(Loc, LHS, RHS);
9899
9900 // If the vector types are identical, return.
9901 if (Context.hasSameType(LHSType, RHSType))
9902 return LHSType;
9903
9904 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
9905 if (LHSVecType && RHSVecType &&
9906 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9907 if (isa<ExtVectorType>(LHSVecType)) {
9908 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9909 return LHSType;
9910 }
9911
9912 if (!IsCompAssign)
9913 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9914 return RHSType;
9915 }
9916
9917 // AllowBoolConversions says that bool and non-bool AltiVec vectors
9918 // can be mixed, with the result being the non-bool type. The non-bool
9919 // operand must have integer element type.
9920 if (AllowBoolConversions && LHSVecType && RHSVecType &&
9921 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
9922 (Context.getTypeSize(LHSVecType->getElementType()) ==
9923 Context.getTypeSize(RHSVecType->getElementType()))) {
9924 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9925 LHSVecType->getElementType()->isIntegerType() &&
9926 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
9927 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9928 return LHSType;
9929 }
9930 if (!IsCompAssign &&
9931 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
9932 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
9933 RHSVecType->getElementType()->isIntegerType()) {
9934 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9935 return RHSType;
9936 }
9937 }
9938
9939 // Expressions containing fixed-length and sizeless SVE vectors are invalid
9940 // since the ambiguity can affect the ABI.
9941 auto IsSveConversion = [](QualType FirstType, QualType SecondType) {
9942 const VectorType *VecType = SecondType->getAs<VectorType>();
9943 return FirstType->isSizelessBuiltinType() && VecType &&
9944 (VecType->getVectorKind() == VectorType::SveFixedLengthDataVector ||
9945 VecType->getVectorKind() ==
9946 VectorType::SveFixedLengthPredicateVector);
9947 };
9948
9949 if (IsSveConversion(LHSType, RHSType) || IsSveConversion(RHSType, LHSType)) {
9950 Diag(Loc, diag::err_typecheck_sve_ambiguous) << LHSType << RHSType;
9951 return QualType();
9952 }
9953
9954 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
9955 // since the ambiguity can affect the ABI.
9956 auto IsSveGnuConversion = [](QualType FirstType, QualType SecondType) {
9957 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
9958 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
9959
9960 if (FirstVecType && SecondVecType)
9961 return FirstVecType->getVectorKind() == VectorType::GenericVector &&
9962 (SecondVecType->getVectorKind() ==
9963 VectorType::SveFixedLengthDataVector ||
9964 SecondVecType->getVectorKind() ==
9965 VectorType::SveFixedLengthPredicateVector);
9966
9967 return FirstType->isSizelessBuiltinType() && SecondVecType &&
9968 SecondVecType->getVectorKind() == VectorType::GenericVector;
9969 };
9970
9971 if (IsSveGnuConversion(LHSType, RHSType) ||
9972 IsSveGnuConversion(RHSType, LHSType)) {
9973 Diag(Loc, diag::err_typecheck_sve_gnu_ambiguous) << LHSType << RHSType;
9974 return QualType();
9975 }
9976
9977 // If there's a vector type and a scalar, try to convert the scalar to
9978 // the vector element type and splat.
9979 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
9980 if (!RHSVecType) {
9981 if (isa<ExtVectorType>(LHSVecType)) {
9982 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
9983 LHSVecType->getElementType(), LHSType,
9984 DiagID))
9985 return LHSType;
9986 } else {
9987 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
9988 return LHSType;
9989 }
9990 }
9991 if (!LHSVecType) {
9992 if (isa<ExtVectorType>(RHSVecType)) {
9993 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
9994 LHSType, RHSVecType->getElementType(),
9995 RHSType, DiagID))
9996 return RHSType;
9997 } else {
9998 if (LHS.get()->getValueKind() == VK_LValue ||
9999 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10000 return RHSType;
10001 }
10002 }
10003
10004 // FIXME: The code below also handles conversion between vectors and
10005 // non-scalars, we should break this down into fine grained specific checks
10006 // and emit proper diagnostics.
10007 QualType VecType = LHSVecType ? LHSType : RHSType;
10008 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10009 QualType OtherType = LHSVecType ? RHSType : LHSType;
10010 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10011 if (isLaxVectorConversion(OtherType, VecType)) {
10012 // If we're allowing lax vector conversions, only the total (data) size
10013 // needs to be the same. For non compound assignment, if one of the types is
10014 // scalar, the result is always the vector type.
10015 if (!IsCompAssign) {
10016 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10017 return VecType;
10018 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10019 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10020 // type. Note that this is already done by non-compound assignments in
10021 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10022 // <1 x T> -> T. The result is also a vector type.
10023 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10024 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10025 ExprResult *RHSExpr = &RHS;
10026 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10027 return VecType;
10028 }
10029 }
10030
10031 // Okay, the expression is invalid.
10032
10033 // If there's a non-vector, non-real operand, diagnose that.
10034 if ((!RHSVecType && !RHSType->isRealType()) ||
10035 (!LHSVecType && !LHSType->isRealType())) {
10036 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10037 << LHSType << RHSType
10038 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10039 return QualType();
10040 }
10041
10042 // OpenCL V1.1 6.2.6.p1:
10043 // If the operands are of more than one vector type, then an error shall
10044 // occur. Implicit conversions between vector types are not permitted, per
10045 // section 6.2.1.
10046 if (getLangOpts().OpenCL &&
10047 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10048 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10049 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10050 << RHSType;
10051 return QualType();
10052 }
10053
10054
10055 // If there is a vector type that is not a ExtVector and a scalar, we reach
10056 // this point if scalar could not be converted to the vector's element type
10057 // without truncation.
10058 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10059 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10060 QualType Scalar = LHSVecType ? RHSType : LHSType;
10061 QualType Vector = LHSVecType ? LHSType : RHSType;
10062 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10063 Diag(Loc,
10064 diag::err_typecheck_vector_not_convertable_implict_truncation)
10065 << ScalarOrVector << Scalar << Vector;
10066
10067 return QualType();
10068 }
10069
10070 // Otherwise, use the generic diagnostic.
10071 Diag(Loc, DiagID)
10072 << LHSType << RHSType
10073 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10074 return QualType();
10075 }
10076
10077 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10078 // expression. These are mainly cases where the null pointer is used as an
10079 // integer instead of a pointer.
checkArithmeticNull(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompare)10080 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
10081 SourceLocation Loc, bool IsCompare) {
10082 // The canonical way to check for a GNU null is with isNullPointerConstant,
10083 // but we use a bit of a hack here for speed; this is a relatively
10084 // hot path, and isNullPointerConstant is slow.
10085 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10086 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10087
10088 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10089
10090 // Avoid analyzing cases where the result will either be invalid (and
10091 // diagnosed as such) or entirely valid and not something to warn about.
10092 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10093 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10094 return;
10095
10096 // Comparison operations would not make sense with a null pointer no matter
10097 // what the other expression is.
10098 if (!IsCompare) {
10099 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10100 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10101 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10102 return;
10103 }
10104
10105 // The rest of the operations only make sense with a null pointer
10106 // if the other expression is a pointer.
10107 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10108 NonNullType->canDecayToPointerType())
10109 return;
10110
10111 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10112 << LHSNull /* LHS is NULL */ << NonNullType
10113 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10114 }
10115
DiagnoseDivisionSizeofPointerOrArray(Sema & S,Expr * LHS,Expr * RHS,SourceLocation Loc)10116 static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10117 SourceLocation Loc) {
10118 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10119 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10120 if (!LUE || !RUE)
10121 return;
10122 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10123 RUE->getKind() != UETT_SizeOf)
10124 return;
10125
10126 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10127 QualType LHSTy = LHSArg->getType();
10128 QualType RHSTy;
10129
10130 if (RUE->isArgumentType())
10131 RHSTy = RUE->getArgumentType().getNonReferenceType();
10132 else
10133 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10134
10135 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10136 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10137 return;
10138
10139 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10140 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10141 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10142 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10143 << LHSArgDecl;
10144 }
10145 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10146 QualType ArrayElemTy = ArrayTy->getElementType();
10147 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10148 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10149 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10150 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10151 return;
10152 S.Diag(Loc, diag::warn_division_sizeof_array)
10153 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10154 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10155 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10156 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10157 << LHSArgDecl;
10158 }
10159
10160 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10161 }
10162 }
10163
DiagnoseBadDivideOrRemainderValues(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsDiv)10164 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
10165 ExprResult &RHS,
10166 SourceLocation Loc, bool IsDiv) {
10167 // Check for division/remainder by zero.
10168 Expr::EvalResult RHSValue;
10169 if (!RHS.get()->isValueDependent() &&
10170 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10171 RHSValue.Val.getInt() == 0)
10172 S.DiagRuntimeBehavior(Loc, RHS.get(),
10173 S.PDiag(diag::warn_remainder_division_by_zero)
10174 << IsDiv << RHS.get()->getSourceRange());
10175 }
10176
CheckMultiplyDivideOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign,bool IsDiv)10177 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10178 SourceLocation Loc,
10179 bool IsCompAssign, bool IsDiv) {
10180 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10181
10182 if (LHS.get()->getType()->isVectorType() ||
10183 RHS.get()->getType()->isVectorType())
10184 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10185 /*AllowBothBool*/getLangOpts().AltiVec,
10186 /*AllowBoolConversions*/false);
10187 if (!IsDiv && (LHS.get()->getType()->isConstantMatrixType() ||
10188 RHS.get()->getType()->isConstantMatrixType()))
10189 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10190
10191 QualType compType = UsualArithmeticConversions(
10192 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10193 if (LHS.isInvalid() || RHS.isInvalid())
10194 return QualType();
10195
10196
10197 if (compType.isNull() || !compType->isArithmeticType())
10198 return InvalidOperands(Loc, LHS, RHS);
10199 if (IsDiv) {
10200 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10201 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10202 }
10203 return compType;
10204 }
10205
CheckRemainderOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)10206 QualType Sema::CheckRemainderOperands(
10207 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10208 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10209
10210 if (LHS.get()->getType()->isVectorType() ||
10211 RHS.get()->getType()->isVectorType()) {
10212 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10213 RHS.get()->getType()->hasIntegerRepresentation())
10214 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10215 /*AllowBothBool*/getLangOpts().AltiVec,
10216 /*AllowBoolConversions*/false);
10217 return InvalidOperands(Loc, LHS, RHS);
10218 }
10219
10220 QualType compType = UsualArithmeticConversions(
10221 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10222 if (LHS.isInvalid() || RHS.isInvalid())
10223 return QualType();
10224
10225 if (compType.isNull() || !compType->isIntegerType())
10226 return InvalidOperands(Loc, LHS, RHS);
10227 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10228 return compType;
10229 }
10230
10231 /// Diagnose invalid arithmetic on two void pointers.
diagnoseArithmeticOnTwoVoidPointers(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)10232 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
10233 Expr *LHSExpr, Expr *RHSExpr) {
10234 S.Diag(Loc, S.getLangOpts().CPlusPlus
10235 ? diag::err_typecheck_pointer_arith_void_type
10236 : diag::ext_gnu_void_ptr)
10237 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10238 << RHSExpr->getSourceRange();
10239 }
10240
10241 /// Diagnose invalid arithmetic on a void pointer.
diagnoseArithmeticOnVoidPointer(Sema & S,SourceLocation Loc,Expr * Pointer)10242 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
10243 Expr *Pointer) {
10244 S.Diag(Loc, S.getLangOpts().CPlusPlus
10245 ? diag::err_typecheck_pointer_arith_void_type
10246 : diag::ext_gnu_void_ptr)
10247 << 0 /* one pointer */ << Pointer->getSourceRange();
10248 }
10249
10250 /// Diagnose invalid arithmetic on a null pointer.
10251 ///
10252 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10253 /// idiom, which we recognize as a GNU extension.
10254 ///
diagnoseArithmeticOnNullPointer(Sema & S,SourceLocation Loc,Expr * Pointer,bool IsGNUIdiom)10255 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
10256 Expr *Pointer, bool IsGNUIdiom) {
10257 if (IsGNUIdiom)
10258 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10259 << Pointer->getSourceRange();
10260 else
10261 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10262 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10263 }
10264
10265 /// Diagnose invalid arithmetic on two function pointers.
diagnoseArithmeticOnTwoFunctionPointers(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS)10266 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
10267 Expr *LHS, Expr *RHS) {
10268 assert(LHS->getType()->isAnyPointerType());
10269 assert(RHS->getType()->isAnyPointerType());
10270 S.Diag(Loc, S.getLangOpts().CPlusPlus
10271 ? diag::err_typecheck_pointer_arith_function_type
10272 : diag::ext_gnu_ptr_func_arith)
10273 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10274 // We only show the second type if it differs from the first.
10275 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
10276 RHS->getType())
10277 << RHS->getType()->getPointeeType()
10278 << LHS->getSourceRange() << RHS->getSourceRange();
10279 }
10280
10281 /// Diagnose invalid arithmetic on a function pointer.
diagnoseArithmeticOnFunctionPointer(Sema & S,SourceLocation Loc,Expr * Pointer)10282 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
10283 Expr *Pointer) {
10284 assert(Pointer->getType()->isAnyPointerType());
10285 S.Diag(Loc, S.getLangOpts().CPlusPlus
10286 ? diag::err_typecheck_pointer_arith_function_type
10287 : diag::ext_gnu_ptr_func_arith)
10288 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10289 << 0 /* one pointer, so only one type */
10290 << Pointer->getSourceRange();
10291 }
10292
10293 /// Emit error if Operand is incomplete pointer type
10294 ///
10295 /// \returns True if pointer has incomplete type
checkArithmeticIncompletePointerType(Sema & S,SourceLocation Loc,Expr * Operand)10296 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
10297 Expr *Operand) {
10298 QualType ResType = Operand->getType();
10299 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10300 ResType = ResAtomicType->getValueType();
10301
10302 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
10303 QualType PointeeTy = ResType->getPointeeType();
10304 return S.RequireCompleteSizedType(
10305 Loc, PointeeTy,
10306 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10307 Operand->getSourceRange());
10308 }
10309
10310 /// Check the validity of an arithmetic pointer operand.
10311 ///
10312 /// If the operand has pointer type, this code will check for pointer types
10313 /// which are invalid in arithmetic operations. These will be diagnosed
10314 /// appropriately, including whether or not the use is supported as an
10315 /// extension.
10316 ///
10317 /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticOpPointerOperand(Sema & S,SourceLocation Loc,Expr * Operand)10318 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
10319 Expr *Operand) {
10320 QualType ResType = Operand->getType();
10321 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10322 ResType = ResAtomicType->getValueType();
10323
10324 if (!ResType->isAnyPointerType()) return true;
10325
10326 QualType PointeeTy = ResType->getPointeeType();
10327 if (PointeeTy->isVoidType()) {
10328 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
10329 return !S.getLangOpts().CPlusPlus;
10330 }
10331 if (PointeeTy->isFunctionType()) {
10332 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
10333 return !S.getLangOpts().CPlusPlus;
10334 }
10335
10336 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10337
10338 return true;
10339 }
10340
10341 /// Check the validity of a binary arithmetic operation w.r.t. pointer
10342 /// operands.
10343 ///
10344 /// This routine will diagnose any invalid arithmetic on pointer operands much
10345 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
10346 /// for emitting a single diagnostic even for operations where both LHS and RHS
10347 /// are (potentially problematic) pointers.
10348 ///
10349 /// \returns True when the operand is valid to use (even if as an extension).
checkArithmeticBinOpPointerOperands(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)10350 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
10351 Expr *LHSExpr, Expr *RHSExpr) {
10352 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10353 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10354 if (!isLHSPointer && !isRHSPointer) return true;
10355
10356 QualType LHSPointeeTy, RHSPointeeTy;
10357 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10358 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10359
10360 // if both are pointers check if operation is valid wrt address spaces
10361 if (isLHSPointer && isRHSPointer) {
10362 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10363 S.Diag(Loc,
10364 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10365 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10366 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10367 return false;
10368 }
10369 }
10370
10371 // Check for arithmetic on pointers to incomplete types.
10372 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10373 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10374 if (isLHSVoidPtr || isRHSVoidPtr) {
10375 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10376 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10377 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10378
10379 return !S.getLangOpts().CPlusPlus;
10380 }
10381
10382 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10383 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10384 if (isLHSFuncPtr || isRHSFuncPtr) {
10385 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10386 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10387 RHSExpr);
10388 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10389
10390 return !S.getLangOpts().CPlusPlus;
10391 }
10392
10393 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10394 return false;
10395 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10396 return false;
10397
10398 return true;
10399 }
10400
10401 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10402 /// literal.
diagnoseStringPlusInt(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10403 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
10404 Expr *LHSExpr, Expr *RHSExpr) {
10405 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10406 Expr* IndexExpr = RHSExpr;
10407 if (!StrExpr) {
10408 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10409 IndexExpr = LHSExpr;
10410 }
10411
10412 bool IsStringPlusInt = StrExpr &&
10413 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
10414 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10415 return;
10416
10417 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10418 Self.Diag(OpLoc, diag::warn_string_plus_int)
10419 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10420
10421 // Only print a fixit for "str" + int, not for int + "str".
10422 if (IndexExpr == RHSExpr) {
10423 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10424 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10425 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10426 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10427 << FixItHint::CreateInsertion(EndLoc, "]");
10428 } else
10429 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10430 }
10431
10432 /// Emit a warning when adding a char literal to a string.
diagnoseStringPlusChar(Sema & Self,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)10433 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
10434 Expr *LHSExpr, Expr *RHSExpr) {
10435 const Expr *StringRefExpr = LHSExpr;
10436 const CharacterLiteral *CharExpr =
10437 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10438
10439 if (!CharExpr) {
10440 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10441 StringRefExpr = RHSExpr;
10442 }
10443
10444 if (!CharExpr || !StringRefExpr)
10445 return;
10446
10447 const QualType StringType = StringRefExpr->getType();
10448
10449 // Return if not a PointerType.
10450 if (!StringType->isAnyPointerType())
10451 return;
10452
10453 // Return if not a CharacterType.
10454 if (!StringType->getPointeeType()->isAnyCharacterType())
10455 return;
10456
10457 ASTContext &Ctx = Self.getASTContext();
10458 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10459
10460 const QualType CharType = CharExpr->getType();
10461 if (!CharType->isAnyCharacterType() &&
10462 CharType->isIntegerType() &&
10463 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10464 Self.Diag(OpLoc, diag::warn_string_plus_char)
10465 << DiagRange << Ctx.CharTy;
10466 } else {
10467 Self.Diag(OpLoc, diag::warn_string_plus_char)
10468 << DiagRange << CharExpr->getType();
10469 }
10470
10471 // Only print a fixit for str + char, not for char + str.
10472 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10473 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10474 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10475 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10476 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
10477 << FixItHint::CreateInsertion(EndLoc, "]");
10478 } else {
10479 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10480 }
10481 }
10482
10483 /// Emit error when two pointers are incompatible.
diagnosePointerIncompatibility(Sema & S,SourceLocation Loc,Expr * LHSExpr,Expr * RHSExpr)10484 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
10485 Expr *LHSExpr, Expr *RHSExpr) {
10486 assert(LHSExpr->getType()->isAnyPointerType());
10487 assert(RHSExpr->getType()->isAnyPointerType());
10488 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10489 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10490 << RHSExpr->getSourceRange();
10491 }
10492
10493 // C99 6.5.6
CheckAdditionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,QualType * CompLHSTy)10494 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
10495 SourceLocation Loc, BinaryOperatorKind Opc,
10496 QualType* CompLHSTy) {
10497 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10498
10499 if (LHS.get()->getType()->isVectorType() ||
10500 RHS.get()->getType()->isVectorType()) {
10501 QualType compType = CheckVectorOperands(
10502 LHS, RHS, Loc, CompLHSTy,
10503 /*AllowBothBool*/getLangOpts().AltiVec,
10504 /*AllowBoolConversions*/getLangOpts().ZVector);
10505 if (CompLHSTy) *CompLHSTy = compType;
10506 return compType;
10507 }
10508
10509 if (LHS.get()->getType()->isConstantMatrixType() ||
10510 RHS.get()->getType()->isConstantMatrixType()) {
10511 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10512 }
10513
10514 QualType compType = UsualArithmeticConversions(
10515 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10516 if (LHS.isInvalid() || RHS.isInvalid())
10517 return QualType();
10518
10519 // Diagnose "string literal" '+' int and string '+' "char literal".
10520 if (Opc == BO_Add) {
10521 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10522 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10523 }
10524
10525 // handle the common case first (both operands are arithmetic).
10526 if (!compType.isNull() && compType->isArithmeticType()) {
10527 if (CompLHSTy) *CompLHSTy = compType;
10528 return compType;
10529 }
10530
10531 // Type-checking. Ultimately the pointer's going to be in PExp;
10532 // note that we bias towards the LHS being the pointer.
10533 Expr *PExp = LHS.get(), *IExp = RHS.get();
10534
10535 bool isObjCPointer;
10536 if (PExp->getType()->isPointerType()) {
10537 isObjCPointer = false;
10538 } else if (PExp->getType()->isObjCObjectPointerType()) {
10539 isObjCPointer = true;
10540 } else {
10541 std::swap(PExp, IExp);
10542 if (PExp->getType()->isPointerType()) {
10543 isObjCPointer = false;
10544 } else if (PExp->getType()->isObjCObjectPointerType()) {
10545 isObjCPointer = true;
10546 } else {
10547 return InvalidOperands(Loc, LHS, RHS);
10548 }
10549 }
10550 assert(PExp->getType()->isAnyPointerType());
10551
10552 if (!IExp->getType()->isIntegerType())
10553 return InvalidOperands(Loc, LHS, RHS);
10554
10555 // Adding to a null pointer results in undefined behavior.
10556 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
10557 Context, Expr::NPC_ValueDependentIsNotNull)) {
10558 // In C++ adding zero to a null pointer is defined.
10559 Expr::EvalResult KnownVal;
10560 if (!getLangOpts().CPlusPlus ||
10561 (!IExp->isValueDependent() &&
10562 (!IExp->EvaluateAsInt(KnownVal, Context) ||
10563 KnownVal.Val.getInt() != 0))) {
10564 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10565 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
10566 Context, BO_Add, PExp, IExp);
10567 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10568 }
10569 }
10570
10571 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10572 return QualType();
10573
10574 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10575 return QualType();
10576
10577 // Check array bounds for pointer arithemtic
10578 CheckArrayAccess(PExp, IExp);
10579
10580 if (CompLHSTy) {
10581 QualType LHSTy = Context.isPromotableBitField(LHS.get());
10582 if (LHSTy.isNull()) {
10583 LHSTy = LHS.get()->getType();
10584 if (LHSTy->isPromotableIntegerType())
10585 LHSTy = Context.getPromotedIntegerType(LHSTy);
10586 }
10587 *CompLHSTy = LHSTy;
10588 }
10589
10590 return PExp->getType();
10591 }
10592
10593 // C99 6.5.6
CheckSubtractionOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,QualType * CompLHSTy)10594 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
10595 SourceLocation Loc,
10596 QualType* CompLHSTy) {
10597 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10598
10599 if (LHS.get()->getType()->isVectorType() ||
10600 RHS.get()->getType()->isVectorType()) {
10601 QualType compType = CheckVectorOperands(
10602 LHS, RHS, Loc, CompLHSTy,
10603 /*AllowBothBool*/getLangOpts().AltiVec,
10604 /*AllowBoolConversions*/getLangOpts().ZVector);
10605 if (CompLHSTy) *CompLHSTy = compType;
10606 return compType;
10607 }
10608
10609 if (LHS.get()->getType()->isConstantMatrixType() ||
10610 RHS.get()->getType()->isConstantMatrixType()) {
10611 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10612 }
10613
10614 QualType compType = UsualArithmeticConversions(
10615 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10616 if (LHS.isInvalid() || RHS.isInvalid())
10617 return QualType();
10618
10619 // Enforce type constraints: C99 6.5.6p3.
10620
10621 // Handle the common case first (both operands are arithmetic).
10622 if (!compType.isNull() && compType->isArithmeticType()) {
10623 if (CompLHSTy) *CompLHSTy = compType;
10624 return compType;
10625 }
10626
10627 // Either ptr - int or ptr - ptr.
10628 if (LHS.get()->getType()->isAnyPointerType()) {
10629 QualType lpointee = LHS.get()->getType()->getPointeeType();
10630
10631 // Diagnose bad cases where we step over interface counts.
10632 if (LHS.get()->getType()->isObjCObjectPointerType() &&
10633 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
10634 return QualType();
10635
10636 // The result type of a pointer-int computation is the pointer type.
10637 if (RHS.get()->getType()->isIntegerType()) {
10638 // Subtracting from a null pointer should produce a warning.
10639 // The last argument to the diagnose call says this doesn't match the
10640 // GNU int-to-pointer idiom.
10641 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
10642 Expr::NPC_ValueDependentIsNotNull)) {
10643 // In C++ adding zero to a null pointer is defined.
10644 Expr::EvalResult KnownVal;
10645 if (!getLangOpts().CPlusPlus ||
10646 (!RHS.get()->isValueDependent() &&
10647 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
10648 KnownVal.Val.getInt() != 0))) {
10649 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
10650 }
10651 }
10652
10653 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
10654 return QualType();
10655
10656 // Check array bounds for pointer arithemtic
10657 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
10658 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
10659
10660 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10661 return LHS.get()->getType();
10662 }
10663
10664 // Handle pointer-pointer subtractions.
10665 if (const PointerType *RHSPTy
10666 = RHS.get()->getType()->getAs<PointerType>()) {
10667 QualType rpointee = RHSPTy->getPointeeType();
10668
10669 if (getLangOpts().CPlusPlus) {
10670 // Pointee types must be the same: C++ [expr.add]
10671 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
10672 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10673 }
10674 } else {
10675 // Pointee types must be compatible C99 6.5.6p3
10676 if (!Context.typesAreCompatible(
10677 Context.getCanonicalType(lpointee).getUnqualifiedType(),
10678 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
10679 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
10680 return QualType();
10681 }
10682 }
10683
10684 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
10685 LHS.get(), RHS.get()))
10686 return QualType();
10687
10688 // FIXME: Add warnings for nullptr - ptr.
10689
10690 // The pointee type may have zero size. As an extension, a structure or
10691 // union may have zero size or an array may have zero length. In this
10692 // case subtraction does not make sense.
10693 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
10694 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
10695 if (ElementSize.isZero()) {
10696 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
10697 << rpointee.getUnqualifiedType()
10698 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10699 }
10700 }
10701
10702 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
10703 return Context.getPointerDiffType();
10704 }
10705 }
10706
10707 return InvalidOperands(Loc, LHS, RHS);
10708 }
10709
isScopedEnumerationType(QualType T)10710 static bool isScopedEnumerationType(QualType T) {
10711 if (const EnumType *ET = T->getAs<EnumType>())
10712 return ET->getDecl()->isScoped();
10713 return false;
10714 }
10715
DiagnoseBadShiftValues(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,QualType LHSType)10716 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
10717 SourceLocation Loc, BinaryOperatorKind Opc,
10718 QualType LHSType) {
10719 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
10720 // so skip remaining warnings as we don't want to modify values within Sema.
10721 if (S.getLangOpts().OpenCL)
10722 return;
10723
10724 // Check right/shifter operand
10725 Expr::EvalResult RHSResult;
10726 if (RHS.get()->isValueDependent() ||
10727 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
10728 return;
10729 llvm::APSInt Right = RHSResult.Val.getInt();
10730
10731 if (Right.isNegative()) {
10732 S.DiagRuntimeBehavior(Loc, RHS.get(),
10733 S.PDiag(diag::warn_shift_negative)
10734 << RHS.get()->getSourceRange());
10735 return;
10736 }
10737
10738 QualType LHSExprType = LHS.get()->getType();
10739 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
10740 if (LHSExprType->isExtIntType())
10741 LeftSize = S.Context.getIntWidth(LHSExprType);
10742 else if (LHSExprType->isFixedPointType()) {
10743 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
10744 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
10745 }
10746 llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
10747 if (Right.uge(LeftBits)) {
10748 S.DiagRuntimeBehavior(Loc, RHS.get(),
10749 S.PDiag(diag::warn_shift_gt_typewidth)
10750 << RHS.get()->getSourceRange());
10751 return;
10752 }
10753
10754 // FIXME: We probably need to handle fixed point types specially here.
10755 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
10756 return;
10757
10758 // When left shifting an ICE which is signed, we can check for overflow which
10759 // according to C++ standards prior to C++2a has undefined behavior
10760 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
10761 // more than the maximum value representable in the result type, so never
10762 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
10763 // expression is still probably a bug.)
10764 Expr::EvalResult LHSResult;
10765 if (LHS.get()->isValueDependent() ||
10766 LHSType->hasUnsignedIntegerRepresentation() ||
10767 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
10768 return;
10769 llvm::APSInt Left = LHSResult.Val.getInt();
10770
10771 // If LHS does not have a signed type and non-negative value
10772 // then, the behavior is undefined before C++2a. Warn about it.
10773 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined() &&
10774 !S.getLangOpts().CPlusPlus20) {
10775 S.DiagRuntimeBehavior(Loc, LHS.get(),
10776 S.PDiag(diag::warn_shift_lhs_negative)
10777 << LHS.get()->getSourceRange());
10778 return;
10779 }
10780
10781 llvm::APInt ResultBits =
10782 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
10783 if (LeftBits.uge(ResultBits))
10784 return;
10785 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
10786 Result = Result.shl(Right);
10787
10788 // Print the bit representation of the signed integer as an unsigned
10789 // hexadecimal number.
10790 SmallString<40> HexResult;
10791 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
10792
10793 // If we are only missing a sign bit, this is less likely to result in actual
10794 // bugs -- if the result is cast back to an unsigned type, it will have the
10795 // expected value. Thus we place this behind a different warning that can be
10796 // turned off separately if needed.
10797 if (LeftBits == ResultBits - 1) {
10798 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
10799 << HexResult << LHSType
10800 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10801 return;
10802 }
10803
10804 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
10805 << HexResult.str() << Result.getMinSignedBits() << LHSType
10806 << Left.getBitWidth() << LHS.get()->getSourceRange()
10807 << RHS.get()->getSourceRange();
10808 }
10809
10810 /// Return the resulting type when a vector is shifted
10811 /// by a scalar or vector shift amount.
checkVectorShift(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)10812 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
10813 SourceLocation Loc, bool IsCompAssign) {
10814 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
10815 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
10816 !LHS.get()->getType()->isVectorType()) {
10817 S.Diag(Loc, diag::err_shift_rhs_only_vector)
10818 << RHS.get()->getType() << LHS.get()->getType()
10819 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10820 return QualType();
10821 }
10822
10823 if (!IsCompAssign) {
10824 LHS = S.UsualUnaryConversions(LHS.get());
10825 if (LHS.isInvalid()) return QualType();
10826 }
10827
10828 RHS = S.UsualUnaryConversions(RHS.get());
10829 if (RHS.isInvalid()) return QualType();
10830
10831 QualType LHSType = LHS.get()->getType();
10832 // Note that LHS might be a scalar because the routine calls not only in
10833 // OpenCL case.
10834 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
10835 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
10836
10837 // Note that RHS might not be a vector.
10838 QualType RHSType = RHS.get()->getType();
10839 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
10840 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
10841
10842 // The operands need to be integers.
10843 if (!LHSEleType->isIntegerType()) {
10844 S.Diag(Loc, diag::err_typecheck_expect_int)
10845 << LHS.get()->getType() << LHS.get()->getSourceRange();
10846 return QualType();
10847 }
10848
10849 if (!RHSEleType->isIntegerType()) {
10850 S.Diag(Loc, diag::err_typecheck_expect_int)
10851 << RHS.get()->getType() << RHS.get()->getSourceRange();
10852 return QualType();
10853 }
10854
10855 if (!LHSVecTy) {
10856 assert(RHSVecTy);
10857 if (IsCompAssign)
10858 return RHSType;
10859 if (LHSEleType != RHSEleType) {
10860 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
10861 LHSEleType = RHSEleType;
10862 }
10863 QualType VecTy =
10864 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
10865 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
10866 LHSType = VecTy;
10867 } else if (RHSVecTy) {
10868 // OpenCL v1.1 s6.3.j says that for vector types, the operators
10869 // are applied component-wise. So if RHS is a vector, then ensure
10870 // that the number of elements is the same as LHS...
10871 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
10872 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10873 << LHS.get()->getType() << RHS.get()->getType()
10874 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10875 return QualType();
10876 }
10877 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
10878 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
10879 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
10880 if (LHSBT != RHSBT &&
10881 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
10882 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
10883 << LHS.get()->getType() << RHS.get()->getType()
10884 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10885 }
10886 }
10887 } else {
10888 // ...else expand RHS to match the number of elements in LHS.
10889 QualType VecTy =
10890 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
10891 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
10892 }
10893
10894 return LHSType;
10895 }
10896
10897 // C99 6.5.7
CheckShiftOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc,bool IsCompAssign)10898 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
10899 SourceLocation Loc, BinaryOperatorKind Opc,
10900 bool IsCompAssign) {
10901 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10902
10903 // Vector shifts promote their scalar inputs to vector type.
10904 if (LHS.get()->getType()->isVectorType() ||
10905 RHS.get()->getType()->isVectorType()) {
10906 if (LangOpts.ZVector) {
10907 // The shift operators for the z vector extensions work basically
10908 // like general shifts, except that neither the LHS nor the RHS is
10909 // allowed to be a "vector bool".
10910 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
10911 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
10912 return InvalidOperands(Loc, LHS, RHS);
10913 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
10914 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
10915 return InvalidOperands(Loc, LHS, RHS);
10916 }
10917 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
10918 }
10919
10920 // Shifts don't perform usual arithmetic conversions, they just do integer
10921 // promotions on each operand. C99 6.5.7p3
10922
10923 // For the LHS, do usual unary conversions, but then reset them away
10924 // if this is a compound assignment.
10925 ExprResult OldLHS = LHS;
10926 LHS = UsualUnaryConversions(LHS.get());
10927 if (LHS.isInvalid())
10928 return QualType();
10929 QualType LHSType = LHS.get()->getType();
10930 if (IsCompAssign) LHS = OldLHS;
10931
10932 // The RHS is simpler.
10933 RHS = UsualUnaryConversions(RHS.get());
10934 if (RHS.isInvalid())
10935 return QualType();
10936 QualType RHSType = RHS.get()->getType();
10937
10938 // C99 6.5.7p2: Each of the operands shall have integer type.
10939 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
10940 if ((!LHSType->isFixedPointOrIntegerType() &&
10941 !LHSType->hasIntegerRepresentation()) ||
10942 !RHSType->hasIntegerRepresentation())
10943 return InvalidOperands(Loc, LHS, RHS);
10944
10945 // C++0x: Don't allow scoped enums. FIXME: Use something better than
10946 // hasIntegerRepresentation() above instead of this.
10947 if (isScopedEnumerationType(LHSType) ||
10948 isScopedEnumerationType(RHSType)) {
10949 return InvalidOperands(Loc, LHS, RHS);
10950 }
10951 // Sanity-check shift operands
10952 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
10953
10954 // "The type of the result is that of the promoted left operand."
10955 return LHSType;
10956 }
10957
10958 /// Diagnose bad pointer comparisons.
diagnoseDistinctPointerComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)10959 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
10960 ExprResult &LHS, ExprResult &RHS,
10961 bool IsError) {
10962 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
10963 : diag::ext_typecheck_comparison_of_distinct_pointers)
10964 << LHS.get()->getType() << RHS.get()->getType()
10965 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10966 }
10967
10968 /// Returns false if the pointers are converted to a composite type,
10969 /// true otherwise.
convertPointersToCompositeType(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS)10970 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
10971 ExprResult &LHS, ExprResult &RHS) {
10972 // C++ [expr.rel]p2:
10973 // [...] Pointer conversions (4.10) and qualification
10974 // conversions (4.4) are performed on pointer operands (or on
10975 // a pointer operand and a null pointer constant) to bring
10976 // them to their composite pointer type. [...]
10977 //
10978 // C++ [expr.eq]p1 uses the same notion for (in)equality
10979 // comparisons of pointers.
10980
10981 QualType LHSType = LHS.get()->getType();
10982 QualType RHSType = RHS.get()->getType();
10983 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
10984 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
10985
10986 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
10987 if (T.isNull()) {
10988 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
10989 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
10990 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
10991 else
10992 S.InvalidOperands(Loc, LHS, RHS);
10993 return true;
10994 }
10995
10996 return false;
10997 }
10998
diagnoseFunctionPointerToVoidComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,bool IsError)10999 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
11000 ExprResult &LHS,
11001 ExprResult &RHS,
11002 bool IsError) {
11003 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11004 : diag::ext_typecheck_comparison_of_fptr_to_void)
11005 << LHS.get()->getType() << RHS.get()->getType()
11006 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11007 }
11008
isObjCObjectLiteral(ExprResult & E)11009 static bool isObjCObjectLiteral(ExprResult &E) {
11010 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11011 case Stmt::ObjCArrayLiteralClass:
11012 case Stmt::ObjCDictionaryLiteralClass:
11013 case Stmt::ObjCStringLiteralClass:
11014 case Stmt::ObjCBoxedExprClass:
11015 return true;
11016 default:
11017 // Note that ObjCBoolLiteral is NOT an object literal!
11018 return false;
11019 }
11020 }
11021
hasIsEqualMethod(Sema & S,const Expr * LHS,const Expr * RHS)11022 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11023 const ObjCObjectPointerType *Type =
11024 LHS->getType()->getAs<ObjCObjectPointerType>();
11025
11026 // If this is not actually an Objective-C object, bail out.
11027 if (!Type)
11028 return false;
11029
11030 // Get the LHS object's interface type.
11031 QualType InterfaceType = Type->getPointeeType();
11032
11033 // If the RHS isn't an Objective-C object, bail out.
11034 if (!RHS->getType()->isObjCObjectPointerType())
11035 return false;
11036
11037 // Try to find the -isEqual: method.
11038 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11039 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11040 InterfaceType,
11041 /*IsInstance=*/true);
11042 if (!Method) {
11043 if (Type->isObjCIdType()) {
11044 // For 'id', just check the global pool.
11045 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
11046 /*receiverId=*/true);
11047 } else {
11048 // Check protocols.
11049 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
11050 /*IsInstance=*/true);
11051 }
11052 }
11053
11054 if (!Method)
11055 return false;
11056
11057 QualType T = Method->parameters()[0]->getType();
11058 if (!T->isObjCObjectPointerType())
11059 return false;
11060
11061 QualType R = Method->getReturnType();
11062 if (!R->isScalarType())
11063 return false;
11064
11065 return true;
11066 }
11067
CheckLiteralKind(Expr * FromE)11068 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
11069 FromE = FromE->IgnoreParenImpCasts();
11070 switch (FromE->getStmtClass()) {
11071 default:
11072 break;
11073 case Stmt::ObjCStringLiteralClass:
11074 // "string literal"
11075 return LK_String;
11076 case Stmt::ObjCArrayLiteralClass:
11077 // "array literal"
11078 return LK_Array;
11079 case Stmt::ObjCDictionaryLiteralClass:
11080 // "dictionary literal"
11081 return LK_Dictionary;
11082 case Stmt::BlockExprClass:
11083 return LK_Block;
11084 case Stmt::ObjCBoxedExprClass: {
11085 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
11086 switch (Inner->getStmtClass()) {
11087 case Stmt::IntegerLiteralClass:
11088 case Stmt::FloatingLiteralClass:
11089 case Stmt::CharacterLiteralClass:
11090 case Stmt::ObjCBoolLiteralExprClass:
11091 case Stmt::CXXBoolLiteralExprClass:
11092 // "numeric literal"
11093 return LK_Numeric;
11094 case Stmt::ImplicitCastExprClass: {
11095 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
11096 // Boolean literals can be represented by implicit casts.
11097 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
11098 return LK_Numeric;
11099 break;
11100 }
11101 default:
11102 break;
11103 }
11104 return LK_Boxed;
11105 }
11106 }
11107 return LK_None;
11108 }
11109
diagnoseObjCLiteralComparison(Sema & S,SourceLocation Loc,ExprResult & LHS,ExprResult & RHS,BinaryOperator::Opcode Opc)11110 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
11111 ExprResult &LHS, ExprResult &RHS,
11112 BinaryOperator::Opcode Opc){
11113 Expr *Literal;
11114 Expr *Other;
11115 if (isObjCObjectLiteral(LHS)) {
11116 Literal = LHS.get();
11117 Other = RHS.get();
11118 } else {
11119 Literal = RHS.get();
11120 Other = LHS.get();
11121 }
11122
11123 // Don't warn on comparisons against nil.
11124 Other = Other->IgnoreParenCasts();
11125 if (Other->isNullPointerConstant(S.getASTContext(),
11126 Expr::NPC_ValueDependentIsNotNull))
11127 return;
11128
11129 // This should be kept in sync with warn_objc_literal_comparison.
11130 // LK_String should always be after the other literals, since it has its own
11131 // warning flag.
11132 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
11133 assert(LiteralKind != Sema::LK_Block);
11134 if (LiteralKind == Sema::LK_None) {
11135 llvm_unreachable("Unknown Objective-C object literal kind");
11136 }
11137
11138 if (LiteralKind == Sema::LK_String)
11139 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11140 << Literal->getSourceRange();
11141 else
11142 S.Diag(Loc, diag::warn_objc_literal_comparison)
11143 << LiteralKind << Literal->getSourceRange();
11144
11145 if (BinaryOperator::isEqualityOp(Opc) &&
11146 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11147 SourceLocation Start = LHS.get()->getBeginLoc();
11148 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
11149 CharSourceRange OpRange =
11150 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
11151
11152 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11153 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11154 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11155 << FixItHint::CreateInsertion(End, "]");
11156 }
11157 }
11158
11159 /// 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)11160 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
11161 ExprResult &RHS, SourceLocation Loc,
11162 BinaryOperatorKind Opc) {
11163 // Check that left hand side is !something.
11164 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11165 if (!UO || UO->getOpcode() != UO_LNot) return;
11166
11167 // Only check if the right hand side is non-bool arithmetic type.
11168 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11169
11170 // Make sure that the something in !something is not bool.
11171 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11172 if (SubExpr->isKnownToHaveBooleanValue()) return;
11173
11174 // Emit warning.
11175 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11176 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11177 << Loc << IsBitwiseOp;
11178
11179 // First note suggest !(x < y)
11180 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11181 SourceLocation FirstClose = RHS.get()->getEndLoc();
11182 FirstClose = S.getLocForEndOfToken(FirstClose);
11183 if (FirstClose.isInvalid())
11184 FirstOpen = SourceLocation();
11185 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11186 << IsBitwiseOp
11187 << FixItHint::CreateInsertion(FirstOpen, "(")
11188 << FixItHint::CreateInsertion(FirstClose, ")");
11189
11190 // Second note suggests (!x) < y
11191 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11192 SourceLocation SecondClose = LHS.get()->getEndLoc();
11193 SecondClose = S.getLocForEndOfToken(SecondClose);
11194 if (SecondClose.isInvalid())
11195 SecondOpen = SourceLocation();
11196 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11197 << FixItHint::CreateInsertion(SecondOpen, "(")
11198 << FixItHint::CreateInsertion(SecondClose, ")");
11199 }
11200
11201 // Returns true if E refers to a non-weak array.
checkForArray(const Expr * E)11202 static bool checkForArray(const Expr *E) {
11203 const ValueDecl *D = nullptr;
11204 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11205 D = DR->getDecl();
11206 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11207 if (Mem->isImplicitAccess())
11208 D = Mem->getMemberDecl();
11209 }
11210 if (!D)
11211 return false;
11212 return D->getType()->isArrayType() && !D->isWeak();
11213 }
11214
11215 /// Diagnose some forms of syntactically-obvious tautological comparison.
diagnoseTautologicalComparison(Sema & S,SourceLocation Loc,Expr * LHS,Expr * RHS,BinaryOperatorKind Opc)11216 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
11217 Expr *LHS, Expr *RHS,
11218 BinaryOperatorKind Opc) {
11219 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11220 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11221
11222 QualType LHSType = LHS->getType();
11223 QualType RHSType = RHS->getType();
11224 if (LHSType->hasFloatingRepresentation() ||
11225 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11226 S.inTemplateInstantiation())
11227 return;
11228
11229 // Comparisons between two array types are ill-formed for operator<=>, so
11230 // we shouldn't emit any additional warnings about it.
11231 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11232 return;
11233
11234 // For non-floating point types, check for self-comparisons of the form
11235 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11236 // often indicate logic errors in the program.
11237 //
11238 // NOTE: Don't warn about comparison expressions resulting from macro
11239 // expansion. Also don't warn about comparisons which are only self
11240 // comparisons within a template instantiation. The warnings should catch
11241 // obvious cases in the definition of the template anyways. The idea is to
11242 // warn when the typed comparison operator will always evaluate to the same
11243 // result.
11244
11245 // Used for indexing into %select in warn_comparison_always
11246 enum {
11247 AlwaysConstant,
11248 AlwaysTrue,
11249 AlwaysFalse,
11250 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11251 };
11252
11253 // C++2a [depr.array.comp]:
11254 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11255 // operands of array type are deprecated.
11256 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11257 RHSStripped->getType()->isArrayType()) {
11258 S.Diag(Loc, diag::warn_depr_array_comparison)
11259 << LHS->getSourceRange() << RHS->getSourceRange()
11260 << LHSStripped->getType() << RHSStripped->getType();
11261 // Carry on to produce the tautological comparison warning, if this
11262 // expression is potentially-evaluated, we can resolve the array to a
11263 // non-weak declaration, and so on.
11264 }
11265
11266 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11267 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11268 unsigned Result;
11269 switch (Opc) {
11270 case BO_EQ:
11271 case BO_LE:
11272 case BO_GE:
11273 Result = AlwaysTrue;
11274 break;
11275 case BO_NE:
11276 case BO_LT:
11277 case BO_GT:
11278 Result = AlwaysFalse;
11279 break;
11280 case BO_Cmp:
11281 Result = AlwaysEqual;
11282 break;
11283 default:
11284 Result = AlwaysConstant;
11285 break;
11286 }
11287 S.DiagRuntimeBehavior(Loc, nullptr,
11288 S.PDiag(diag::warn_comparison_always)
11289 << 0 /*self-comparison*/
11290 << Result);
11291 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11292 // What is it always going to evaluate to?
11293 unsigned Result;
11294 switch (Opc) {
11295 case BO_EQ: // e.g. array1 == array2
11296 Result = AlwaysFalse;
11297 break;
11298 case BO_NE: // e.g. array1 != array2
11299 Result = AlwaysTrue;
11300 break;
11301 default: // e.g. array1 <= array2
11302 // The best we can say is 'a constant'
11303 Result = AlwaysConstant;
11304 break;
11305 }
11306 S.DiagRuntimeBehavior(Loc, nullptr,
11307 S.PDiag(diag::warn_comparison_always)
11308 << 1 /*array comparison*/
11309 << Result);
11310 }
11311 }
11312
11313 if (isa<CastExpr>(LHSStripped))
11314 LHSStripped = LHSStripped->IgnoreParenCasts();
11315 if (isa<CastExpr>(RHSStripped))
11316 RHSStripped = RHSStripped->IgnoreParenCasts();
11317
11318 // Warn about comparisons against a string constant (unless the other
11319 // operand is null); the user probably wants string comparison function.
11320 Expr *LiteralString = nullptr;
11321 Expr *LiteralStringStripped = nullptr;
11322 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11323 !RHSStripped->isNullPointerConstant(S.Context,
11324 Expr::NPC_ValueDependentIsNull)) {
11325 LiteralString = LHS;
11326 LiteralStringStripped = LHSStripped;
11327 } else if ((isa<StringLiteral>(RHSStripped) ||
11328 isa<ObjCEncodeExpr>(RHSStripped)) &&
11329 !LHSStripped->isNullPointerConstant(S.Context,
11330 Expr::NPC_ValueDependentIsNull)) {
11331 LiteralString = RHS;
11332 LiteralStringStripped = RHSStripped;
11333 }
11334
11335 if (LiteralString) {
11336 S.DiagRuntimeBehavior(Loc, nullptr,
11337 S.PDiag(diag::warn_stringcompare)
11338 << isa<ObjCEncodeExpr>(LiteralStringStripped)
11339 << LiteralString->getSourceRange());
11340 }
11341 }
11342
castKindToImplicitConversionKind(CastKind CK)11343 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
11344 switch (CK) {
11345 default: {
11346 #ifndef NDEBUG
11347 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11348 << "\n";
11349 #endif
11350 llvm_unreachable("unhandled cast kind");
11351 }
11352 case CK_UserDefinedConversion:
11353 return ICK_Identity;
11354 case CK_LValueToRValue:
11355 return ICK_Lvalue_To_Rvalue;
11356 case CK_ArrayToPointerDecay:
11357 return ICK_Array_To_Pointer;
11358 case CK_FunctionToPointerDecay:
11359 return ICK_Function_To_Pointer;
11360 case CK_IntegralCast:
11361 return ICK_Integral_Conversion;
11362 case CK_FloatingCast:
11363 return ICK_Floating_Conversion;
11364 case CK_IntegralToFloating:
11365 case CK_FloatingToIntegral:
11366 return ICK_Floating_Integral;
11367 case CK_IntegralComplexCast:
11368 case CK_FloatingComplexCast:
11369 case CK_FloatingComplexToIntegralComplex:
11370 case CK_IntegralComplexToFloatingComplex:
11371 return ICK_Complex_Conversion;
11372 case CK_FloatingComplexToReal:
11373 case CK_FloatingRealToComplex:
11374 case CK_IntegralComplexToReal:
11375 case CK_IntegralRealToComplex:
11376 return ICK_Complex_Real;
11377 }
11378 }
11379
checkThreeWayNarrowingConversion(Sema & S,QualType ToType,Expr * E,QualType FromType,SourceLocation Loc)11380 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
11381 QualType FromType,
11382 SourceLocation Loc) {
11383 // Check for a narrowing implicit conversion.
11384 StandardConversionSequence SCS;
11385 SCS.setAsIdentityConversion();
11386 SCS.setToType(0, FromType);
11387 SCS.setToType(1, ToType);
11388 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11389 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11390
11391 APValue PreNarrowingValue;
11392 QualType PreNarrowingType;
11393 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11394 PreNarrowingType,
11395 /*IgnoreFloatToIntegralConversion*/ true)) {
11396 case NK_Dependent_Narrowing:
11397 // Implicit conversion to a narrower type, but the expression is
11398 // value-dependent so we can't tell whether it's actually narrowing.
11399 case NK_Not_Narrowing:
11400 return false;
11401
11402 case NK_Constant_Narrowing:
11403 // Implicit conversion to a narrower type, and the value is not a constant
11404 // expression.
11405 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11406 << /*Constant*/ 1
11407 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11408 return true;
11409
11410 case NK_Variable_Narrowing:
11411 // Implicit conversion to a narrower type, and the value is not a constant
11412 // expression.
11413 case NK_Type_Narrowing:
11414 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11415 << /*Constant*/ 0 << FromType << ToType;
11416 // TODO: It's not a constant expression, but what if the user intended it
11417 // to be? Can we produce notes to help them figure out why it isn't?
11418 return true;
11419 }
11420 llvm_unreachable("unhandled case in switch");
11421 }
11422
checkArithmeticOrEnumeralThreeWayCompare(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)11423 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
11424 ExprResult &LHS,
11425 ExprResult &RHS,
11426 SourceLocation Loc) {
11427 QualType LHSType = LHS.get()->getType();
11428 QualType RHSType = RHS.get()->getType();
11429 // Dig out the original argument type and expression before implicit casts
11430 // were applied. These are the types/expressions we need to check the
11431 // [expr.spaceship] requirements against.
11432 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11433 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11434 QualType LHSStrippedType = LHSStripped.get()->getType();
11435 QualType RHSStrippedType = RHSStripped.get()->getType();
11436
11437 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11438 // other is not, the program is ill-formed.
11439 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11440 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11441 return QualType();
11442 }
11443
11444 // FIXME: Consider combining this with checkEnumArithmeticConversions.
11445 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11446 RHSStrippedType->isEnumeralType();
11447 if (NumEnumArgs == 1) {
11448 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11449 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11450 if (OtherTy->hasFloatingRepresentation()) {
11451 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11452 return QualType();
11453 }
11454 }
11455 if (NumEnumArgs == 2) {
11456 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11457 // type E, the operator yields the result of converting the operands
11458 // to the underlying type of E and applying <=> to the converted operands.
11459 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11460 S.InvalidOperands(Loc, LHS, RHS);
11461 return QualType();
11462 }
11463 QualType IntType =
11464 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11465 assert(IntType->isArithmeticType());
11466
11467 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11468 // promote the boolean type, and all other promotable integer types, to
11469 // avoid this.
11470 if (IntType->isPromotableIntegerType())
11471 IntType = S.Context.getPromotedIntegerType(IntType);
11472
11473 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11474 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11475 LHSType = RHSType = IntType;
11476 }
11477
11478 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11479 // usual arithmetic conversions are applied to the operands.
11480 QualType Type =
11481 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11482 if (LHS.isInvalid() || RHS.isInvalid())
11483 return QualType();
11484 if (Type.isNull())
11485 return S.InvalidOperands(Loc, LHS, RHS);
11486
11487 Optional<ComparisonCategoryType> CCT =
11488 getComparisonCategoryForBuiltinCmp(Type);
11489 if (!CCT)
11490 return S.InvalidOperands(Loc, LHS, RHS);
11491
11492 bool HasNarrowing = checkThreeWayNarrowingConversion(
11493 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11494 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11495 RHS.get()->getBeginLoc());
11496 if (HasNarrowing)
11497 return QualType();
11498
11499 assert(!Type.isNull() && "composite type for <=> has not been set");
11500
11501 return S.CheckComparisonCategoryType(
11502 *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);
11503 }
11504
checkArithmeticOrEnumeralCompare(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)11505 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
11506 ExprResult &RHS,
11507 SourceLocation Loc,
11508 BinaryOperatorKind Opc) {
11509 if (Opc == BO_Cmp)
11510 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11511
11512 // C99 6.5.8p3 / C99 6.5.9p4
11513 QualType Type =
11514 S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);
11515 if (LHS.isInvalid() || RHS.isInvalid())
11516 return QualType();
11517 if (Type.isNull())
11518 return S.InvalidOperands(Loc, LHS, RHS);
11519 assert(Type->isArithmeticType() || Type->isEnumeralType());
11520
11521 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
11522 return S.InvalidOperands(Loc, LHS, RHS);
11523
11524 // Check for comparisons of floating point operands using != and ==.
11525 if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
11526 S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
11527
11528 // The result of comparisons is 'bool' in C++, 'int' in C.
11529 return S.Context.getLogicalOperationType();
11530 }
11531
CheckPtrComparisonWithNullChar(ExprResult & E,ExprResult & NullE)11532 void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
11533 if (!NullE.get()->getType()->isAnyPointerType())
11534 return;
11535 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
11536 if (!E.get()->getType()->isAnyPointerType() &&
11537 E.get()->isNullPointerConstant(Context,
11538 Expr::NPC_ValueDependentIsNotNull) ==
11539 Expr::NPCK_ZeroExpression) {
11540 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
11541 if (CL->getValue() == 0)
11542 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11543 << NullValue
11544 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11545 NullValue ? "NULL" : "(void *)0");
11546 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
11547 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
11548 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
11549 if (T == Context.CharTy)
11550 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
11551 << NullValue
11552 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
11553 NullValue ? "NULL" : "(void *)0");
11554 }
11555 }
11556 }
11557
11558 // C99 6.5.8, C++ [expr.rel]
CheckCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)11559 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
11560 SourceLocation Loc,
11561 BinaryOperatorKind Opc) {
11562 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
11563 bool IsThreeWay = Opc == BO_Cmp;
11564 bool IsOrdered = IsRelational || IsThreeWay;
11565 auto IsAnyPointerType = [](ExprResult E) {
11566 QualType Ty = E.get()->getType();
11567 return Ty->isPointerType() || Ty->isMemberPointerType();
11568 };
11569
11570 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
11571 // type, array-to-pointer, ..., conversions are performed on both operands to
11572 // bring them to their composite type.
11573 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
11574 // any type-related checks.
11575 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
11576 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
11577 if (LHS.isInvalid())
11578 return QualType();
11579 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
11580 if (RHS.isInvalid())
11581 return QualType();
11582 } else {
11583 LHS = DefaultLvalueConversion(LHS.get());
11584 if (LHS.isInvalid())
11585 return QualType();
11586 RHS = DefaultLvalueConversion(RHS.get());
11587 if (RHS.isInvalid())
11588 return QualType();
11589 }
11590
11591 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
11592 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
11593 CheckPtrComparisonWithNullChar(LHS, RHS);
11594 CheckPtrComparisonWithNullChar(RHS, LHS);
11595 }
11596
11597 // Handle vector comparisons separately.
11598 if (LHS.get()->getType()->isVectorType() ||
11599 RHS.get()->getType()->isVectorType())
11600 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
11601
11602 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
11603 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
11604
11605 QualType LHSType = LHS.get()->getType();
11606 QualType RHSType = RHS.get()->getType();
11607 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
11608 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
11609 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
11610
11611 const Expr::NullPointerConstantKind LHSNullKind =
11612 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11613 const Expr::NullPointerConstantKind RHSNullKind =
11614 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
11615 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
11616 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
11617
11618 auto computeResultTy = [&]() {
11619 if (Opc != BO_Cmp)
11620 return Context.getLogicalOperationType();
11621 assert(getLangOpts().CPlusPlus);
11622 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
11623
11624 QualType CompositeTy = LHS.get()->getType();
11625 assert(!CompositeTy->isReferenceType());
11626
11627 Optional<ComparisonCategoryType> CCT =
11628 getComparisonCategoryForBuiltinCmp(CompositeTy);
11629 if (!CCT)
11630 return InvalidOperands(Loc, LHS, RHS);
11631
11632 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
11633 // P0946R0: Comparisons between a null pointer constant and an object
11634 // pointer result in std::strong_equality, which is ill-formed under
11635 // P1959R0.
11636 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
11637 << (LHSIsNull ? LHS.get()->getSourceRange()
11638 : RHS.get()->getSourceRange());
11639 return QualType();
11640 }
11641
11642 return CheckComparisonCategoryType(
11643 *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);
11644 };
11645
11646 if (!IsOrdered && LHSIsNull != RHSIsNull) {
11647 bool IsEquality = Opc == BO_EQ;
11648 if (RHSIsNull)
11649 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
11650 RHS.get()->getSourceRange());
11651 else
11652 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
11653 LHS.get()->getSourceRange());
11654 }
11655
11656 if ((LHSType->isIntegerType() && !LHSIsNull) ||
11657 (RHSType->isIntegerType() && !RHSIsNull)) {
11658 // Skip normal pointer conversion checks in this case; we have better
11659 // diagnostics for this below.
11660 } else if (getLangOpts().CPlusPlus) {
11661 // Equality comparison of a function pointer to a void pointer is invalid,
11662 // but we allow it as an extension.
11663 // FIXME: If we really want to allow this, should it be part of composite
11664 // pointer type computation so it works in conditionals too?
11665 if (!IsOrdered &&
11666 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
11667 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
11668 // This is a gcc extension compatibility comparison.
11669 // In a SFINAE context, we treat this as a hard error to maintain
11670 // conformance with the C++ standard.
11671 diagnoseFunctionPointerToVoidComparison(
11672 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
11673
11674 if (isSFINAEContext())
11675 return QualType();
11676
11677 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11678 return computeResultTy();
11679 }
11680
11681 // C++ [expr.eq]p2:
11682 // If at least one operand is a pointer [...] bring them to their
11683 // composite pointer type.
11684 // C++ [expr.spaceship]p6
11685 // If at least one of the operands is of pointer type, [...] bring them
11686 // to their composite pointer type.
11687 // C++ [expr.rel]p2:
11688 // If both operands are pointers, [...] bring them to their composite
11689 // pointer type.
11690 // For <=>, the only valid non-pointer types are arrays and functions, and
11691 // we already decayed those, so this is really the same as the relational
11692 // comparison rule.
11693 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
11694 (IsOrdered ? 2 : 1) &&
11695 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
11696 RHSType->isObjCObjectPointerType()))) {
11697 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11698 return QualType();
11699 return computeResultTy();
11700 }
11701 } else if (LHSType->isPointerType() &&
11702 RHSType->isPointerType()) { // C99 6.5.8p2
11703 // All of the following pointer-related warnings are GCC extensions, except
11704 // when handling null pointer constants.
11705 QualType LCanPointeeTy =
11706 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11707 QualType RCanPointeeTy =
11708 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
11709
11710 // C99 6.5.9p2 and C99 6.5.8p2
11711 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
11712 RCanPointeeTy.getUnqualifiedType())) {
11713 if (IsRelational) {
11714 // Pointers both need to point to complete or incomplete types
11715 if ((LCanPointeeTy->isIncompleteType() !=
11716 RCanPointeeTy->isIncompleteType()) &&
11717 !getLangOpts().C11) {
11718 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
11719 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
11720 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
11721 << RCanPointeeTy->isIncompleteType();
11722 }
11723 if (LCanPointeeTy->isFunctionType()) {
11724 // Valid unless a relational comparison of function pointers
11725 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
11726 << LHSType << RHSType << LHS.get()->getSourceRange()
11727 << RHS.get()->getSourceRange();
11728 }
11729 }
11730 } else if (!IsRelational &&
11731 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
11732 // Valid unless comparison between non-null pointer and function pointer
11733 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
11734 && !LHSIsNull && !RHSIsNull)
11735 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
11736 /*isError*/false);
11737 } else {
11738 // Invalid
11739 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
11740 }
11741 if (LCanPointeeTy != RCanPointeeTy) {
11742 // Treat NULL constant as a special case in OpenCL.
11743 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
11744 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
11745 Diag(Loc,
11746 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11747 << LHSType << RHSType << 0 /* comparison */
11748 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11749 }
11750 }
11751 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
11752 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
11753 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
11754 : CK_BitCast;
11755 if (LHSIsNull && !RHSIsNull)
11756 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
11757 else
11758 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
11759 }
11760 return computeResultTy();
11761 }
11762
11763 if (getLangOpts().CPlusPlus) {
11764 // C++ [expr.eq]p4:
11765 // Two operands of type std::nullptr_t or one operand of type
11766 // std::nullptr_t and the other a null pointer constant compare equal.
11767 if (!IsOrdered && LHSIsNull && RHSIsNull) {
11768 if (LHSType->isNullPtrType()) {
11769 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11770 return computeResultTy();
11771 }
11772 if (RHSType->isNullPtrType()) {
11773 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11774 return computeResultTy();
11775 }
11776 }
11777
11778 // Comparison of Objective-C pointers and block pointers against nullptr_t.
11779 // These aren't covered by the composite pointer type rules.
11780 if (!IsOrdered && RHSType->isNullPtrType() &&
11781 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
11782 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11783 return computeResultTy();
11784 }
11785 if (!IsOrdered && LHSType->isNullPtrType() &&
11786 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
11787 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11788 return computeResultTy();
11789 }
11790
11791 if (IsRelational &&
11792 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
11793 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
11794 // HACK: Relational comparison of nullptr_t against a pointer type is
11795 // invalid per DR583, but we allow it within std::less<> and friends,
11796 // since otherwise common uses of it break.
11797 // FIXME: Consider removing this hack once LWG fixes std::less<> and
11798 // friends to have std::nullptr_t overload candidates.
11799 DeclContext *DC = CurContext;
11800 if (isa<FunctionDecl>(DC))
11801 DC = DC->getParent();
11802 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
11803 if (CTSD->isInStdNamespace() &&
11804 llvm::StringSwitch<bool>(CTSD->getName())
11805 .Cases("less", "less_equal", "greater", "greater_equal", true)
11806 .Default(false)) {
11807 if (RHSType->isNullPtrType())
11808 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11809 else
11810 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11811 return computeResultTy();
11812 }
11813 }
11814 }
11815
11816 // C++ [expr.eq]p2:
11817 // If at least one operand is a pointer to member, [...] bring them to
11818 // their composite pointer type.
11819 if (!IsOrdered &&
11820 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
11821 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
11822 return QualType();
11823 else
11824 return computeResultTy();
11825 }
11826 }
11827
11828 // Handle block pointer types.
11829 if (!IsOrdered && LHSType->isBlockPointerType() &&
11830 RHSType->isBlockPointerType()) {
11831 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
11832 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
11833
11834 if (!LHSIsNull && !RHSIsNull &&
11835 !Context.typesAreCompatible(lpointee, rpointee)) {
11836 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11837 << LHSType << RHSType << LHS.get()->getSourceRange()
11838 << RHS.get()->getSourceRange();
11839 }
11840 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11841 return computeResultTy();
11842 }
11843
11844 // Allow block pointers to be compared with null pointer constants.
11845 if (!IsOrdered
11846 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
11847 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
11848 if (!LHSIsNull && !RHSIsNull) {
11849 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
11850 ->getPointeeType()->isVoidType())
11851 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
11852 ->getPointeeType()->isVoidType())))
11853 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
11854 << LHSType << RHSType << LHS.get()->getSourceRange()
11855 << RHS.get()->getSourceRange();
11856 }
11857 if (LHSIsNull && !RHSIsNull)
11858 LHS = ImpCastExprToType(LHS.get(), RHSType,
11859 RHSType->isPointerType() ? CK_BitCast
11860 : CK_AnyPointerToBlockPointerCast);
11861 else
11862 RHS = ImpCastExprToType(RHS.get(), LHSType,
11863 LHSType->isPointerType() ? CK_BitCast
11864 : CK_AnyPointerToBlockPointerCast);
11865 return computeResultTy();
11866 }
11867
11868 if (LHSType->isObjCObjectPointerType() ||
11869 RHSType->isObjCObjectPointerType()) {
11870 const PointerType *LPT = LHSType->getAs<PointerType>();
11871 const PointerType *RPT = RHSType->getAs<PointerType>();
11872 if (LPT || RPT) {
11873 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
11874 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
11875
11876 if (!LPtrToVoid && !RPtrToVoid &&
11877 !Context.typesAreCompatible(LHSType, RHSType)) {
11878 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11879 /*isError*/false);
11880 }
11881 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
11882 // the RHS, but we have test coverage for this behavior.
11883 // FIXME: Consider using convertPointersToCompositeType in C++.
11884 if (LHSIsNull && !RHSIsNull) {
11885 Expr *E = LHS.get();
11886 if (getLangOpts().ObjCAutoRefCount)
11887 CheckObjCConversion(SourceRange(), RHSType, E,
11888 CCK_ImplicitConversion);
11889 LHS = ImpCastExprToType(E, RHSType,
11890 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11891 }
11892 else {
11893 Expr *E = RHS.get();
11894 if (getLangOpts().ObjCAutoRefCount)
11895 CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
11896 /*Diagnose=*/true,
11897 /*DiagnoseCFAudited=*/false, Opc);
11898 RHS = ImpCastExprToType(E, LHSType,
11899 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
11900 }
11901 return computeResultTy();
11902 }
11903 if (LHSType->isObjCObjectPointerType() &&
11904 RHSType->isObjCObjectPointerType()) {
11905 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
11906 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
11907 /*isError*/false);
11908 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
11909 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
11910
11911 if (LHSIsNull && !RHSIsNull)
11912 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
11913 else
11914 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
11915 return computeResultTy();
11916 }
11917
11918 if (!IsOrdered && LHSType->isBlockPointerType() &&
11919 RHSType->isBlockCompatibleObjCPointerType(Context)) {
11920 LHS = ImpCastExprToType(LHS.get(), RHSType,
11921 CK_BlockPointerToObjCPointerCast);
11922 return computeResultTy();
11923 } else if (!IsOrdered &&
11924 LHSType->isBlockCompatibleObjCPointerType(Context) &&
11925 RHSType->isBlockPointerType()) {
11926 RHS = ImpCastExprToType(RHS.get(), LHSType,
11927 CK_BlockPointerToObjCPointerCast);
11928 return computeResultTy();
11929 }
11930 }
11931 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
11932 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
11933 unsigned DiagID = 0;
11934 bool isError = false;
11935 if (LangOpts.DebuggerSupport) {
11936 // Under a debugger, allow the comparison of pointers to integers,
11937 // since users tend to want to compare addresses.
11938 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
11939 (RHSIsNull && RHSType->isIntegerType())) {
11940 if (IsOrdered) {
11941 isError = getLangOpts().CPlusPlus;
11942 DiagID =
11943 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
11944 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
11945 }
11946 } else if (getLangOpts().CPlusPlus) {
11947 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
11948 isError = true;
11949 } else if (IsOrdered)
11950 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
11951 else
11952 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
11953
11954 if (DiagID) {
11955 Diag(Loc, DiagID)
11956 << LHSType << RHSType << LHS.get()->getSourceRange()
11957 << RHS.get()->getSourceRange();
11958 if (isError)
11959 return QualType();
11960 }
11961
11962 if (LHSType->isIntegerType())
11963 LHS = ImpCastExprToType(LHS.get(), RHSType,
11964 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11965 else
11966 RHS = ImpCastExprToType(RHS.get(), LHSType,
11967 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
11968 return computeResultTy();
11969 }
11970
11971 // Handle block pointers.
11972 if (!IsOrdered && RHSIsNull
11973 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
11974 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11975 return computeResultTy();
11976 }
11977 if (!IsOrdered && LHSIsNull
11978 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
11979 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11980 return computeResultTy();
11981 }
11982
11983 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
11984 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
11985 return computeResultTy();
11986 }
11987
11988 if (LHSType->isQueueT() && RHSType->isQueueT()) {
11989 return computeResultTy();
11990 }
11991
11992 if (LHSIsNull && RHSType->isQueueT()) {
11993 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
11994 return computeResultTy();
11995 }
11996
11997 if (LHSType->isQueueT() && RHSIsNull) {
11998 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
11999 return computeResultTy();
12000 }
12001 }
12002
12003 return InvalidOperands(Loc, LHS, RHS);
12004 }
12005
12006 // Return a signed ext_vector_type that is of identical size and number of
12007 // elements. For floating point vectors, return an integer type of identical
12008 // size and number of elements. In the non ext_vector_type case, search from
12009 // the largest type to the smallest type to avoid cases where long long == long,
12010 // where long gets picked over long long.
GetSignedVectorType(QualType V)12011 QualType Sema::GetSignedVectorType(QualType V) {
12012 const VectorType *VTy = V->castAs<VectorType>();
12013 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12014
12015 if (isa<ExtVectorType>(VTy)) {
12016 if (TypeSize == Context.getTypeSize(Context.CharTy))
12017 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
12018 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12019 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
12020 else if (TypeSize == Context.getTypeSize(Context.IntTy))
12021 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
12022 else if (TypeSize == Context.getTypeSize(Context.LongTy))
12023 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
12024 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12025 "Unhandled vector element size in vector compare");
12026 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
12027 }
12028
12029 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12030 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
12031 VectorType::GenericVector);
12032 else if (TypeSize == Context.getTypeSize(Context.LongTy))
12033 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
12034 VectorType::GenericVector);
12035 else if (TypeSize == Context.getTypeSize(Context.IntTy))
12036 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
12037 VectorType::GenericVector);
12038 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
12039 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
12040 VectorType::GenericVector);
12041 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12042 "Unhandled vector element size in vector compare");
12043 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
12044 VectorType::GenericVector);
12045 }
12046
12047 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
12048 /// operates on extended vector types. Instead of producing an IntTy result,
12049 /// like a scalar comparison, a vector comparison produces a vector of integer
12050 /// types.
CheckVectorCompareOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)12051 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12052 SourceLocation Loc,
12053 BinaryOperatorKind Opc) {
12054 if (Opc == BO_Cmp) {
12055 Diag(Loc, diag::err_three_way_vector_comparison);
12056 return QualType();
12057 }
12058
12059 // Check to make sure we're operating on vectors of the same type and width,
12060 // Allowing one side to be a scalar of element type.
12061 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
12062 /*AllowBothBool*/true,
12063 /*AllowBoolConversions*/getLangOpts().ZVector);
12064 if (vType.isNull())
12065 return vType;
12066
12067 QualType LHSType = LHS.get()->getType();
12068
12069 // If AltiVec, the comparison results in a numeric type, i.e.
12070 // bool for C++, int for C
12071 if (getLangOpts().AltiVec &&
12072 vType->castAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
12073 return Context.getLogicalOperationType();
12074
12075 // For non-floating point types, check for self-comparisons of the form
12076 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12077 // often indicate logic errors in the program.
12078 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12079
12080 // Check for comparisons of floating point operands using != and ==.
12081 if (BinaryOperator::isEqualityOp(Opc) &&
12082 LHSType->hasFloatingRepresentation()) {
12083 assert(RHS.get()->getType()->hasFloatingRepresentation());
12084 CheckFloatComparison(Loc, LHS.get(), RHS.get());
12085 }
12086
12087 // Return a signed type for the vector.
12088 return GetSignedVectorType(vType);
12089 }
12090
diagnoseXorMisusedAsPow(Sema & S,const ExprResult & XorLHS,const ExprResult & XorRHS,const SourceLocation Loc)12091 static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12092 const ExprResult &XorRHS,
12093 const SourceLocation Loc) {
12094 // Do not diagnose macros.
12095 if (Loc.isMacroID())
12096 return;
12097
12098 bool Negative = false;
12099 bool ExplicitPlus = false;
12100 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12101 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12102
12103 if (!LHSInt)
12104 return;
12105 if (!RHSInt) {
12106 // Check negative literals.
12107 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12108 UnaryOperatorKind Opc = UO->getOpcode();
12109 if (Opc != UO_Minus && Opc != UO_Plus)
12110 return;
12111 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12112 if (!RHSInt)
12113 return;
12114 Negative = (Opc == UO_Minus);
12115 ExplicitPlus = !Negative;
12116 } else {
12117 return;
12118 }
12119 }
12120
12121 const llvm::APInt &LeftSideValue = LHSInt->getValue();
12122 llvm::APInt RightSideValue = RHSInt->getValue();
12123 if (LeftSideValue != 2 && LeftSideValue != 10)
12124 return;
12125
12126 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12127 return;
12128
12129 CharSourceRange ExprRange = CharSourceRange::getCharRange(
12130 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12131 llvm::StringRef ExprStr =
12132 Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());
12133
12134 CharSourceRange XorRange =
12135 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
12136 llvm::StringRef XorStr =
12137 Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());
12138 // Do not diagnose if xor keyword/macro is used.
12139 if (XorStr == "xor")
12140 return;
12141
12142 std::string LHSStr = std::string(Lexer::getSourceText(
12143 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12144 S.getSourceManager(), S.getLangOpts()));
12145 std::string RHSStr = std::string(Lexer::getSourceText(
12146 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12147 S.getSourceManager(), S.getLangOpts()));
12148
12149 if (Negative) {
12150 RightSideValue = -RightSideValue;
12151 RHSStr = "-" + RHSStr;
12152 } else if (ExplicitPlus) {
12153 RHSStr = "+" + RHSStr;
12154 }
12155
12156 StringRef LHSStrRef = LHSStr;
12157 StringRef RHSStrRef = RHSStr;
12158 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12159 // literals.
12160 if (LHSStrRef.startswith("0b") || LHSStrRef.startswith("0B") ||
12161 RHSStrRef.startswith("0b") || RHSStrRef.startswith("0B") ||
12162 LHSStrRef.startswith("0x") || LHSStrRef.startswith("0X") ||
12163 RHSStrRef.startswith("0x") || RHSStrRef.startswith("0X") ||
12164 (LHSStrRef.size() > 1 && LHSStrRef.startswith("0")) ||
12165 (RHSStrRef.size() > 1 && RHSStrRef.startswith("0")) ||
12166 LHSStrRef.find('\'') != StringRef::npos ||
12167 RHSStrRef.find('\'') != StringRef::npos)
12168 return;
12169
12170 bool SuggestXor = S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12171 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12172 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12173 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12174 std::string SuggestedExpr = "1 << " + RHSStr;
12175 bool Overflow = false;
12176 llvm::APInt One = (LeftSideValue - 1);
12177 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12178 if (Overflow) {
12179 if (RightSideIntValue < 64)
12180 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12181 << ExprStr << XorValue.toString(10, true) << ("1LL << " + RHSStr)
12182 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12183 else if (RightSideIntValue == 64)
12184 S.Diag(Loc, diag::warn_xor_used_as_pow) << ExprStr << XorValue.toString(10, true);
12185 else
12186 return;
12187 } else {
12188 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12189 << ExprStr << XorValue.toString(10, true) << SuggestedExpr
12190 << PowValue.toString(10, true)
12191 << FixItHint::CreateReplacement(
12192 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12193 }
12194
12195 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0x2 ^ " + RHSStr) << SuggestXor;
12196 } else if (LeftSideValue == 10) {
12197 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12198 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12199 << ExprStr << XorValue.toString(10, true) << SuggestedValue
12200 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12201 S.Diag(Loc, diag::note_xor_used_as_pow_silence) << ("0xA ^ " + RHSStr) << SuggestXor;
12202 }
12203 }
12204
CheckVectorLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)12205 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12206 SourceLocation Loc) {
12207 // Ensure that either both operands are of the same vector type, or
12208 // one operand is of a vector type and the other is of its element type.
12209 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12210 /*AllowBothBool*/true,
12211 /*AllowBoolConversions*/false);
12212 if (vType.isNull())
12213 return InvalidOperands(Loc, LHS, RHS);
12214 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
12215 !getLangOpts().OpenCLCPlusPlus && vType->hasFloatingRepresentation())
12216 return InvalidOperands(Loc, LHS, RHS);
12217 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12218 // usage of the logical operators && and || with vectors in C. This
12219 // check could be notionally dropped.
12220 if (!getLangOpts().CPlusPlus &&
12221 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12222 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12223
12224 return GetSignedVectorType(LHS.get()->getType());
12225 }
12226
CheckMatrixElementwiseOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)12227 QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12228 SourceLocation Loc,
12229 bool IsCompAssign) {
12230 if (!IsCompAssign) {
12231 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12232 if (LHS.isInvalid())
12233 return QualType();
12234 }
12235 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12236 if (RHS.isInvalid())
12237 return QualType();
12238
12239 // For conversion purposes, we ignore any qualifiers.
12240 // For example, "const float" and "float" are equivalent.
12241 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12242 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12243
12244 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12245 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12246 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12247
12248 if (Context.hasSameType(LHSType, RHSType))
12249 return LHSType;
12250
12251 // Type conversion may change LHS/RHS. Keep copies to the original results, in
12252 // case we have to return InvalidOperands.
12253 ExprResult OriginalLHS = LHS;
12254 ExprResult OriginalRHS = RHS;
12255 if (LHSMatType && !RHSMatType) {
12256 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12257 if (!RHS.isInvalid())
12258 return LHSType;
12259
12260 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12261 }
12262
12263 if (!LHSMatType && RHSMatType) {
12264 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12265 if (!LHS.isInvalid())
12266 return RHSType;
12267 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12268 }
12269
12270 return InvalidOperands(Loc, LHS, RHS);
12271 }
12272
CheckMatrixMultiplyOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,bool IsCompAssign)12273 QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12274 SourceLocation Loc,
12275 bool IsCompAssign) {
12276 if (!IsCompAssign) {
12277 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
12278 if (LHS.isInvalid())
12279 return QualType();
12280 }
12281 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
12282 if (RHS.isInvalid())
12283 return QualType();
12284
12285 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12286 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12287 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12288
12289 if (LHSMatType && RHSMatType) {
12290 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12291 return InvalidOperands(Loc, LHS, RHS);
12292
12293 if (!Context.hasSameType(LHSMatType->getElementType(),
12294 RHSMatType->getElementType()))
12295 return InvalidOperands(Loc, LHS, RHS);
12296
12297 return Context.getConstantMatrixType(LHSMatType->getElementType(),
12298 LHSMatType->getNumRows(),
12299 RHSMatType->getNumColumns());
12300 }
12301 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12302 }
12303
CheckBitwiseOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)12304 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
12305 SourceLocation Loc,
12306 BinaryOperatorKind Opc) {
12307 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12308
12309 bool IsCompAssign =
12310 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12311
12312 if (LHS.get()->getType()->isVectorType() ||
12313 RHS.get()->getType()->isVectorType()) {
12314 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12315 RHS.get()->getType()->hasIntegerRepresentation())
12316 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12317 /*AllowBothBool*/true,
12318 /*AllowBoolConversions*/getLangOpts().ZVector);
12319 return InvalidOperands(Loc, LHS, RHS);
12320 }
12321
12322 if (Opc == BO_And)
12323 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12324
12325 if (LHS.get()->getType()->hasFloatingRepresentation() ||
12326 RHS.get()->getType()->hasFloatingRepresentation())
12327 return InvalidOperands(Loc, LHS, RHS);
12328
12329 ExprResult LHSResult = LHS, RHSResult = RHS;
12330 QualType compType = UsualArithmeticConversions(
12331 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12332 if (LHSResult.isInvalid() || RHSResult.isInvalid())
12333 return QualType();
12334 LHS = LHSResult.get();
12335 RHS = RHSResult.get();
12336
12337 if (Opc == BO_Xor)
12338 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12339
12340 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12341 return compType;
12342 return InvalidOperands(Loc, LHS, RHS);
12343 }
12344
12345 // C99 6.5.[13,14]
CheckLogicalOperands(ExprResult & LHS,ExprResult & RHS,SourceLocation Loc,BinaryOperatorKind Opc)12346 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12347 SourceLocation Loc,
12348 BinaryOperatorKind Opc) {
12349 // Check vector operands differently.
12350 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
12351 return CheckVectorLogicalOperands(LHS, RHS, Loc);
12352
12353 bool EnumConstantInBoolContext = false;
12354 for (const ExprResult &HS : {LHS, RHS}) {
12355 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12356 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12357 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12358 EnumConstantInBoolContext = true;
12359 }
12360 }
12361
12362 if (EnumConstantInBoolContext)
12363 Diag(Loc, diag::warn_enum_constant_in_bool_context);
12364
12365 // Diagnose cases where the user write a logical and/or but probably meant a
12366 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
12367 // is a constant.
12368 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
12369 !LHS.get()->getType()->isBooleanType() &&
12370 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
12371 // Don't warn in macros or template instantiations.
12372 !Loc.isMacroID() && !inTemplateInstantiation()) {
12373 // If the RHS can be constant folded, and if it constant folds to something
12374 // that isn't 0 or 1 (which indicate a potential logical operation that
12375 // happened to fold to true/false) then warn.
12376 // Parens on the RHS are ignored.
12377 Expr::EvalResult EVResult;
12378 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
12379 llvm::APSInt Result = EVResult.Val.getInt();
12380 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
12381 !RHS.get()->getExprLoc().isMacroID()) ||
12382 (Result != 0 && Result != 1)) {
12383 Diag(Loc, diag::warn_logical_instead_of_bitwise)
12384 << RHS.get()->getSourceRange()
12385 << (Opc == BO_LAnd ? "&&" : "||");
12386 // Suggest replacing the logical operator with the bitwise version
12387 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
12388 << (Opc == BO_LAnd ? "&" : "|")
12389 << FixItHint::CreateReplacement(SourceRange(
12390 Loc, getLocForEndOfToken(Loc)),
12391 Opc == BO_LAnd ? "&" : "|");
12392 if (Opc == BO_LAnd)
12393 // Suggest replacing "Foo() && kNonZero" with "Foo()"
12394 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
12395 << FixItHint::CreateRemoval(
12396 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
12397 RHS.get()->getEndLoc()));
12398 }
12399 }
12400 }
12401
12402 if (!Context.getLangOpts().CPlusPlus) {
12403 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
12404 // not operate on the built-in scalar and vector float types.
12405 if (Context.getLangOpts().OpenCL &&
12406 Context.getLangOpts().OpenCLVersion < 120) {
12407 if (LHS.get()->getType()->isFloatingType() ||
12408 RHS.get()->getType()->isFloatingType())
12409 return InvalidOperands(Loc, LHS, RHS);
12410 }
12411
12412 LHS = UsualUnaryConversions(LHS.get());
12413 if (LHS.isInvalid())
12414 return QualType();
12415
12416 RHS = UsualUnaryConversions(RHS.get());
12417 if (RHS.isInvalid())
12418 return QualType();
12419
12420 if (!LHS.get()->getType()->isScalarType() ||
12421 !RHS.get()->getType()->isScalarType())
12422 return InvalidOperands(Loc, LHS, RHS);
12423
12424 return Context.IntTy;
12425 }
12426
12427 // The following is safe because we only use this method for
12428 // non-overloadable operands.
12429
12430 // C++ [expr.log.and]p1
12431 // C++ [expr.log.or]p1
12432 // The operands are both contextually converted to type bool.
12433 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
12434 if (LHSRes.isInvalid())
12435 return InvalidOperands(Loc, LHS, RHS);
12436 LHS = LHSRes;
12437
12438 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
12439 if (RHSRes.isInvalid())
12440 return InvalidOperands(Loc, LHS, RHS);
12441 RHS = RHSRes;
12442
12443 // C++ [expr.log.and]p2
12444 // C++ [expr.log.or]p2
12445 // The result is a bool.
12446 return Context.BoolTy;
12447 }
12448
IsReadonlyMessage(Expr * E,Sema & S)12449 static bool IsReadonlyMessage(Expr *E, Sema &S) {
12450 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12451 if (!ME) return false;
12452 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
12453 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
12454 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
12455 if (!Base) return false;
12456 return Base->getMethodDecl() != nullptr;
12457 }
12458
12459 /// Is the given expression (which must be 'const') a reference to a
12460 /// variable which was originally non-const, but which has become
12461 /// 'const' due to being captured within a block?
12462 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
isReferenceToNonConstCapture(Sema & S,Expr * E)12463 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
12464 assert(E->isLValue() && E->getType().isConstQualified());
12465 E = E->IgnoreParens();
12466
12467 // Must be a reference to a declaration from an enclosing scope.
12468 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
12469 if (!DRE) return NCCK_None;
12470 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
12471
12472 // The declaration must be a variable which is not declared 'const'.
12473 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
12474 if (!var) return NCCK_None;
12475 if (var->getType().isConstQualified()) return NCCK_None;
12476 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
12477
12478 // Decide whether the first capture was for a block or a lambda.
12479 DeclContext *DC = S.CurContext, *Prev = nullptr;
12480 // Decide whether the first capture was for a block or a lambda.
12481 while (DC) {
12482 // For init-capture, it is possible that the variable belongs to the
12483 // template pattern of the current context.
12484 if (auto *FD = dyn_cast<FunctionDecl>(DC))
12485 if (var->isInitCapture() &&
12486 FD->getTemplateInstantiationPattern() == var->getDeclContext())
12487 break;
12488 if (DC == var->getDeclContext())
12489 break;
12490 Prev = DC;
12491 DC = DC->getParent();
12492 }
12493 // Unless we have an init-capture, we've gone one step too far.
12494 if (!var->isInitCapture())
12495 DC = Prev;
12496 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
12497 }
12498
IsTypeModifiable(QualType Ty,bool IsDereference)12499 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
12500 Ty = Ty.getNonReferenceType();
12501 if (IsDereference && Ty->isPointerType())
12502 Ty = Ty->getPointeeType();
12503 return !Ty.isConstQualified();
12504 }
12505
12506 // Update err_typecheck_assign_const and note_typecheck_assign_const
12507 // when this enum is changed.
12508 enum {
12509 ConstFunction,
12510 ConstVariable,
12511 ConstMember,
12512 ConstMethod,
12513 NestedConstMember,
12514 ConstUnknown, // Keep as last element
12515 };
12516
12517 /// Emit the "read-only variable not assignable" error and print notes to give
12518 /// more information about why the variable is not assignable, such as pointing
12519 /// to the declaration of a const variable, showing that a method is const, or
12520 /// that the function is returning a const reference.
DiagnoseConstAssignment(Sema & S,const Expr * E,SourceLocation Loc)12521 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
12522 SourceLocation Loc) {
12523 SourceRange ExprRange = E->getSourceRange();
12524
12525 // Only emit one error on the first const found. All other consts will emit
12526 // a note to the error.
12527 bool DiagnosticEmitted = false;
12528
12529 // Track if the current expression is the result of a dereference, and if the
12530 // next checked expression is the result of a dereference.
12531 bool IsDereference = false;
12532 bool NextIsDereference = false;
12533
12534 // Loop to process MemberExpr chains.
12535 while (true) {
12536 IsDereference = NextIsDereference;
12537
12538 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
12539 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
12540 NextIsDereference = ME->isArrow();
12541 const ValueDecl *VD = ME->getMemberDecl();
12542 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
12543 // Mutable fields can be modified even if the class is const.
12544 if (Field->isMutable()) {
12545 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
12546 break;
12547 }
12548
12549 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
12550 if (!DiagnosticEmitted) {
12551 S.Diag(Loc, diag::err_typecheck_assign_const)
12552 << ExprRange << ConstMember << false /*static*/ << Field
12553 << Field->getType();
12554 DiagnosticEmitted = true;
12555 }
12556 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12557 << ConstMember << false /*static*/ << Field << Field->getType()
12558 << Field->getSourceRange();
12559 }
12560 E = ME->getBase();
12561 continue;
12562 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
12563 if (VDecl->getType().isConstQualified()) {
12564 if (!DiagnosticEmitted) {
12565 S.Diag(Loc, diag::err_typecheck_assign_const)
12566 << ExprRange << ConstMember << true /*static*/ << VDecl
12567 << VDecl->getType();
12568 DiagnosticEmitted = true;
12569 }
12570 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12571 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
12572 << VDecl->getSourceRange();
12573 }
12574 // Static fields do not inherit constness from parents.
12575 break;
12576 }
12577 break; // End MemberExpr
12578 } else if (const ArraySubscriptExpr *ASE =
12579 dyn_cast<ArraySubscriptExpr>(E)) {
12580 E = ASE->getBase()->IgnoreParenImpCasts();
12581 continue;
12582 } else if (const ExtVectorElementExpr *EVE =
12583 dyn_cast<ExtVectorElementExpr>(E)) {
12584 E = EVE->getBase()->IgnoreParenImpCasts();
12585 continue;
12586 }
12587 break;
12588 }
12589
12590 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
12591 // Function calls
12592 const FunctionDecl *FD = CE->getDirectCallee();
12593 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
12594 if (!DiagnosticEmitted) {
12595 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12596 << ConstFunction << FD;
12597 DiagnosticEmitted = true;
12598 }
12599 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
12600 diag::note_typecheck_assign_const)
12601 << ConstFunction << FD << FD->getReturnType()
12602 << FD->getReturnTypeSourceRange();
12603 }
12604 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12605 // Point to variable declaration.
12606 if (const ValueDecl *VD = DRE->getDecl()) {
12607 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
12608 if (!DiagnosticEmitted) {
12609 S.Diag(Loc, diag::err_typecheck_assign_const)
12610 << ExprRange << ConstVariable << VD << VD->getType();
12611 DiagnosticEmitted = true;
12612 }
12613 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
12614 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
12615 }
12616 }
12617 } else if (isa<CXXThisExpr>(E)) {
12618 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
12619 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
12620 if (MD->isConst()) {
12621 if (!DiagnosticEmitted) {
12622 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
12623 << ConstMethod << MD;
12624 DiagnosticEmitted = true;
12625 }
12626 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
12627 << ConstMethod << MD << MD->getSourceRange();
12628 }
12629 }
12630 }
12631 }
12632
12633 if (DiagnosticEmitted)
12634 return;
12635
12636 // Can't determine a more specific message, so display the generic error.
12637 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
12638 }
12639
12640 enum OriginalExprKind {
12641 OEK_Variable,
12642 OEK_Member,
12643 OEK_LValue
12644 };
12645
DiagnoseRecursiveConstFields(Sema & S,const ValueDecl * VD,const RecordType * Ty,SourceLocation Loc,SourceRange Range,OriginalExprKind OEK,bool & DiagnosticEmitted)12646 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
12647 const RecordType *Ty,
12648 SourceLocation Loc, SourceRange Range,
12649 OriginalExprKind OEK,
12650 bool &DiagnosticEmitted) {
12651 std::vector<const RecordType *> RecordTypeList;
12652 RecordTypeList.push_back(Ty);
12653 unsigned NextToCheckIndex = 0;
12654 // We walk the record hierarchy breadth-first to ensure that we print
12655 // diagnostics in field nesting order.
12656 while (RecordTypeList.size() > NextToCheckIndex) {
12657 bool IsNested = NextToCheckIndex > 0;
12658 for (const FieldDecl *Field :
12659 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
12660 // First, check every field for constness.
12661 QualType FieldTy = Field->getType();
12662 if (FieldTy.isConstQualified()) {
12663 if (!DiagnosticEmitted) {
12664 S.Diag(Loc, diag::err_typecheck_assign_const)
12665 << Range << NestedConstMember << OEK << VD
12666 << IsNested << Field;
12667 DiagnosticEmitted = true;
12668 }
12669 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
12670 << NestedConstMember << IsNested << Field
12671 << FieldTy << Field->getSourceRange();
12672 }
12673
12674 // Then we append it to the list to check next in order.
12675 FieldTy = FieldTy.getCanonicalType();
12676 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
12677 if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
12678 RecordTypeList.push_back(FieldRecTy);
12679 }
12680 }
12681 ++NextToCheckIndex;
12682 }
12683 }
12684
12685 /// Emit an error for the case where a record we are trying to assign to has a
12686 /// const-qualified field somewhere in its hierarchy.
DiagnoseRecursiveConstFields(Sema & S,const Expr * E,SourceLocation Loc)12687 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
12688 SourceLocation Loc) {
12689 QualType Ty = E->getType();
12690 assert(Ty->isRecordType() && "lvalue was not record?");
12691 SourceRange Range = E->getSourceRange();
12692 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
12693 bool DiagEmitted = false;
12694
12695 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
12696 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
12697 Range, OEK_Member, DiagEmitted);
12698 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12699 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
12700 Range, OEK_Variable, DiagEmitted);
12701 else
12702 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
12703 Range, OEK_LValue, DiagEmitted);
12704 if (!DiagEmitted)
12705 DiagnoseConstAssignment(S, E, Loc);
12706 }
12707
12708 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
12709 /// emit an error and return true. If so, return false.
CheckForModifiableLvalue(Expr * E,SourceLocation Loc,Sema & S)12710 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
12711 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
12712
12713 S.CheckShadowingDeclModification(E, Loc);
12714
12715 SourceLocation OrigLoc = Loc;
12716 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
12717 &Loc);
12718 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
12719 IsLV = Expr::MLV_InvalidMessageExpression;
12720 if (IsLV == Expr::MLV_Valid)
12721 return false;
12722
12723 unsigned DiagID = 0;
12724 bool NeedType = false;
12725 switch (IsLV) { // C99 6.5.16p2
12726 case Expr::MLV_ConstQualified:
12727 // Use a specialized diagnostic when we're assigning to an object
12728 // from an enclosing function or block.
12729 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
12730 if (NCCK == NCCK_Block)
12731 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
12732 else
12733 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
12734 break;
12735 }
12736
12737 // In ARC, use some specialized diagnostics for occasions where we
12738 // infer 'const'. These are always pseudo-strong variables.
12739 if (S.getLangOpts().ObjCAutoRefCount) {
12740 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
12741 if (declRef && isa<VarDecl>(declRef->getDecl())) {
12742 VarDecl *var = cast<VarDecl>(declRef->getDecl());
12743
12744 // Use the normal diagnostic if it's pseudo-__strong but the
12745 // user actually wrote 'const'.
12746 if (var->isARCPseudoStrong() &&
12747 (!var->getTypeSourceInfo() ||
12748 !var->getTypeSourceInfo()->getType().isConstQualified())) {
12749 // There are three pseudo-strong cases:
12750 // - self
12751 ObjCMethodDecl *method = S.getCurMethodDecl();
12752 if (method && var == method->getSelfDecl()) {
12753 DiagID = method->isClassMethod()
12754 ? diag::err_typecheck_arc_assign_self_class_method
12755 : diag::err_typecheck_arc_assign_self;
12756
12757 // - Objective-C externally_retained attribute.
12758 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
12759 isa<ParmVarDecl>(var)) {
12760 DiagID = diag::err_typecheck_arc_assign_externally_retained;
12761
12762 // - fast enumeration variables
12763 } else {
12764 DiagID = diag::err_typecheck_arr_assign_enumeration;
12765 }
12766
12767 SourceRange Assign;
12768 if (Loc != OrigLoc)
12769 Assign = SourceRange(OrigLoc, OrigLoc);
12770 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12771 // We need to preserve the AST regardless, so migration tool
12772 // can do its job.
12773 return false;
12774 }
12775 }
12776 }
12777
12778 // If none of the special cases above are triggered, then this is a
12779 // simple const assignment.
12780 if (DiagID == 0) {
12781 DiagnoseConstAssignment(S, E, Loc);
12782 return true;
12783 }
12784
12785 break;
12786 case Expr::MLV_ConstAddrSpace:
12787 DiagnoseConstAssignment(S, E, Loc);
12788 return true;
12789 case Expr::MLV_ConstQualifiedField:
12790 DiagnoseRecursiveConstFields(S, E, Loc);
12791 return true;
12792 case Expr::MLV_ArrayType:
12793 case Expr::MLV_ArrayTemporary:
12794 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
12795 NeedType = true;
12796 break;
12797 case Expr::MLV_NotObjectType:
12798 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
12799 NeedType = true;
12800 break;
12801 case Expr::MLV_LValueCast:
12802 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
12803 break;
12804 case Expr::MLV_Valid:
12805 llvm_unreachable("did not take early return for MLV_Valid");
12806 case Expr::MLV_InvalidExpression:
12807 case Expr::MLV_MemberFunction:
12808 case Expr::MLV_ClassTemporary:
12809 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
12810 break;
12811 case Expr::MLV_IncompleteType:
12812 case Expr::MLV_IncompleteVoidType:
12813 return S.RequireCompleteType(Loc, E->getType(),
12814 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
12815 case Expr::MLV_DuplicateVectorComponents:
12816 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
12817 break;
12818 case Expr::MLV_NoSetterProperty:
12819 llvm_unreachable("readonly properties should be processed differently");
12820 case Expr::MLV_InvalidMessageExpression:
12821 DiagID = diag::err_readonly_message_assignment;
12822 break;
12823 case Expr::MLV_SubObjCPropertySetting:
12824 DiagID = diag::err_no_subobject_property_setting;
12825 break;
12826 }
12827
12828 SourceRange Assign;
12829 if (Loc != OrigLoc)
12830 Assign = SourceRange(OrigLoc, OrigLoc);
12831 if (NeedType)
12832 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
12833 else
12834 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
12835 return true;
12836 }
12837
CheckIdentityFieldAssignment(Expr * LHSExpr,Expr * RHSExpr,SourceLocation Loc,Sema & Sema)12838 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
12839 SourceLocation Loc,
12840 Sema &Sema) {
12841 if (Sema.inTemplateInstantiation())
12842 return;
12843 if (Sema.isUnevaluatedContext())
12844 return;
12845 if (Loc.isInvalid() || Loc.isMacroID())
12846 return;
12847 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
12848 return;
12849
12850 // C / C++ fields
12851 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
12852 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
12853 if (ML && MR) {
12854 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
12855 return;
12856 const ValueDecl *LHSDecl =
12857 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
12858 const ValueDecl *RHSDecl =
12859 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
12860 if (LHSDecl != RHSDecl)
12861 return;
12862 if (LHSDecl->getType().isVolatileQualified())
12863 return;
12864 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12865 if (RefTy->getPointeeType().isVolatileQualified())
12866 return;
12867
12868 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
12869 }
12870
12871 // Objective-C instance variables
12872 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
12873 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
12874 if (OL && OR && OL->getDecl() == OR->getDecl()) {
12875 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
12876 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
12877 if (RL && RR && RL->getDecl() == RR->getDecl())
12878 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
12879 }
12880 }
12881
12882 // C99 6.5.16.1
CheckAssignmentOperands(Expr * LHSExpr,ExprResult & RHS,SourceLocation Loc,QualType CompoundType)12883 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
12884 SourceLocation Loc,
12885 QualType CompoundType) {
12886 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
12887
12888 // Verify that LHS is a modifiable lvalue, and emit error if not.
12889 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
12890 return QualType();
12891
12892 QualType LHSType = LHSExpr->getType();
12893 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
12894 CompoundType;
12895 // OpenCL v1.2 s6.1.1.1 p2:
12896 // The half data type can only be used to declare a pointer to a buffer that
12897 // contains half values
12898 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
12899 LHSType->isHalfType()) {
12900 Diag(Loc, diag::err_opencl_half_load_store) << 1
12901 << LHSType.getUnqualifiedType();
12902 return QualType();
12903 }
12904
12905 AssignConvertType ConvTy;
12906 if (CompoundType.isNull()) {
12907 Expr *RHSCheck = RHS.get();
12908
12909 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
12910
12911 QualType LHSTy(LHSType);
12912 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
12913 if (RHS.isInvalid())
12914 return QualType();
12915 // Special case of NSObject attributes on c-style pointer types.
12916 if (ConvTy == IncompatiblePointer &&
12917 ((Context.isObjCNSObjectType(LHSType) &&
12918 RHSType->isObjCObjectPointerType()) ||
12919 (Context.isObjCNSObjectType(RHSType) &&
12920 LHSType->isObjCObjectPointerType())))
12921 ConvTy = Compatible;
12922
12923 if (ConvTy == Compatible &&
12924 LHSType->isObjCObjectType())
12925 Diag(Loc, diag::err_objc_object_assignment)
12926 << LHSType;
12927
12928 // If the RHS is a unary plus or minus, check to see if they = and + are
12929 // right next to each other. If so, the user may have typo'd "x =+ 4"
12930 // instead of "x += 4".
12931 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
12932 RHSCheck = ICE->getSubExpr();
12933 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
12934 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
12935 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
12936 // Only if the two operators are exactly adjacent.
12937 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
12938 // And there is a space or other character before the subexpr of the
12939 // unary +/-. We don't want to warn on "x=-1".
12940 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
12941 UO->getSubExpr()->getBeginLoc().isFileID()) {
12942 Diag(Loc, diag::warn_not_compound_assign)
12943 << (UO->getOpcode() == UO_Plus ? "+" : "-")
12944 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
12945 }
12946 }
12947
12948 if (ConvTy == Compatible) {
12949 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
12950 // Warn about retain cycles where a block captures the LHS, but
12951 // not if the LHS is a simple variable into which the block is
12952 // being stored...unless that variable can be captured by reference!
12953 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
12954 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
12955 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
12956 checkRetainCycles(LHSExpr, RHS.get());
12957 }
12958
12959 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
12960 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
12961 // It is safe to assign a weak reference into a strong variable.
12962 // Although this code can still have problems:
12963 // id x = self.weakProp;
12964 // id y = self.weakProp;
12965 // we do not warn to warn spuriously when 'x' and 'y' are on separate
12966 // paths through the function. This should be revisited if
12967 // -Wrepeated-use-of-weak is made flow-sensitive.
12968 // For ObjCWeak only, we do not warn if the assign is to a non-weak
12969 // variable, which will be valid for the current autorelease scope.
12970 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12971 RHS.get()->getBeginLoc()))
12972 getCurFunction()->markSafeWeakUse(RHS.get());
12973
12974 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
12975 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
12976 }
12977 }
12978 } else {
12979 // Compound assignment "x += y"
12980 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
12981 }
12982
12983 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
12984 RHS.get(), AA_Assigning))
12985 return QualType();
12986
12987 CheckForNullPointerDereference(*this, LHSExpr);
12988
12989 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
12990 if (CompoundType.isNull()) {
12991 // C++2a [expr.ass]p5:
12992 // A simple-assignment whose left operand is of a volatile-qualified
12993 // type is deprecated unless the assignment is either a discarded-value
12994 // expression or an unevaluated operand
12995 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
12996 } else {
12997 // C++2a [expr.ass]p6:
12998 // [Compound-assignment] expressions are deprecated if E1 has
12999 // volatile-qualified type
13000 Diag(Loc, diag::warn_deprecated_compound_assign_volatile) << LHSType;
13001 }
13002 }
13003
13004 // C99 6.5.16p3: The type of an assignment expression is the type of the
13005 // left operand unless the left operand has qualified type, in which case
13006 // it is the unqualified version of the type of the left operand.
13007 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
13008 // is converted to the type of the assignment expression (above).
13009 // C++ 5.17p1: the type of the assignment expression is that of its left
13010 // operand.
13011 return (getLangOpts().CPlusPlus
13012 ? LHSType : LHSType.getUnqualifiedType());
13013 }
13014
13015 // Only ignore explicit casts to void.
IgnoreCommaOperand(const Expr * E)13016 static bool IgnoreCommaOperand(const Expr *E) {
13017 E = E->IgnoreParens();
13018
13019 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13020 if (CE->getCastKind() == CK_ToVoid) {
13021 return true;
13022 }
13023
13024 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13025 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13026 CE->getSubExpr()->getType()->isDependentType()) {
13027 return true;
13028 }
13029 }
13030
13031 return false;
13032 }
13033
13034 // Look for instances where it is likely the comma operator is confused with
13035 // another operator. There is an explicit list of acceptable expressions for
13036 // the left hand side of the comma operator, otherwise emit a warning.
DiagnoseCommaOperator(const Expr * LHS,SourceLocation Loc)13037 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
13038 // No warnings in macros
13039 if (Loc.isMacroID())
13040 return;
13041
13042 // Don't warn in template instantiations.
13043 if (inTemplateInstantiation())
13044 return;
13045
13046 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13047 // instead, skip more than needed, then call back into here with the
13048 // CommaVisitor in SemaStmt.cpp.
13049 // The listed locations are the initialization and increment portions
13050 // of a for loop. The additional checks are on the condition of
13051 // if statements, do/while loops, and for loops.
13052 // Differences in scope flags for C89 mode requires the extra logic.
13053 const unsigned ForIncrementFlags =
13054 getLangOpts().C99 || getLangOpts().CPlusPlus
13055 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
13056 : Scope::ContinueScope | Scope::BreakScope;
13057 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13058 const unsigned ScopeFlags = getCurScope()->getFlags();
13059 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13060 (ScopeFlags & ForInitFlags) == ForInitFlags)
13061 return;
13062
13063 // If there are multiple comma operators used together, get the RHS of the
13064 // of the comma operator as the LHS.
13065 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13066 if (BO->getOpcode() != BO_Comma)
13067 break;
13068 LHS = BO->getRHS();
13069 }
13070
13071 // Only allow some expressions on LHS to not warn.
13072 if (IgnoreCommaOperand(LHS))
13073 return;
13074
13075 Diag(Loc, diag::warn_comma_operator);
13076 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13077 << LHS->getSourceRange()
13078 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
13079 LangOpts.CPlusPlus ? "static_cast<void>("
13080 : "(void)(")
13081 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
13082 ")");
13083 }
13084
13085 // C99 6.5.17
CheckCommaOperands(Sema & S,ExprResult & LHS,ExprResult & RHS,SourceLocation Loc)13086 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
13087 SourceLocation Loc) {
13088 LHS = S.CheckPlaceholderExpr(LHS.get());
13089 RHS = S.CheckPlaceholderExpr(RHS.get());
13090 if (LHS.isInvalid() || RHS.isInvalid())
13091 return QualType();
13092
13093 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13094 // operands, but not unary promotions.
13095 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13096
13097 // So we treat the LHS as a ignored value, and in C++ we allow the
13098 // containing site to determine what should be done with the RHS.
13099 LHS = S.IgnoredValueConversions(LHS.get());
13100 if (LHS.isInvalid())
13101 return QualType();
13102
13103 S.DiagnoseUnusedExprResult(LHS.get());
13104
13105 if (!S.getLangOpts().CPlusPlus) {
13106 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
13107 if (RHS.isInvalid())
13108 return QualType();
13109 if (!RHS.get()->getType()->isVoidType())
13110 S.RequireCompleteType(Loc, RHS.get()->getType(),
13111 diag::err_incomplete_type);
13112 }
13113
13114 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13115 S.DiagnoseCommaOperator(LHS.get(), Loc);
13116
13117 return RHS.get()->getType();
13118 }
13119
13120 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13121 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
CheckIncrementDecrementOperand(Sema & S,Expr * Op,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation OpLoc,bool IsInc,bool IsPrefix)13122 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
13123 ExprValueKind &VK,
13124 ExprObjectKind &OK,
13125 SourceLocation OpLoc,
13126 bool IsInc, bool IsPrefix) {
13127 if (Op->isTypeDependent())
13128 return S.Context.DependentTy;
13129
13130 QualType ResType = Op->getType();
13131 // Atomic types can be used for increment / decrement where the non-atomic
13132 // versions can, so ignore the _Atomic() specifier for the purpose of
13133 // checking.
13134 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13135 ResType = ResAtomicType->getValueType();
13136
13137 assert(!ResType.isNull() && "no type for increment/decrement expression");
13138
13139 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13140 // Decrement of bool is not allowed.
13141 if (!IsInc) {
13142 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13143 return QualType();
13144 }
13145 // Increment of bool sets it to true, but is deprecated.
13146 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13147 : diag::warn_increment_bool)
13148 << Op->getSourceRange();
13149 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13150 // Error on enum increments and decrements in C++ mode
13151 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13152 return QualType();
13153 } else if (ResType->isRealType()) {
13154 // OK!
13155 } else if (ResType->isPointerType()) {
13156 // C99 6.5.2.4p2, 6.5.6p2
13157 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13158 return QualType();
13159 } else if (ResType->isObjCObjectPointerType()) {
13160 // On modern runtimes, ObjC pointer arithmetic is forbidden.
13161 // Otherwise, we just need a complete type.
13162 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13163 checkArithmeticOnObjCPointer(S, OpLoc, Op))
13164 return QualType();
13165 } else if (ResType->isAnyComplexType()) {
13166 // C99 does not support ++/-- on complex types, we allow as an extension.
13167 S.Diag(OpLoc, diag::ext_integer_increment_complex)
13168 << ResType << Op->getSourceRange();
13169 } else if (ResType->isPlaceholderType()) {
13170 ExprResult PR = S.CheckPlaceholderExpr(Op);
13171 if (PR.isInvalid()) return QualType();
13172 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13173 IsInc, IsPrefix);
13174 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13175 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13176 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13177 (ResType->castAs<VectorType>()->getVectorKind() !=
13178 VectorType::AltiVecBool)) {
13179 // The z vector extensions allow ++ and -- for non-bool vectors.
13180 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
13181 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13182 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13183 } else {
13184 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13185 << ResType << int(IsInc) << Op->getSourceRange();
13186 return QualType();
13187 }
13188 // At this point, we know we have a real, complex or pointer type.
13189 // Now make sure the operand is a modifiable lvalue.
13190 if (CheckForModifiableLvalue(Op, OpLoc, S))
13191 return QualType();
13192 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13193 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13194 // An operand with volatile-qualified type is deprecated
13195 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13196 << IsInc << ResType;
13197 }
13198 // In C++, a prefix increment is the same type as the operand. Otherwise
13199 // (in C or with postfix), the increment is the unqualified type of the
13200 // operand.
13201 if (IsPrefix && S.getLangOpts().CPlusPlus) {
13202 VK = VK_LValue;
13203 OK = Op->getObjectKind();
13204 return ResType;
13205 } else {
13206 VK = VK_RValue;
13207 return ResType.getUnqualifiedType();
13208 }
13209 }
13210
13211
13212 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13213 /// This routine allows us to typecheck complex/recursive expressions
13214 /// where the declaration is needed for type checking. We only need to
13215 /// handle cases when the expression references a function designator
13216 /// or is an lvalue. Here are some examples:
13217 /// - &(x) => x
13218 /// - &*****f => f for f a function designator.
13219 /// - &s.xx => s
13220 /// - &s.zz[1].yy -> s, if zz is an array
13221 /// - *(x + 1) -> x, if x is an array
13222 /// - &"123"[2] -> 0
13223 /// - & __real__ x -> x
13224 ///
13225 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13226 /// members.
getPrimaryDecl(Expr * E)13227 static ValueDecl *getPrimaryDecl(Expr *E) {
13228 switch (E->getStmtClass()) {
13229 case Stmt::DeclRefExprClass:
13230 return cast<DeclRefExpr>(E)->getDecl();
13231 case Stmt::MemberExprClass:
13232 // If this is an arrow operator, the address is an offset from
13233 // the base's value, so the object the base refers to is
13234 // irrelevant.
13235 if (cast<MemberExpr>(E)->isArrow())
13236 return nullptr;
13237 // Otherwise, the expression refers to a part of the base
13238 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13239 case Stmt::ArraySubscriptExprClass: {
13240 // FIXME: This code shouldn't be necessary! We should catch the implicit
13241 // promotion of register arrays earlier.
13242 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13243 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13244 if (ICE->getSubExpr()->getType()->isArrayType())
13245 return getPrimaryDecl(ICE->getSubExpr());
13246 }
13247 return nullptr;
13248 }
13249 case Stmt::UnaryOperatorClass: {
13250 UnaryOperator *UO = cast<UnaryOperator>(E);
13251
13252 switch(UO->getOpcode()) {
13253 case UO_Real:
13254 case UO_Imag:
13255 case UO_Extension:
13256 return getPrimaryDecl(UO->getSubExpr());
13257 default:
13258 return nullptr;
13259 }
13260 }
13261 case Stmt::ParenExprClass:
13262 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13263 case Stmt::ImplicitCastExprClass:
13264 // If the result of an implicit cast is an l-value, we care about
13265 // the sub-expression; otherwise, the result here doesn't matter.
13266 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13267 case Stmt::CXXUuidofExprClass:
13268 return cast<CXXUuidofExpr>(E)->getGuidDecl();
13269 default:
13270 return nullptr;
13271 }
13272 }
13273
13274 namespace {
13275 enum {
13276 AO_Bit_Field = 0,
13277 AO_Vector_Element = 1,
13278 AO_Property_Expansion = 2,
13279 AO_Register_Variable = 3,
13280 AO_Matrix_Element = 4,
13281 AO_No_Error = 5
13282 };
13283 }
13284 /// Diagnose invalid operand for address of operations.
13285 ///
13286 /// \param Type The type of operand which cannot have its address taken.
diagnoseAddressOfInvalidType(Sema & S,SourceLocation Loc,Expr * E,unsigned Type)13287 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
13288 Expr *E, unsigned Type) {
13289 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13290 }
13291
13292 /// CheckAddressOfOperand - The operand of & must be either a function
13293 /// designator or an lvalue designating an object. If it is an lvalue, the
13294 /// object cannot be declared with storage class register or be a bit field.
13295 /// Note: The usual conversions are *not* applied to the operand of the &
13296 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
13297 /// In C++, the operand might be an overloaded function name, in which case
13298 /// we allow the '&' but retain the overloaded-function type.
CheckAddressOfOperand(ExprResult & OrigOp,SourceLocation OpLoc)13299 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
13300 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13301 if (PTy->getKind() == BuiltinType::Overload) {
13302 Expr *E = OrigOp.get()->IgnoreParens();
13303 if (!isa<OverloadExpr>(E)) {
13304 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13305 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13306 << OrigOp.get()->getSourceRange();
13307 return QualType();
13308 }
13309
13310 OverloadExpr *Ovl = cast<OverloadExpr>(E);
13311 if (isa<UnresolvedMemberExpr>(Ovl))
13312 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
13313 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13314 << OrigOp.get()->getSourceRange();
13315 return QualType();
13316 }
13317
13318 return Context.OverloadTy;
13319 }
13320
13321 if (PTy->getKind() == BuiltinType::UnknownAny)
13322 return Context.UnknownAnyTy;
13323
13324 if (PTy->getKind() == BuiltinType::BoundMember) {
13325 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13326 << OrigOp.get()->getSourceRange();
13327 return QualType();
13328 }
13329
13330 OrigOp = CheckPlaceholderExpr(OrigOp.get());
13331 if (OrigOp.isInvalid()) return QualType();
13332 }
13333
13334 if (OrigOp.get()->isTypeDependent())
13335 return Context.DependentTy;
13336
13337 assert(!OrigOp.get()->getType()->isPlaceholderType());
13338
13339 // Make sure to ignore parentheses in subsequent checks
13340 Expr *op = OrigOp.get()->IgnoreParens();
13341
13342 // In OpenCL captures for blocks called as lambda functions
13343 // are located in the private address space. Blocks used in
13344 // enqueue_kernel can be located in a different address space
13345 // depending on a vendor implementation. Thus preventing
13346 // taking an address of the capture to avoid invalid AS casts.
13347 if (LangOpts.OpenCL) {
13348 auto* VarRef = dyn_cast<DeclRefExpr>(op);
13349 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
13350 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
13351 return QualType();
13352 }
13353 }
13354
13355 if (getLangOpts().C99) {
13356 // Implement C99-only parts of addressof rules.
13357 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
13358 if (uOp->getOpcode() == UO_Deref)
13359 // Per C99 6.5.3.2, the address of a deref always returns a valid result
13360 // (assuming the deref expression is valid).
13361 return uOp->getSubExpr()->getType();
13362 }
13363 // Technically, there should be a check for array subscript
13364 // expressions here, but the result of one is always an lvalue anyway.
13365 }
13366 ValueDecl *dcl = getPrimaryDecl(op);
13367
13368 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
13369 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
13370 op->getBeginLoc()))
13371 return QualType();
13372
13373 Expr::LValueClassification lval = op->ClassifyLValue(Context);
13374 unsigned AddressOfError = AO_No_Error;
13375
13376 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
13377 bool sfinae = (bool)isSFINAEContext();
13378 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
13379 : diag::ext_typecheck_addrof_temporary)
13380 << op->getType() << op->getSourceRange();
13381 if (sfinae)
13382 return QualType();
13383 // Materialize the temporary as an lvalue so that we can take its address.
13384 OrigOp = op =
13385 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
13386 } else if (isa<ObjCSelectorExpr>(op)) {
13387 return Context.getPointerType(op->getType());
13388 } else if (lval == Expr::LV_MemberFunction) {
13389 // If it's an instance method, make a member pointer.
13390 // The expression must have exactly the form &A::foo.
13391
13392 // If the underlying expression isn't a decl ref, give up.
13393 if (!isa<DeclRefExpr>(op)) {
13394 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13395 << OrigOp.get()->getSourceRange();
13396 return QualType();
13397 }
13398 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
13399 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
13400
13401 // The id-expression was parenthesized.
13402 if (OrigOp.get() != DRE) {
13403 Diag(OpLoc, diag::err_parens_pointer_member_function)
13404 << OrigOp.get()->getSourceRange();
13405
13406 // The method was named without a qualifier.
13407 } else if (!DRE->getQualifier()) {
13408 if (MD->getParent()->getName().empty())
13409 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13410 << op->getSourceRange();
13411 else {
13412 SmallString<32> Str;
13413 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13414 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13415 << op->getSourceRange()
13416 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
13417 }
13418 }
13419
13420 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13421 if (isa<CXXDestructorDecl>(MD))
13422 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
13423
13424 QualType MPTy = Context.getMemberPointerType(
13425 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
13426 // Under the MS ABI, lock down the inheritance model now.
13427 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13428 (void)isCompleteType(OpLoc, MPTy);
13429 return MPTy;
13430 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
13431 // C99 6.5.3.2p1
13432 // The operand must be either an l-value or a function designator
13433 if (!op->getType()->isFunctionType()) {
13434 // Use a special diagnostic for loads from property references.
13435 if (isa<PseudoObjectExpr>(op)) {
13436 AddressOfError = AO_Property_Expansion;
13437 } else {
13438 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
13439 << op->getType() << op->getSourceRange();
13440 return QualType();
13441 }
13442 }
13443 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
13444 // The operand cannot be a bit-field
13445 AddressOfError = AO_Bit_Field;
13446 } else if (op->getObjectKind() == OK_VectorComponent) {
13447 // The operand cannot be an element of a vector
13448 AddressOfError = AO_Vector_Element;
13449 } else if (op->getObjectKind() == OK_MatrixComponent) {
13450 // The operand cannot be an element of a matrix.
13451 AddressOfError = AO_Matrix_Element;
13452 } else if (dcl) { // C99 6.5.3.2p1
13453 // We have an lvalue with a decl. Make sure the decl is not declared
13454 // with the register storage-class specifier.
13455 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
13456 // in C++ it is not error to take address of a register
13457 // variable (c++03 7.1.1P3)
13458 if (vd->getStorageClass() == SC_Register &&
13459 !getLangOpts().CPlusPlus) {
13460 AddressOfError = AO_Register_Variable;
13461 }
13462 } else if (isa<MSPropertyDecl>(dcl)) {
13463 AddressOfError = AO_Property_Expansion;
13464 } else if (isa<FunctionTemplateDecl>(dcl)) {
13465 return Context.OverloadTy;
13466 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
13467 // Okay: we can take the address of a field.
13468 // Could be a pointer to member, though, if there is an explicit
13469 // scope qualifier for the class.
13470 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
13471 DeclContext *Ctx = dcl->getDeclContext();
13472 if (Ctx && Ctx->isRecord()) {
13473 if (dcl->getType()->isReferenceType()) {
13474 Diag(OpLoc,
13475 diag::err_cannot_form_pointer_to_member_of_reference_type)
13476 << dcl->getDeclName() << dcl->getType();
13477 return QualType();
13478 }
13479
13480 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
13481 Ctx = Ctx->getParent();
13482
13483 QualType MPTy = Context.getMemberPointerType(
13484 op->getType(),
13485 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
13486 // Under the MS ABI, lock down the inheritance model now.
13487 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13488 (void)isCompleteType(OpLoc, MPTy);
13489 return MPTy;
13490 }
13491 }
13492 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
13493 !isa<BindingDecl>(dcl) && !isa<MSGuidDecl>(dcl))
13494 llvm_unreachable("Unknown/unexpected decl type");
13495 }
13496
13497 if (AddressOfError != AO_No_Error) {
13498 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
13499 return QualType();
13500 }
13501
13502 if (lval == Expr::LV_IncompleteVoidType) {
13503 // Taking the address of a void variable is technically illegal, but we
13504 // allow it in cases which are otherwise valid.
13505 // Example: "extern void x; void* y = &x;".
13506 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
13507 }
13508
13509 // If the operand has type "type", the result has type "pointer to type".
13510 if (op->getType()->isObjCObjectType())
13511 return Context.getObjCObjectPointerType(op->getType());
13512
13513 CheckAddressOfPackedMember(op);
13514
13515 return Context.getPointerType(op->getType());
13516 }
13517
RecordModifiableNonNullParam(Sema & S,const Expr * Exp)13518 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
13519 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
13520 if (!DRE)
13521 return;
13522 const Decl *D = DRE->getDecl();
13523 if (!D)
13524 return;
13525 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
13526 if (!Param)
13527 return;
13528 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
13529 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
13530 return;
13531 if (FunctionScopeInfo *FD = S.getCurFunction())
13532 if (!FD->ModifiedNonNullParams.count(Param))
13533 FD->ModifiedNonNullParams.insert(Param);
13534 }
13535
13536 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
CheckIndirectionOperand(Sema & S,Expr * Op,ExprValueKind & VK,SourceLocation OpLoc)13537 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
13538 SourceLocation OpLoc) {
13539 if (Op->isTypeDependent())
13540 return S.Context.DependentTy;
13541
13542 ExprResult ConvResult = S.UsualUnaryConversions(Op);
13543 if (ConvResult.isInvalid())
13544 return QualType();
13545 Op = ConvResult.get();
13546 QualType OpTy = Op->getType();
13547 QualType Result;
13548
13549 if (isa<CXXReinterpretCastExpr>(Op)) {
13550 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
13551 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
13552 Op->getSourceRange());
13553 }
13554
13555 if (const PointerType *PT = OpTy->getAs<PointerType>())
13556 {
13557 Result = PT->getPointeeType();
13558 }
13559 else if (const ObjCObjectPointerType *OPT =
13560 OpTy->getAs<ObjCObjectPointerType>())
13561 Result = OPT->getPointeeType();
13562 else {
13563 ExprResult PR = S.CheckPlaceholderExpr(Op);
13564 if (PR.isInvalid()) return QualType();
13565 if (PR.get() != Op)
13566 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
13567 }
13568
13569 if (Result.isNull()) {
13570 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
13571 << OpTy << Op->getSourceRange();
13572 return QualType();
13573 }
13574
13575 // Note that per both C89 and C99, indirection is always legal, even if Result
13576 // is an incomplete type or void. It would be possible to warn about
13577 // dereferencing a void pointer, but it's completely well-defined, and such a
13578 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
13579 // for pointers to 'void' but is fine for any other pointer type:
13580 //
13581 // C++ [expr.unary.op]p1:
13582 // [...] the expression to which [the unary * operator] is applied shall
13583 // be a pointer to an object type, or a pointer to a function type
13584 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
13585 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
13586 << OpTy << Op->getSourceRange();
13587
13588 // Dereferences are usually l-values...
13589 VK = VK_LValue;
13590
13591 // ...except that certain expressions are never l-values in C.
13592 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
13593 VK = VK_RValue;
13594
13595 return Result;
13596 }
13597
ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind)13598 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
13599 BinaryOperatorKind Opc;
13600 switch (Kind) {
13601 default: llvm_unreachable("Unknown binop!");
13602 case tok::periodstar: Opc = BO_PtrMemD; break;
13603 case tok::arrowstar: Opc = BO_PtrMemI; break;
13604 case tok::star: Opc = BO_Mul; break;
13605 case tok::slash: Opc = BO_Div; break;
13606 case tok::percent: Opc = BO_Rem; break;
13607 case tok::plus: Opc = BO_Add; break;
13608 case tok::minus: Opc = BO_Sub; break;
13609 case tok::lessless: Opc = BO_Shl; break;
13610 case tok::greatergreater: Opc = BO_Shr; break;
13611 case tok::lessequal: Opc = BO_LE; break;
13612 case tok::less: Opc = BO_LT; break;
13613 case tok::greaterequal: Opc = BO_GE; break;
13614 case tok::greater: Opc = BO_GT; break;
13615 case tok::exclaimequal: Opc = BO_NE; break;
13616 case tok::equalequal: Opc = BO_EQ; break;
13617 case tok::spaceship: Opc = BO_Cmp; break;
13618 case tok::amp: Opc = BO_And; break;
13619 case tok::caret: Opc = BO_Xor; break;
13620 case tok::pipe: Opc = BO_Or; break;
13621 case tok::ampamp: Opc = BO_LAnd; break;
13622 case tok::pipepipe: Opc = BO_LOr; break;
13623 case tok::equal: Opc = BO_Assign; break;
13624 case tok::starequal: Opc = BO_MulAssign; break;
13625 case tok::slashequal: Opc = BO_DivAssign; break;
13626 case tok::percentequal: Opc = BO_RemAssign; break;
13627 case tok::plusequal: Opc = BO_AddAssign; break;
13628 case tok::minusequal: Opc = BO_SubAssign; break;
13629 case tok::lesslessequal: Opc = BO_ShlAssign; break;
13630 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
13631 case tok::ampequal: Opc = BO_AndAssign; break;
13632 case tok::caretequal: Opc = BO_XorAssign; break;
13633 case tok::pipeequal: Opc = BO_OrAssign; break;
13634 case tok::comma: Opc = BO_Comma; break;
13635 }
13636 return Opc;
13637 }
13638
ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)13639 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
13640 tok::TokenKind Kind) {
13641 UnaryOperatorKind Opc;
13642 switch (Kind) {
13643 default: llvm_unreachable("Unknown unary op!");
13644 case tok::plusplus: Opc = UO_PreInc; break;
13645 case tok::minusminus: Opc = UO_PreDec; break;
13646 case tok::amp: Opc = UO_AddrOf; break;
13647 case tok::star: Opc = UO_Deref; break;
13648 case tok::plus: Opc = UO_Plus; break;
13649 case tok::minus: Opc = UO_Minus; break;
13650 case tok::tilde: Opc = UO_Not; break;
13651 case tok::exclaim: Opc = UO_LNot; break;
13652 case tok::kw___real: Opc = UO_Real; break;
13653 case tok::kw___imag: Opc = UO_Imag; break;
13654 case tok::kw___extension__: Opc = UO_Extension; break;
13655 }
13656 return Opc;
13657 }
13658
13659 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
13660 /// This warning suppressed in the event of macro expansions.
DiagnoseSelfAssignment(Sema & S,Expr * LHSExpr,Expr * RHSExpr,SourceLocation OpLoc,bool IsBuiltin)13661 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
13662 SourceLocation OpLoc, bool IsBuiltin) {
13663 if (S.inTemplateInstantiation())
13664 return;
13665 if (S.isUnevaluatedContext())
13666 return;
13667 if (OpLoc.isInvalid() || OpLoc.isMacroID())
13668 return;
13669 LHSExpr = LHSExpr->IgnoreParenImpCasts();
13670 RHSExpr = RHSExpr->IgnoreParenImpCasts();
13671 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13672 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13673 if (!LHSDeclRef || !RHSDeclRef ||
13674 LHSDeclRef->getLocation().isMacroID() ||
13675 RHSDeclRef->getLocation().isMacroID())
13676 return;
13677 const ValueDecl *LHSDecl =
13678 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
13679 const ValueDecl *RHSDecl =
13680 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
13681 if (LHSDecl != RHSDecl)
13682 return;
13683 if (LHSDecl->getType().isVolatileQualified())
13684 return;
13685 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13686 if (RefTy->getPointeeType().isVolatileQualified())
13687 return;
13688
13689 S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
13690 : diag::warn_self_assignment_overloaded)
13691 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
13692 << RHSExpr->getSourceRange();
13693 }
13694
13695 /// Check if a bitwise-& is performed on an Objective-C pointer. This
13696 /// is usually indicative of introspection within the Objective-C pointer.
checkObjCPointerIntrospection(Sema & S,ExprResult & L,ExprResult & R,SourceLocation OpLoc)13697 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
13698 SourceLocation OpLoc) {
13699 if (!S.getLangOpts().ObjC)
13700 return;
13701
13702 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
13703 const Expr *LHS = L.get();
13704 const Expr *RHS = R.get();
13705
13706 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13707 ObjCPointerExpr = LHS;
13708 OtherExpr = RHS;
13709 }
13710 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
13711 ObjCPointerExpr = RHS;
13712 OtherExpr = LHS;
13713 }
13714
13715 // This warning is deliberately made very specific to reduce false
13716 // positives with logic that uses '&' for hashing. This logic mainly
13717 // looks for code trying to introspect into tagged pointers, which
13718 // code should generally never do.
13719 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
13720 unsigned Diag = diag::warn_objc_pointer_masking;
13721 // Determine if we are introspecting the result of performSelectorXXX.
13722 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
13723 // Special case messages to -performSelector and friends, which
13724 // can return non-pointer values boxed in a pointer value.
13725 // Some clients may wish to silence warnings in this subcase.
13726 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
13727 Selector S = ME->getSelector();
13728 StringRef SelArg0 = S.getNameForSlot(0);
13729 if (SelArg0.startswith("performSelector"))
13730 Diag = diag::warn_objc_pointer_masking_performSelector;
13731 }
13732
13733 S.Diag(OpLoc, Diag)
13734 << ObjCPointerExpr->getSourceRange();
13735 }
13736 }
13737
getDeclFromExpr(Expr * E)13738 static NamedDecl *getDeclFromExpr(Expr *E) {
13739 if (!E)
13740 return nullptr;
13741 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
13742 return DRE->getDecl();
13743 if (auto *ME = dyn_cast<MemberExpr>(E))
13744 return ME->getMemberDecl();
13745 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
13746 return IRE->getDecl();
13747 return nullptr;
13748 }
13749
13750 // This helper function promotes a binary operator's operands (which are of a
13751 // half vector type) to a vector of floats and then truncates the result to
13752 // 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)13753 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
13754 BinaryOperatorKind Opc, QualType ResultTy,
13755 ExprValueKind VK, ExprObjectKind OK,
13756 bool IsCompAssign, SourceLocation OpLoc,
13757 FPOptionsOverride FPFeatures) {
13758 auto &Context = S.getASTContext();
13759 assert((isVector(ResultTy, Context.HalfTy) ||
13760 isVector(ResultTy, Context.ShortTy)) &&
13761 "Result must be a vector of half or short");
13762 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
13763 isVector(RHS.get()->getType(), Context.HalfTy) &&
13764 "both operands expected to be a half vector");
13765
13766 RHS = convertVector(RHS.get(), Context.FloatTy, S);
13767 QualType BinOpResTy = RHS.get()->getType();
13768
13769 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
13770 // change BinOpResTy to a vector of ints.
13771 if (isVector(ResultTy, Context.ShortTy))
13772 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
13773
13774 if (IsCompAssign)
13775 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13776 ResultTy, VK, OK, OpLoc, FPFeatures,
13777 BinOpResTy, BinOpResTy);
13778
13779 LHS = convertVector(LHS.get(), Context.FloatTy, S);
13780 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
13781 BinOpResTy, VK, OK, OpLoc, FPFeatures);
13782 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
13783 }
13784
13785 static std::pair<ExprResult, ExprResult>
CorrectDelayedTyposInBinOp(Sema & S,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)13786 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
13787 Expr *RHSExpr) {
13788 ExprResult LHS = LHSExpr, RHS = RHSExpr;
13789 if (!S.Context.isDependenceAllowed()) {
13790 // C cannot handle TypoExpr nodes on either side of a binop because it
13791 // doesn't handle dependent types properly, so make sure any TypoExprs have
13792 // been dealt with before checking the operands.
13793 LHS = S.CorrectDelayedTyposInExpr(LHS);
13794 RHS = S.CorrectDelayedTyposInExpr(
13795 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
13796 [Opc, LHS](Expr *E) {
13797 if (Opc != BO_Assign)
13798 return ExprResult(E);
13799 // Avoid correcting the RHS to the same Expr as the LHS.
13800 Decl *D = getDeclFromExpr(E);
13801 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
13802 });
13803 }
13804 return std::make_pair(LHS, RHS);
13805 }
13806
13807 /// Returns true if conversion between vectors of halfs and vectors of floats
13808 /// is needed.
needsConversionOfHalfVec(bool OpRequiresConversion,ASTContext & Ctx,Expr * E0,Expr * E1=nullptr)13809 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
13810 Expr *E0, Expr *E1 = nullptr) {
13811 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
13812 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
13813 return false;
13814
13815 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
13816 QualType Ty = E->IgnoreImplicit()->getType();
13817
13818 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
13819 // to vectors of floats. Although the element type of the vectors is __fp16,
13820 // the vectors shouldn't be treated as storage-only types. See the
13821 // discussion here: https://reviews.llvm.org/rG825235c140e7
13822 if (const VectorType *VT = Ty->getAs<VectorType>()) {
13823 if (VT->getVectorKind() == VectorType::NeonVector)
13824 return false;
13825 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
13826 }
13827 return false;
13828 };
13829
13830 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
13831 }
13832
13833 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
13834 /// operator @p Opc at location @c TokLoc. This routine only supports
13835 /// built-in operations; ActOnBinOp handles overloaded operators.
CreateBuiltinBinOp(SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)13836 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
13837 BinaryOperatorKind Opc,
13838 Expr *LHSExpr, Expr *RHSExpr) {
13839 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
13840 // The syntax only allows initializer lists on the RHS of assignment,
13841 // so we don't need to worry about accepting invalid code for
13842 // non-assignment operators.
13843 // C++11 5.17p9:
13844 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
13845 // of x = {} is x = T().
13846 InitializationKind Kind = InitializationKind::CreateDirectList(
13847 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13848 InitializedEntity Entity =
13849 InitializedEntity::InitializeTemporary(LHSExpr->getType());
13850 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
13851 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
13852 if (Init.isInvalid())
13853 return Init;
13854 RHSExpr = Init.get();
13855 }
13856
13857 ExprResult LHS = LHSExpr, RHS = RHSExpr;
13858 QualType ResultTy; // Result type of the binary operator.
13859 // The following two variables are used for compound assignment operators
13860 QualType CompLHSTy; // Type of LHS after promotions for computation
13861 QualType CompResultTy; // Type of computation result
13862 ExprValueKind VK = VK_RValue;
13863 ExprObjectKind OK = OK_Ordinary;
13864 bool ConvertHalfVec = false;
13865
13866 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
13867 if (!LHS.isUsable() || !RHS.isUsable())
13868 return ExprError();
13869
13870 if (getLangOpts().OpenCL) {
13871 QualType LHSTy = LHSExpr->getType();
13872 QualType RHSTy = RHSExpr->getType();
13873 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
13874 // the ATOMIC_VAR_INIT macro.
13875 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
13876 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
13877 if (BO_Assign == Opc)
13878 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
13879 else
13880 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13881 return ExprError();
13882 }
13883
13884 // OpenCL special types - image, sampler, pipe, and blocks are to be used
13885 // only with a builtin functions and therefore should be disallowed here.
13886 if (LHSTy->isImageType() || RHSTy->isImageType() ||
13887 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
13888 LHSTy->isPipeType() || RHSTy->isPipeType() ||
13889 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
13890 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
13891 return ExprError();
13892 }
13893 }
13894
13895 switch (Opc) {
13896 case BO_Assign:
13897 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
13898 if (getLangOpts().CPlusPlus &&
13899 LHS.get()->getObjectKind() != OK_ObjCProperty) {
13900 VK = LHS.get()->getValueKind();
13901 OK = LHS.get()->getObjectKind();
13902 }
13903 if (!ResultTy.isNull()) {
13904 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
13905 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
13906
13907 // Avoid copying a block to the heap if the block is assigned to a local
13908 // auto variable that is declared in the same scope as the block. This
13909 // optimization is unsafe if the local variable is declared in an outer
13910 // scope. For example:
13911 //
13912 // BlockTy b;
13913 // {
13914 // b = ^{...};
13915 // }
13916 // // It is unsafe to invoke the block here if it wasn't copied to the
13917 // // heap.
13918 // b();
13919
13920 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
13921 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
13922 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
13923 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
13924 BE->getBlockDecl()->setCanAvoidCopyToHeap();
13925
13926 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
13927 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
13928 NTCUC_Assignment, NTCUK_Copy);
13929 }
13930 RecordModifiableNonNullParam(*this, LHS.get());
13931 break;
13932 case BO_PtrMemD:
13933 case BO_PtrMemI:
13934 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
13935 Opc == BO_PtrMemI);
13936 break;
13937 case BO_Mul:
13938 case BO_Div:
13939 ConvertHalfVec = true;
13940 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
13941 Opc == BO_Div);
13942 break;
13943 case BO_Rem:
13944 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
13945 break;
13946 case BO_Add:
13947 ConvertHalfVec = true;
13948 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
13949 break;
13950 case BO_Sub:
13951 ConvertHalfVec = true;
13952 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
13953 break;
13954 case BO_Shl:
13955 case BO_Shr:
13956 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
13957 break;
13958 case BO_LE:
13959 case BO_LT:
13960 case BO_GE:
13961 case BO_GT:
13962 ConvertHalfVec = true;
13963 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13964 break;
13965 case BO_EQ:
13966 case BO_NE:
13967 ConvertHalfVec = true;
13968 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13969 break;
13970 case BO_Cmp:
13971 ConvertHalfVec = true;
13972 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
13973 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
13974 break;
13975 case BO_And:
13976 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
13977 LLVM_FALLTHROUGH;
13978 case BO_Xor:
13979 case BO_Or:
13980 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
13981 break;
13982 case BO_LAnd:
13983 case BO_LOr:
13984 ConvertHalfVec = true;
13985 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
13986 break;
13987 case BO_MulAssign:
13988 case BO_DivAssign:
13989 ConvertHalfVec = true;
13990 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
13991 Opc == BO_DivAssign);
13992 CompLHSTy = CompResultTy;
13993 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
13994 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
13995 break;
13996 case BO_RemAssign:
13997 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
13998 CompLHSTy = CompResultTy;
13999 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14000 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14001 break;
14002 case BO_AddAssign:
14003 ConvertHalfVec = true;
14004 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14005 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14006 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14007 break;
14008 case BO_SubAssign:
14009 ConvertHalfVec = true;
14010 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14011 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14012 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14013 break;
14014 case BO_ShlAssign:
14015 case BO_ShrAssign:
14016 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14017 CompLHSTy = CompResultTy;
14018 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14019 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14020 break;
14021 case BO_AndAssign:
14022 case BO_OrAssign: // fallthrough
14023 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14024 LLVM_FALLTHROUGH;
14025 case BO_XorAssign:
14026 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14027 CompLHSTy = CompResultTy;
14028 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14029 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
14030 break;
14031 case BO_Comma:
14032 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14033 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14034 VK = RHS.get()->getValueKind();
14035 OK = RHS.get()->getObjectKind();
14036 }
14037 break;
14038 }
14039 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14040 return ExprError();
14041
14042 // Some of the binary operations require promoting operands of half vector to
14043 // float vectors and truncating the result back to half vector. For now, we do
14044 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14045 // arm64).
14046 assert(
14047 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14048 isVector(LHS.get()->getType(), Context.HalfTy)) &&
14049 "both sides are half vectors or neither sides are");
14050 ConvertHalfVec =
14051 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14052
14053 // Check for array bounds violations for both sides of the BinaryOperator
14054 CheckArrayAccess(LHS.get());
14055 CheckArrayAccess(RHS.get());
14056
14057 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14058 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14059 &Context.Idents.get("object_setClass"),
14060 SourceLocation(), LookupOrdinaryName);
14061 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14062 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14063 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14064 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
14065 "object_setClass(")
14066 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14067 ",")
14068 << FixItHint::CreateInsertion(RHSLocEnd, ")");
14069 }
14070 else
14071 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14072 }
14073 else if (const ObjCIvarRefExpr *OIRE =
14074 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14075 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14076
14077 // Opc is not a compound assignment if CompResultTy is null.
14078 if (CompResultTy.isNull()) {
14079 if (ConvertHalfVec)
14080 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14081 OpLoc, CurFPFeatureOverrides());
14082 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14083 VK, OK, OpLoc, CurFPFeatureOverrides());
14084 }
14085
14086 // Handle compound assignments.
14087 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14088 OK_ObjCProperty) {
14089 VK = VK_LValue;
14090 OK = LHS.get()->getObjectKind();
14091 }
14092
14093 // The LHS is not converted to the result type for fixed-point compound
14094 // assignment as the common type is computed on demand. Reset the CompLHSTy
14095 // to the LHS type we would have gotten after unary conversions.
14096 if (CompResultTy->isFixedPointType())
14097 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14098
14099 if (ConvertHalfVec)
14100 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14101 OpLoc, CurFPFeatureOverrides());
14102
14103 return CompoundAssignOperator::Create(
14104 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14105 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14106 }
14107
14108 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14109 /// operators are mixed in a way that suggests that the programmer forgot that
14110 /// comparison operators have higher precedence. The most typical example of
14111 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
DiagnoseBitwisePrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14112 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
14113 SourceLocation OpLoc, Expr *LHSExpr,
14114 Expr *RHSExpr) {
14115 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14116 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14117
14118 // Check that one of the sides is a comparison operator and the other isn't.
14119 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14120 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14121 if (isLeftComp == isRightComp)
14122 return;
14123
14124 // Bitwise operations are sometimes used as eager logical ops.
14125 // Don't diagnose this.
14126 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14127 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14128 if (isLeftBitwise || isRightBitwise)
14129 return;
14130
14131 SourceRange DiagRange = isLeftComp
14132 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14133 : SourceRange(OpLoc, RHSExpr->getEndLoc());
14134 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14135 SourceRange ParensRange =
14136 isLeftComp
14137 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14138 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14139
14140 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14141 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14142 SuggestParentheses(Self, OpLoc,
14143 Self.PDiag(diag::note_precedence_silence) << OpStr,
14144 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14145 SuggestParentheses(Self, OpLoc,
14146 Self.PDiag(diag::note_precedence_bitwise_first)
14147 << BinaryOperator::getOpcodeStr(Opc),
14148 ParensRange);
14149 }
14150
14151 /// It accepts a '&&' expr that is inside a '||' one.
14152 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14153 /// in parentheses.
14154 static void
EmitDiagnosticForLogicalAndInLogicalOr(Sema & Self,SourceLocation OpLoc,BinaryOperator * Bop)14155 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
14156 BinaryOperator *Bop) {
14157 assert(Bop->getOpcode() == BO_LAnd);
14158 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14159 << Bop->getSourceRange() << OpLoc;
14160 SuggestParentheses(Self, Bop->getOperatorLoc(),
14161 Self.PDiag(diag::note_precedence_silence)
14162 << Bop->getOpcodeStr(),
14163 Bop->getSourceRange());
14164 }
14165
14166 /// Returns true if the given expression can be evaluated as a constant
14167 /// 'true'.
EvaluatesAsTrue(Sema & S,Expr * E)14168 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
14169 bool Res;
14170 return !E->isValueDependent() &&
14171 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
14172 }
14173
14174 /// Returns true if the given expression can be evaluated as a constant
14175 /// 'false'.
EvaluatesAsFalse(Sema & S,Expr * E)14176 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
14177 bool Res;
14178 return !E->isValueDependent() &&
14179 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
14180 }
14181
14182 /// Look for '&&' in the left hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrLHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14183 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
14184 Expr *LHSExpr, Expr *RHSExpr) {
14185 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14186 if (Bop->getOpcode() == BO_LAnd) {
14187 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
14188 if (EvaluatesAsFalse(S, RHSExpr))
14189 return;
14190 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
14191 if (!EvaluatesAsTrue(S, Bop->getLHS()))
14192 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14193 } else if (Bop->getOpcode() == BO_LOr) {
14194 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14195 // If it's "a || b && 1 || c" we didn't warn earlier for
14196 // "a || b && 1", but warn now.
14197 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
14198 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14199 }
14200 }
14201 }
14202 }
14203
14204 /// Look for '&&' in the right hand of a '||' expr.
DiagnoseLogicalAndInLogicalOrRHS(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14205 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
14206 Expr *LHSExpr, Expr *RHSExpr) {
14207 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14208 if (Bop->getOpcode() == BO_LAnd) {
14209 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
14210 if (EvaluatesAsFalse(S, LHSExpr))
14211 return;
14212 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
14213 if (!EvaluatesAsTrue(S, Bop->getRHS()))
14214 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14215 }
14216 }
14217 }
14218
14219 /// Look for bitwise op in the left or right hand of a bitwise op with
14220 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
14221 /// the '&' expression in parentheses.
DiagnoseBitwiseOpInBitwiseOp(Sema & S,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * SubExpr)14222 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
14223 SourceLocation OpLoc, Expr *SubExpr) {
14224 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14225 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14226 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14227 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14228 << Bop->getSourceRange() << OpLoc;
14229 SuggestParentheses(S, Bop->getOperatorLoc(),
14230 S.PDiag(diag::note_precedence_silence)
14231 << Bop->getOpcodeStr(),
14232 Bop->getSourceRange());
14233 }
14234 }
14235 }
14236
DiagnoseAdditionInShift(Sema & S,SourceLocation OpLoc,Expr * SubExpr,StringRef Shift)14237 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
14238 Expr *SubExpr, StringRef Shift) {
14239 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14240 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14241 StringRef Op = Bop->getOpcodeStr();
14242 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14243 << Bop->getSourceRange() << OpLoc << Shift << Op;
14244 SuggestParentheses(S, Bop->getOperatorLoc(),
14245 S.PDiag(diag::note_precedence_silence) << Op,
14246 Bop->getSourceRange());
14247 }
14248 }
14249 }
14250
DiagnoseShiftCompare(Sema & S,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14251 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
14252 Expr *LHSExpr, Expr *RHSExpr) {
14253 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14254 if (!OCE)
14255 return;
14256
14257 FunctionDecl *FD = OCE->getDirectCallee();
14258 if (!FD || !FD->isOverloadedOperator())
14259 return;
14260
14261 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
14262 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14263 return;
14264
14265 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
14266 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
14267 << (Kind == OO_LessLess);
14268 SuggestParentheses(S, OCE->getOperatorLoc(),
14269 S.PDiag(diag::note_precedence_silence)
14270 << (Kind == OO_LessLess ? "<<" : ">>"),
14271 OCE->getSourceRange());
14272 SuggestParentheses(
14273 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
14274 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
14275 }
14276
14277 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
14278 /// precedence.
DiagnoseBinOpPrecedence(Sema & Self,BinaryOperatorKind Opc,SourceLocation OpLoc,Expr * LHSExpr,Expr * RHSExpr)14279 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
14280 SourceLocation OpLoc, Expr *LHSExpr,
14281 Expr *RHSExpr){
14282 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
14283 if (BinaryOperator::isBitwiseOp(Opc))
14284 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
14285
14286 // Diagnose "arg1 & arg2 | arg3"
14287 if ((Opc == BO_Or || Opc == BO_Xor) &&
14288 !OpLoc.isMacroID()/* Don't warn in macros. */) {
14289 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
14290 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
14291 }
14292
14293 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
14294 // We don't warn for 'assert(a || b && "bad")' since this is safe.
14295 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
14296 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
14297 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
14298 }
14299
14300 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
14301 || Opc == BO_Shr) {
14302 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
14303 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
14304 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
14305 }
14306
14307 // Warn on overloaded shift operators and comparisons, such as:
14308 // cout << 5 == 4;
14309 if (BinaryOperator::isComparisonOp(Opc))
14310 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
14311 }
14312
14313 // Binary Operators. 'Tok' is the token for the operator.
ActOnBinOp(Scope * S,SourceLocation TokLoc,tok::TokenKind Kind,Expr * LHSExpr,Expr * RHSExpr)14314 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
14315 tok::TokenKind Kind,
14316 Expr *LHSExpr, Expr *RHSExpr) {
14317 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
14318 assert(LHSExpr && "ActOnBinOp(): missing left expression");
14319 assert(RHSExpr && "ActOnBinOp(): missing right expression");
14320
14321 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
14322 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
14323
14324 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
14325 }
14326
LookupBinOp(Scope * S,SourceLocation OpLoc,BinaryOperatorKind Opc,UnresolvedSetImpl & Functions)14327 void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
14328 UnresolvedSetImpl &Functions) {
14329 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
14330 if (OverOp != OO_None && OverOp != OO_Equal)
14331 LookupOverloadedOperatorName(OverOp, S, Functions);
14332
14333 // In C++20 onwards, we may have a second operator to look up.
14334 if (getLangOpts().CPlusPlus20) {
14335 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))
14336 LookupOverloadedOperatorName(ExtraOp, S, Functions);
14337 }
14338 }
14339
14340 /// Build an overloaded binary operator expression in the given scope.
BuildOverloadedBinOp(Sema & S,Scope * Sc,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHS,Expr * RHS)14341 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
14342 BinaryOperatorKind Opc,
14343 Expr *LHS, Expr *RHS) {
14344 switch (Opc) {
14345 case BO_Assign:
14346 case BO_DivAssign:
14347 case BO_RemAssign:
14348 case BO_SubAssign:
14349 case BO_AndAssign:
14350 case BO_OrAssign:
14351 case BO_XorAssign:
14352 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
14353 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
14354 break;
14355 default:
14356 break;
14357 }
14358
14359 // Find all of the overloaded operators visible from this point.
14360 UnresolvedSet<16> Functions;
14361 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
14362
14363 // Build the (potentially-overloaded, potentially-dependent)
14364 // binary operation.
14365 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
14366 }
14367
BuildBinOp(Scope * S,SourceLocation OpLoc,BinaryOperatorKind Opc,Expr * LHSExpr,Expr * RHSExpr)14368 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
14369 BinaryOperatorKind Opc,
14370 Expr *LHSExpr, Expr *RHSExpr) {
14371 ExprResult LHS, RHS;
14372 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14373 if (!LHS.isUsable() || !RHS.isUsable())
14374 return ExprError();
14375 LHSExpr = LHS.get();
14376 RHSExpr = RHS.get();
14377
14378 // We want to end up calling one of checkPseudoObjectAssignment
14379 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
14380 // both expressions are overloadable or either is type-dependent),
14381 // or CreateBuiltinBinOp (in any other case). We also want to get
14382 // any placeholder types out of the way.
14383
14384 // Handle pseudo-objects in the LHS.
14385 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
14386 // Assignments with a pseudo-object l-value need special analysis.
14387 if (pty->getKind() == BuiltinType::PseudoObject &&
14388 BinaryOperator::isAssignmentOp(Opc))
14389 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
14390
14391 // Don't resolve overloads if the other type is overloadable.
14392 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
14393 // We can't actually test that if we still have a placeholder,
14394 // though. Fortunately, none of the exceptions we see in that
14395 // code below are valid when the LHS is an overload set. Note
14396 // that an overload set can be dependently-typed, but it never
14397 // instantiates to having an overloadable type.
14398 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14399 if (resolvedRHS.isInvalid()) return ExprError();
14400 RHSExpr = resolvedRHS.get();
14401
14402 if (RHSExpr->isTypeDependent() ||
14403 RHSExpr->getType()->isOverloadableType())
14404 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14405 }
14406
14407 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
14408 // template, diagnose the missing 'template' keyword instead of diagnosing
14409 // an invalid use of a bound member function.
14410 //
14411 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
14412 // to C++1z [over.over]/1.4, but we already checked for that case above.
14413 if (Opc == BO_LT && inTemplateInstantiation() &&
14414 (pty->getKind() == BuiltinType::BoundMember ||
14415 pty->getKind() == BuiltinType::Overload)) {
14416 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
14417 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
14418 std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
14419 return isa<FunctionTemplateDecl>(ND);
14420 })) {
14421 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
14422 : OE->getNameLoc(),
14423 diag::err_template_kw_missing)
14424 << OE->getName().getAsString() << "";
14425 return ExprError();
14426 }
14427 }
14428
14429 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
14430 if (LHS.isInvalid()) return ExprError();
14431 LHSExpr = LHS.get();
14432 }
14433
14434 // Handle pseudo-objects in the RHS.
14435 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
14436 // An overload in the RHS can potentially be resolved by the type
14437 // being assigned to.
14438 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
14439 if (getLangOpts().CPlusPlus &&
14440 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
14441 LHSExpr->getType()->isOverloadableType()))
14442 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14443
14444 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14445 }
14446
14447 // Don't resolve overloads if the other type is overloadable.
14448 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
14449 LHSExpr->getType()->isOverloadableType())
14450 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14451
14452 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
14453 if (!resolvedRHS.isUsable()) return ExprError();
14454 RHSExpr = resolvedRHS.get();
14455 }
14456
14457 if (getLangOpts().CPlusPlus) {
14458 // If either expression is type-dependent, always build an
14459 // overloaded op.
14460 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
14461 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14462
14463 // Otherwise, build an overloaded op if either expression has an
14464 // overloadable type.
14465 if (LHSExpr->getType()->isOverloadableType() ||
14466 RHSExpr->getType()->isOverloadableType())
14467 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
14468 }
14469
14470 if (getLangOpts().RecoveryAST &&
14471 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
14472 assert(!getLangOpts().CPlusPlus);
14473 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
14474 "Should only occur in error-recovery path.");
14475 if (BinaryOperator::isCompoundAssignmentOp(Opc))
14476 // C [6.15.16] p3:
14477 // An assignment expression has the value of the left operand after the
14478 // assignment, but is not an lvalue.
14479 return CompoundAssignOperator::Create(
14480 Context, LHSExpr, RHSExpr, Opc,
14481 LHSExpr->getType().getUnqualifiedType(), VK_RValue, OK_Ordinary,
14482 OpLoc, CurFPFeatureOverrides());
14483 QualType ResultType;
14484 switch (Opc) {
14485 case BO_Assign:
14486 ResultType = LHSExpr->getType().getUnqualifiedType();
14487 break;
14488 case BO_LT:
14489 case BO_GT:
14490 case BO_LE:
14491 case BO_GE:
14492 case BO_EQ:
14493 case BO_NE:
14494 case BO_LAnd:
14495 case BO_LOr:
14496 // These operators have a fixed result type regardless of operands.
14497 ResultType = Context.IntTy;
14498 break;
14499 case BO_Comma:
14500 ResultType = RHSExpr->getType();
14501 break;
14502 default:
14503 ResultType = Context.DependentTy;
14504 break;
14505 }
14506 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
14507 VK_RValue, OK_Ordinary, OpLoc,
14508 CurFPFeatureOverrides());
14509 }
14510
14511 // Build a built-in binary operation.
14512 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
14513 }
14514
isOverflowingIntegerType(ASTContext & Ctx,QualType T)14515 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
14516 if (T.isNull() || T->isDependentType())
14517 return false;
14518
14519 if (!T->isPromotableIntegerType())
14520 return true;
14521
14522 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
14523 }
14524
CreateBuiltinUnaryOp(SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * InputExpr)14525 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
14526 UnaryOperatorKind Opc,
14527 Expr *InputExpr) {
14528 ExprResult Input = InputExpr;
14529 ExprValueKind VK = VK_RValue;
14530 ExprObjectKind OK = OK_Ordinary;
14531 QualType resultType;
14532 bool CanOverflow = false;
14533
14534 bool ConvertHalfVec = false;
14535 if (getLangOpts().OpenCL) {
14536 QualType Ty = InputExpr->getType();
14537 // The only legal unary operation for atomics is '&'.
14538 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
14539 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14540 // only with a builtin functions and therefore should be disallowed here.
14541 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
14542 || Ty->isBlockPointerType())) {
14543 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14544 << InputExpr->getType()
14545 << Input.get()->getSourceRange());
14546 }
14547 }
14548
14549 switch (Opc) {
14550 case UO_PreInc:
14551 case UO_PreDec:
14552 case UO_PostInc:
14553 case UO_PostDec:
14554 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
14555 OpLoc,
14556 Opc == UO_PreInc ||
14557 Opc == UO_PostInc,
14558 Opc == UO_PreInc ||
14559 Opc == UO_PreDec);
14560 CanOverflow = isOverflowingIntegerType(Context, resultType);
14561 break;
14562 case UO_AddrOf:
14563 resultType = CheckAddressOfOperand(Input, OpLoc);
14564 CheckAddressOfNoDeref(InputExpr);
14565 RecordModifiableNonNullParam(*this, InputExpr);
14566 break;
14567 case UO_Deref: {
14568 Input = DefaultFunctionArrayLvalueConversion(Input.get());
14569 if (Input.isInvalid()) return ExprError();
14570 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
14571 break;
14572 }
14573 case UO_Plus:
14574 case UO_Minus:
14575 CanOverflow = Opc == UO_Minus &&
14576 isOverflowingIntegerType(Context, Input.get()->getType());
14577 Input = UsualUnaryConversions(Input.get());
14578 if (Input.isInvalid()) return ExprError();
14579 // Unary plus and minus require promoting an operand of half vector to a
14580 // float vector and truncating the result back to a half vector. For now, we
14581 // do this only when HalfArgsAndReturns is set (that is, when the target is
14582 // arm or arm64).
14583 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
14584
14585 // If the operand is a half vector, promote it to a float vector.
14586 if (ConvertHalfVec)
14587 Input = convertVector(Input.get(), Context.FloatTy, *this);
14588 resultType = Input.get()->getType();
14589 if (resultType->isDependentType())
14590 break;
14591 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
14592 break;
14593 else if (resultType->isVectorType() &&
14594 // The z vector extensions don't allow + or - with bool vectors.
14595 (!Context.getLangOpts().ZVector ||
14596 resultType->castAs<VectorType>()->getVectorKind() !=
14597 VectorType::AltiVecBool))
14598 break;
14599 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
14600 Opc == UO_Plus &&
14601 resultType->isPointerType())
14602 break;
14603
14604 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14605 << resultType << Input.get()->getSourceRange());
14606
14607 case UO_Not: // bitwise complement
14608 Input = UsualUnaryConversions(Input.get());
14609 if (Input.isInvalid())
14610 return ExprError();
14611 resultType = Input.get()->getType();
14612 if (resultType->isDependentType())
14613 break;
14614 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
14615 if (resultType->isComplexType() || resultType->isComplexIntegerType())
14616 // C99 does not support '~' for complex conjugation.
14617 Diag(OpLoc, diag::ext_integer_complement_complex)
14618 << resultType << Input.get()->getSourceRange();
14619 else if (resultType->hasIntegerRepresentation())
14620 break;
14621 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
14622 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
14623 // on vector float types.
14624 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14625 if (!T->isIntegerType())
14626 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14627 << resultType << Input.get()->getSourceRange());
14628 } else {
14629 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14630 << resultType << Input.get()->getSourceRange());
14631 }
14632 break;
14633
14634 case UO_LNot: // logical negation
14635 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
14636 Input = DefaultFunctionArrayLvalueConversion(Input.get());
14637 if (Input.isInvalid()) return ExprError();
14638 resultType = Input.get()->getType();
14639
14640 // Though we still have to promote half FP to float...
14641 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
14642 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
14643 resultType = Context.FloatTy;
14644 }
14645
14646 if (resultType->isDependentType())
14647 break;
14648 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
14649 // C99 6.5.3.3p1: ok, fallthrough;
14650 if (Context.getLangOpts().CPlusPlus) {
14651 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
14652 // operand contextually converted to bool.
14653 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
14654 ScalarTypeToBooleanCastKind(resultType));
14655 } else if (Context.getLangOpts().OpenCL &&
14656 Context.getLangOpts().OpenCLVersion < 120) {
14657 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14658 // operate on scalar float types.
14659 if (!resultType->isIntegerType() && !resultType->isPointerType())
14660 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14661 << resultType << Input.get()->getSourceRange());
14662 }
14663 } else if (resultType->isExtVectorType()) {
14664 if (Context.getLangOpts().OpenCL &&
14665 Context.getLangOpts().OpenCLVersion < 120 &&
14666 !Context.getLangOpts().OpenCLCPlusPlus) {
14667 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
14668 // operate on vector float types.
14669 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
14670 if (!T->isIntegerType())
14671 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14672 << resultType << Input.get()->getSourceRange());
14673 }
14674 // Vector logical not returns the signed variant of the operand type.
14675 resultType = GetSignedVectorType(resultType);
14676 break;
14677 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
14678 const VectorType *VTy = resultType->castAs<VectorType>();
14679 if (VTy->getVectorKind() != VectorType::GenericVector)
14680 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14681 << resultType << Input.get()->getSourceRange());
14682
14683 // Vector logical not returns the signed variant of the operand type.
14684 resultType = GetSignedVectorType(resultType);
14685 break;
14686 } else {
14687 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
14688 << resultType << Input.get()->getSourceRange());
14689 }
14690
14691 // LNot always has type int. C99 6.5.3.3p5.
14692 // In C++, it's bool. C++ 5.3.1p8
14693 resultType = Context.getLogicalOperationType();
14694 break;
14695 case UO_Real:
14696 case UO_Imag:
14697 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
14698 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
14699 // complex l-values to ordinary l-values and all other values to r-values.
14700 if (Input.isInvalid()) return ExprError();
14701 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
14702 if (Input.get()->getValueKind() != VK_RValue &&
14703 Input.get()->getObjectKind() == OK_Ordinary)
14704 VK = Input.get()->getValueKind();
14705 } else if (!getLangOpts().CPlusPlus) {
14706 // In C, a volatile scalar is read by __imag. In C++, it is not.
14707 Input = DefaultLvalueConversion(Input.get());
14708 }
14709 break;
14710 case UO_Extension:
14711 resultType = Input.get()->getType();
14712 VK = Input.get()->getValueKind();
14713 OK = Input.get()->getObjectKind();
14714 break;
14715 case UO_Coawait:
14716 // It's unnecessary to represent the pass-through operator co_await in the
14717 // AST; just return the input expression instead.
14718 assert(!Input.get()->getType()->isDependentType() &&
14719 "the co_await expression must be non-dependant before "
14720 "building operator co_await");
14721 return Input;
14722 }
14723 if (resultType.isNull() || Input.isInvalid())
14724 return ExprError();
14725
14726 // Check for array bounds violations in the operand of the UnaryOperator,
14727 // except for the '*' and '&' operators that have to be handled specially
14728 // by CheckArrayAccess (as there are special cases like &array[arraysize]
14729 // that are explicitly defined as valid by the standard).
14730 if (Opc != UO_AddrOf && Opc != UO_Deref)
14731 CheckArrayAccess(Input.get());
14732
14733 auto *UO =
14734 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
14735 OpLoc, CanOverflow, CurFPFeatureOverrides());
14736
14737 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
14738 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
14739 !isUnevaluatedContext())
14740 ExprEvalContexts.back().PossibleDerefs.insert(UO);
14741
14742 // Convert the result back to a half vector.
14743 if (ConvertHalfVec)
14744 return convertVector(UO, Context.HalfTy, *this);
14745 return UO;
14746 }
14747
14748 /// Determine whether the given expression is a qualified member
14749 /// access expression, of a form that could be turned into a pointer to member
14750 /// with the address-of operator.
isQualifiedMemberAccess(Expr * E)14751 bool Sema::isQualifiedMemberAccess(Expr *E) {
14752 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14753 if (!DRE->getQualifier())
14754 return false;
14755
14756 ValueDecl *VD = DRE->getDecl();
14757 if (!VD->isCXXClassMember())
14758 return false;
14759
14760 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
14761 return true;
14762 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
14763 return Method->isInstance();
14764
14765 return false;
14766 }
14767
14768 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14769 if (!ULE->getQualifier())
14770 return false;
14771
14772 for (NamedDecl *D : ULE->decls()) {
14773 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
14774 if (Method->isInstance())
14775 return true;
14776 } else {
14777 // Overload set does not contain methods.
14778 break;
14779 }
14780 }
14781
14782 return false;
14783 }
14784
14785 return false;
14786 }
14787
BuildUnaryOp(Scope * S,SourceLocation OpLoc,UnaryOperatorKind Opc,Expr * Input)14788 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
14789 UnaryOperatorKind Opc, Expr *Input) {
14790 // First things first: handle placeholders so that the
14791 // overloaded-operator check considers the right type.
14792 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
14793 // Increment and decrement of pseudo-object references.
14794 if (pty->getKind() == BuiltinType::PseudoObject &&
14795 UnaryOperator::isIncrementDecrementOp(Opc))
14796 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
14797
14798 // extension is always a builtin operator.
14799 if (Opc == UO_Extension)
14800 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14801
14802 // & gets special logic for several kinds of placeholder.
14803 // The builtin code knows what to do.
14804 if (Opc == UO_AddrOf &&
14805 (pty->getKind() == BuiltinType::Overload ||
14806 pty->getKind() == BuiltinType::UnknownAny ||
14807 pty->getKind() == BuiltinType::BoundMember))
14808 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14809
14810 // Anything else needs to be handled now.
14811 ExprResult Result = CheckPlaceholderExpr(Input);
14812 if (Result.isInvalid()) return ExprError();
14813 Input = Result.get();
14814 }
14815
14816 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
14817 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
14818 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
14819 // Find all of the overloaded operators visible from this point.
14820 UnresolvedSet<16> Functions;
14821 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
14822 if (S && OverOp != OO_None)
14823 LookupOverloadedOperatorName(OverOp, S, Functions);
14824
14825 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
14826 }
14827
14828 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
14829 }
14830
14831 // Unary Operators. 'Tok' is the token for the operator.
ActOnUnaryOp(Scope * S,SourceLocation OpLoc,tok::TokenKind Op,Expr * Input)14832 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
14833 tok::TokenKind Op, Expr *Input) {
14834 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
14835 }
14836
14837 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
ActOnAddrLabel(SourceLocation OpLoc,SourceLocation LabLoc,LabelDecl * TheDecl)14838 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
14839 LabelDecl *TheDecl) {
14840 TheDecl->markUsed(Context);
14841 // Create the AST node. The address of a label always has type 'void*'.
14842 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
14843 Context.getPointerType(Context.VoidTy));
14844 }
14845
ActOnStartStmtExpr()14846 void Sema::ActOnStartStmtExpr() {
14847 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14848 }
14849
ActOnStmtExprError()14850 void Sema::ActOnStmtExprError() {
14851 // Note that function is also called by TreeTransform when leaving a
14852 // StmtExpr scope without rebuilding anything.
14853
14854 DiscardCleanupsInEvaluationContext();
14855 PopExpressionEvaluationContext();
14856 }
14857
ActOnStmtExpr(Scope * S,SourceLocation LPLoc,Stmt * SubStmt,SourceLocation RPLoc)14858 ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
14859 SourceLocation RPLoc) {
14860 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
14861 }
14862
BuildStmtExpr(SourceLocation LPLoc,Stmt * SubStmt,SourceLocation RPLoc,unsigned TemplateDepth)14863 ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
14864 SourceLocation RPLoc, unsigned TemplateDepth) {
14865 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
14866 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
14867
14868 if (hasAnyUnrecoverableErrorsInThisFunction())
14869 DiscardCleanupsInEvaluationContext();
14870 assert(!Cleanup.exprNeedsCleanups() &&
14871 "cleanups within StmtExpr not correctly bound!");
14872 PopExpressionEvaluationContext();
14873
14874 // FIXME: there are a variety of strange constraints to enforce here, for
14875 // example, it is not possible to goto into a stmt expression apparently.
14876 // More semantic analysis is needed.
14877
14878 // If there are sub-stmts in the compound stmt, take the type of the last one
14879 // as the type of the stmtexpr.
14880 QualType Ty = Context.VoidTy;
14881 bool StmtExprMayBindToTemp = false;
14882 if (!Compound->body_empty()) {
14883 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
14884 if (const auto *LastStmt =
14885 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
14886 if (const Expr *Value = LastStmt->getExprStmt()) {
14887 StmtExprMayBindToTemp = true;
14888 Ty = Value->getType();
14889 }
14890 }
14891 }
14892
14893 // FIXME: Check that expression type is complete/non-abstract; statement
14894 // expressions are not lvalues.
14895 Expr *ResStmtExpr =
14896 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
14897 if (StmtExprMayBindToTemp)
14898 return MaybeBindToTemporary(ResStmtExpr);
14899 return ResStmtExpr;
14900 }
14901
ActOnStmtExprResult(ExprResult ER)14902 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
14903 if (ER.isInvalid())
14904 return ExprError();
14905
14906 // Do function/array conversion on the last expression, but not
14907 // lvalue-to-rvalue. However, initialize an unqualified type.
14908 ER = DefaultFunctionArrayConversion(ER.get());
14909 if (ER.isInvalid())
14910 return ExprError();
14911 Expr *E = ER.get();
14912
14913 if (E->isTypeDependent())
14914 return E;
14915
14916 // In ARC, if the final expression ends in a consume, splice
14917 // the consume out and bind it later. In the alternate case
14918 // (when dealing with a retainable type), the result
14919 // initialization will create a produce. In both cases the
14920 // result will be +1, and we'll need to balance that out with
14921 // a bind.
14922 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
14923 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
14924 return Cast->getSubExpr();
14925
14926 // FIXME: Provide a better location for the initialization.
14927 return PerformCopyInitialization(
14928 InitializedEntity::InitializeStmtExprResult(
14929 E->getBeginLoc(), E->getType().getUnqualifiedType()),
14930 SourceLocation(), E);
14931 }
14932
BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,TypeSourceInfo * TInfo,ArrayRef<OffsetOfComponent> Components,SourceLocation RParenLoc)14933 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
14934 TypeSourceInfo *TInfo,
14935 ArrayRef<OffsetOfComponent> Components,
14936 SourceLocation RParenLoc) {
14937 QualType ArgTy = TInfo->getType();
14938 bool Dependent = ArgTy->isDependentType();
14939 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
14940
14941 // We must have at least one component that refers to the type, and the first
14942 // one is known to be a field designator. Verify that the ArgTy represents
14943 // a struct/union/class.
14944 if (!Dependent && !ArgTy->isRecordType())
14945 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
14946 << ArgTy << TypeRange);
14947
14948 // Type must be complete per C99 7.17p3 because a declaring a variable
14949 // with an incomplete type would be ill-formed.
14950 if (!Dependent
14951 && RequireCompleteType(BuiltinLoc, ArgTy,
14952 diag::err_offsetof_incomplete_type, TypeRange))
14953 return ExprError();
14954
14955 bool DidWarnAboutNonPOD = false;
14956 QualType CurrentType = ArgTy;
14957 SmallVector<OffsetOfNode, 4> Comps;
14958 SmallVector<Expr*, 4> Exprs;
14959 for (const OffsetOfComponent &OC : Components) {
14960 if (OC.isBrackets) {
14961 // Offset of an array sub-field. TODO: Should we allow vector elements?
14962 if (!CurrentType->isDependentType()) {
14963 const ArrayType *AT = Context.getAsArrayType(CurrentType);
14964 if(!AT)
14965 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
14966 << CurrentType);
14967 CurrentType = AT->getElementType();
14968 } else
14969 CurrentType = Context.DependentTy;
14970
14971 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
14972 if (IdxRval.isInvalid())
14973 return ExprError();
14974 Expr *Idx = IdxRval.get();
14975
14976 // The expression must be an integral expression.
14977 // FIXME: An integral constant expression?
14978 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
14979 !Idx->getType()->isIntegerType())
14980 return ExprError(
14981 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
14982 << Idx->getSourceRange());
14983
14984 // Record this array index.
14985 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
14986 Exprs.push_back(Idx);
14987 continue;
14988 }
14989
14990 // Offset of a field.
14991 if (CurrentType->isDependentType()) {
14992 // We have the offset of a field, but we can't look into the dependent
14993 // type. Just record the identifier of the field.
14994 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
14995 CurrentType = Context.DependentTy;
14996 continue;
14997 }
14998
14999 // We need to have a complete type to look into.
15000 if (RequireCompleteType(OC.LocStart, CurrentType,
15001 diag::err_offsetof_incomplete_type))
15002 return ExprError();
15003
15004 // Look for the designated field.
15005 const RecordType *RC = CurrentType->getAs<RecordType>();
15006 if (!RC)
15007 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15008 << CurrentType);
15009 RecordDecl *RD = RC->getDecl();
15010
15011 // C++ [lib.support.types]p5:
15012 // The macro offsetof accepts a restricted set of type arguments in this
15013 // International Standard. type shall be a POD structure or a POD union
15014 // (clause 9).
15015 // C++11 [support.types]p4:
15016 // If type is not a standard-layout class (Clause 9), the results are
15017 // undefined.
15018 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15019 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15020 unsigned DiagID =
15021 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15022 : diag::ext_offsetof_non_pod_type;
15023
15024 if (!IsSafe && !DidWarnAboutNonPOD &&
15025 DiagRuntimeBehavior(BuiltinLoc, nullptr,
15026 PDiag(DiagID)
15027 << SourceRange(Components[0].LocStart, OC.LocEnd)
15028 << CurrentType))
15029 DidWarnAboutNonPOD = true;
15030 }
15031
15032 // Look for the field.
15033 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15034 LookupQualifiedName(R, RD);
15035 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15036 IndirectFieldDecl *IndirectMemberDecl = nullptr;
15037 if (!MemberDecl) {
15038 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15039 MemberDecl = IndirectMemberDecl->getAnonField();
15040 }
15041
15042 if (!MemberDecl)
15043 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
15044 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
15045 OC.LocEnd));
15046
15047 // C99 7.17p3:
15048 // (If the specified member is a bit-field, the behavior is undefined.)
15049 //
15050 // We diagnose this as an error.
15051 if (MemberDecl->isBitField()) {
15052 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15053 << MemberDecl->getDeclName()
15054 << SourceRange(BuiltinLoc, RParenLoc);
15055 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15056 return ExprError();
15057 }
15058
15059 RecordDecl *Parent = MemberDecl->getParent();
15060 if (IndirectMemberDecl)
15061 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15062
15063 // If the member was found in a base class, introduce OffsetOfNodes for
15064 // the base class indirections.
15065 CXXBasePaths Paths;
15066 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15067 Paths)) {
15068 if (Paths.getDetectedVirtual()) {
15069 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15070 << MemberDecl->getDeclName()
15071 << SourceRange(BuiltinLoc, RParenLoc);
15072 return ExprError();
15073 }
15074
15075 CXXBasePath &Path = Paths.front();
15076 for (const CXXBasePathElement &B : Path)
15077 Comps.push_back(OffsetOfNode(B.Base));
15078 }
15079
15080 if (IndirectMemberDecl) {
15081 for (auto *FI : IndirectMemberDecl->chain()) {
15082 assert(isa<FieldDecl>(FI));
15083 Comps.push_back(OffsetOfNode(OC.LocStart,
15084 cast<FieldDecl>(FI), OC.LocEnd));
15085 }
15086 } else
15087 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15088
15089 CurrentType = MemberDecl->getType().getNonReferenceType();
15090 }
15091
15092 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15093 Comps, Exprs, RParenLoc);
15094 }
15095
ActOnBuiltinOffsetOf(Scope * S,SourceLocation BuiltinLoc,SourceLocation TypeLoc,ParsedType ParsedArgTy,ArrayRef<OffsetOfComponent> Components,SourceLocation RParenLoc)15096 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
15097 SourceLocation BuiltinLoc,
15098 SourceLocation TypeLoc,
15099 ParsedType ParsedArgTy,
15100 ArrayRef<OffsetOfComponent> Components,
15101 SourceLocation RParenLoc) {
15102
15103 TypeSourceInfo *ArgTInfo;
15104 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15105 if (ArgTy.isNull())
15106 return ExprError();
15107
15108 if (!ArgTInfo)
15109 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15110
15111 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15112 }
15113
15114
ActOnChooseExpr(SourceLocation BuiltinLoc,Expr * CondExpr,Expr * LHSExpr,Expr * RHSExpr,SourceLocation RPLoc)15115 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
15116 Expr *CondExpr,
15117 Expr *LHSExpr, Expr *RHSExpr,
15118 SourceLocation RPLoc) {
15119 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15120
15121 ExprValueKind VK = VK_RValue;
15122 ExprObjectKind OK = OK_Ordinary;
15123 QualType resType;
15124 bool CondIsTrue = false;
15125 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15126 resType = Context.DependentTy;
15127 } else {
15128 // The conditional expression is required to be a constant expression.
15129 llvm::APSInt condEval(32);
15130 ExprResult CondICE = VerifyIntegerConstantExpression(
15131 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15132 if (CondICE.isInvalid())
15133 return ExprError();
15134 CondExpr = CondICE.get();
15135 CondIsTrue = condEval.getZExtValue();
15136
15137 // If the condition is > zero, then the AST type is the same as the LHSExpr.
15138 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15139
15140 resType = ActiveExpr->getType();
15141 VK = ActiveExpr->getValueKind();
15142 OK = ActiveExpr->getObjectKind();
15143 }
15144
15145 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15146 resType, VK, OK, RPLoc, CondIsTrue);
15147 }
15148
15149 //===----------------------------------------------------------------------===//
15150 // Clang Extensions.
15151 //===----------------------------------------------------------------------===//
15152
15153 /// ActOnBlockStart - This callback is invoked when a block literal is started.
ActOnBlockStart(SourceLocation CaretLoc,Scope * CurScope)15154 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15155 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
15156
15157 if (LangOpts.CPlusPlus) {
15158 MangleNumberingContext *MCtx;
15159 Decl *ManglingContextDecl;
15160 std::tie(MCtx, ManglingContextDecl) =
15161 getCurrentMangleNumberContext(Block->getDeclContext());
15162 if (MCtx) {
15163 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15164 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15165 }
15166 }
15167
15168 PushBlockScope(CurScope, Block);
15169 CurContext->addDecl(Block);
15170 if (CurScope)
15171 PushDeclContext(CurScope, Block);
15172 else
15173 CurContext = Block;
15174
15175 getCurBlock()->HasImplicitReturnType = true;
15176
15177 // Enter a new evaluation context to insulate the block from any
15178 // cleanups from the enclosing full-expression.
15179 PushExpressionEvaluationContext(
15180 ExpressionEvaluationContext::PotentiallyEvaluated);
15181 }
15182
ActOnBlockArguments(SourceLocation CaretLoc,Declarator & ParamInfo,Scope * CurScope)15183 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
15184 Scope *CurScope) {
15185 assert(ParamInfo.getIdentifier() == nullptr &&
15186 "block-id should have no identifier!");
15187 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15188 BlockScopeInfo *CurBlock = getCurBlock();
15189
15190 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
15191 QualType T = Sig->getType();
15192
15193 // FIXME: We should allow unexpanded parameter packs here, but that would,
15194 // in turn, make the block expression contain unexpanded parameter packs.
15195 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15196 // Drop the parameters.
15197 FunctionProtoType::ExtProtoInfo EPI;
15198 EPI.HasTrailingReturn = false;
15199 EPI.TypeQuals.addConst();
15200 T = Context.getFunctionType(Context.DependentTy, None, EPI);
15201 Sig = Context.getTrivialTypeSourceInfo(T);
15202 }
15203
15204 // GetTypeForDeclarator always produces a function type for a block
15205 // literal signature. Furthermore, it is always a FunctionProtoType
15206 // unless the function was written with a typedef.
15207 assert(T->isFunctionType() &&
15208 "GetTypeForDeclarator made a non-function block signature");
15209
15210 // Look for an explicit signature in that function type.
15211 FunctionProtoTypeLoc ExplicitSignature;
15212
15213 if ((ExplicitSignature = Sig->getTypeLoc()
15214 .getAsAdjusted<FunctionProtoTypeLoc>())) {
15215
15216 // Check whether that explicit signature was synthesized by
15217 // GetTypeForDeclarator. If so, don't save that as part of the
15218 // written signature.
15219 if (ExplicitSignature.getLocalRangeBegin() ==
15220 ExplicitSignature.getLocalRangeEnd()) {
15221 // This would be much cheaper if we stored TypeLocs instead of
15222 // TypeSourceInfos.
15223 TypeLoc Result = ExplicitSignature.getReturnLoc();
15224 unsigned Size = Result.getFullDataSize();
15225 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15226 Sig->getTypeLoc().initializeFullCopy(Result, Size);
15227
15228 ExplicitSignature = FunctionProtoTypeLoc();
15229 }
15230 }
15231
15232 CurBlock->TheDecl->setSignatureAsWritten(Sig);
15233 CurBlock->FunctionType = T;
15234
15235 const auto *Fn = T->castAs<FunctionType>();
15236 QualType RetTy = Fn->getReturnType();
15237 bool isVariadic =
15238 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
15239
15240 CurBlock->TheDecl->setIsVariadic(isVariadic);
15241
15242 // Context.DependentTy is used as a placeholder for a missing block
15243 // return type. TODO: what should we do with declarators like:
15244 // ^ * { ... }
15245 // If the answer is "apply template argument deduction"....
15246 if (RetTy != Context.DependentTy) {
15247 CurBlock->ReturnType = RetTy;
15248 CurBlock->TheDecl->setBlockMissingReturnType(false);
15249 CurBlock->HasImplicitReturnType = false;
15250 }
15251
15252 // Push block parameters from the declarator if we had them.
15253 SmallVector<ParmVarDecl*, 8> Params;
15254 if (ExplicitSignature) {
15255 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
15256 ParmVarDecl *Param = ExplicitSignature.getParam(I);
15257 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
15258 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
15259 // Diagnose this as an extension in C17 and earlier.
15260 if (!getLangOpts().C2x)
15261 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
15262 }
15263 Params.push_back(Param);
15264 }
15265
15266 // Fake up parameter variables if we have a typedef, like
15267 // ^ fntype { ... }
15268 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
15269 for (const auto &I : Fn->param_types()) {
15270 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
15271 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
15272 Params.push_back(Param);
15273 }
15274 }
15275
15276 // Set the parameters on the block decl.
15277 if (!Params.empty()) {
15278 CurBlock->TheDecl->setParams(Params);
15279 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
15280 /*CheckParameterNames=*/false);
15281 }
15282
15283 // Finally we can process decl attributes.
15284 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
15285
15286 // Put the parameter variables in scope.
15287 for (auto AI : CurBlock->TheDecl->parameters()) {
15288 AI->setOwningFunction(CurBlock->TheDecl);
15289
15290 // If this has an identifier, add it to the scope stack.
15291 if (AI->getIdentifier()) {
15292 CheckShadow(CurBlock->TheScope, AI);
15293
15294 PushOnScopeChains(AI, CurBlock->TheScope);
15295 }
15296 }
15297 }
15298
15299 /// ActOnBlockError - If there is an error parsing a block, this callback
15300 /// is invoked to pop the information about the block from the action impl.
ActOnBlockError(SourceLocation CaretLoc,Scope * CurScope)15301 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
15302 // Leave the expression-evaluation context.
15303 DiscardCleanupsInEvaluationContext();
15304 PopExpressionEvaluationContext();
15305
15306 // Pop off CurBlock, handle nested blocks.
15307 PopDeclContext();
15308 PopFunctionScopeInfo();
15309 }
15310
15311 /// ActOnBlockStmtExpr - This is called when the body of a block statement
15312 /// literal was successfully completed. ^(int x){...}
ActOnBlockStmtExpr(SourceLocation CaretLoc,Stmt * Body,Scope * CurScope)15313 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
15314 Stmt *Body, Scope *CurScope) {
15315 // If blocks are disabled, emit an error.
15316 if (!LangOpts.Blocks)
15317 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
15318
15319 // Leave the expression-evaluation context.
15320 if (hasAnyUnrecoverableErrorsInThisFunction())
15321 DiscardCleanupsInEvaluationContext();
15322 assert(!Cleanup.exprNeedsCleanups() &&
15323 "cleanups within block not correctly bound!");
15324 PopExpressionEvaluationContext();
15325
15326 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
15327 BlockDecl *BD = BSI->TheDecl;
15328
15329 if (BSI->HasImplicitReturnType)
15330 deduceClosureReturnType(*BSI);
15331
15332 QualType RetTy = Context.VoidTy;
15333 if (!BSI->ReturnType.isNull())
15334 RetTy = BSI->ReturnType;
15335
15336 bool NoReturn = BD->hasAttr<NoReturnAttr>();
15337 QualType BlockTy;
15338
15339 // If the user wrote a function type in some form, try to use that.
15340 if (!BSI->FunctionType.isNull()) {
15341 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
15342
15343 FunctionType::ExtInfo Ext = FTy->getExtInfo();
15344 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
15345
15346 // Turn protoless block types into nullary block types.
15347 if (isa<FunctionNoProtoType>(FTy)) {
15348 FunctionProtoType::ExtProtoInfo EPI;
15349 EPI.ExtInfo = Ext;
15350 BlockTy = Context.getFunctionType(RetTy, None, EPI);
15351
15352 // Otherwise, if we don't need to change anything about the function type,
15353 // preserve its sugar structure.
15354 } else if (FTy->getReturnType() == RetTy &&
15355 (!NoReturn || FTy->getNoReturnAttr())) {
15356 BlockTy = BSI->FunctionType;
15357
15358 // Otherwise, make the minimal modifications to the function type.
15359 } else {
15360 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
15361 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15362 EPI.TypeQuals = Qualifiers();
15363 EPI.ExtInfo = Ext;
15364 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
15365 }
15366
15367 // If we don't have a function type, just build one from nothing.
15368 } else {
15369 FunctionProtoType::ExtProtoInfo EPI;
15370 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
15371 BlockTy = Context.getFunctionType(RetTy, None, EPI);
15372 }
15373
15374 DiagnoseUnusedParameters(BD->parameters());
15375 BlockTy = Context.getBlockPointerType(BlockTy);
15376
15377 // If needed, diagnose invalid gotos and switches in the block.
15378 if (getCurFunction()->NeedsScopeChecking() &&
15379 !PP.isCodeCompletionEnabled())
15380 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
15381
15382 BD->setBody(cast<CompoundStmt>(Body));
15383
15384 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
15385 DiagnoseUnguardedAvailabilityViolations(BD);
15386
15387 // Try to apply the named return value optimization. We have to check again
15388 // if we can do this, though, because blocks keep return statements around
15389 // to deduce an implicit return type.
15390 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
15391 !BD->isDependentContext())
15392 computeNRVO(Body, BSI);
15393
15394 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
15395 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
15396 checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,
15397 NTCUK_Destruct|NTCUK_Copy);
15398
15399 PopDeclContext();
15400
15401 // Pop the block scope now but keep it alive to the end of this function.
15402 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
15403 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
15404
15405 // Set the captured variables on the block.
15406 SmallVector<BlockDecl::Capture, 4> Captures;
15407 for (Capture &Cap : BSI->Captures) {
15408 if (Cap.isInvalid() || Cap.isThisCapture())
15409 continue;
15410
15411 VarDecl *Var = Cap.getVariable();
15412 Expr *CopyExpr = nullptr;
15413 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
15414 if (const RecordType *Record =
15415 Cap.getCaptureType()->getAs<RecordType>()) {
15416 // The capture logic needs the destructor, so make sure we mark it.
15417 // Usually this is unnecessary because most local variables have
15418 // their destructors marked at declaration time, but parameters are
15419 // an exception because it's technically only the call site that
15420 // actually requires the destructor.
15421 if (isa<ParmVarDecl>(Var))
15422 FinalizeVarWithDestructor(Var, Record);
15423
15424 // Enter a separate potentially-evaluated context while building block
15425 // initializers to isolate their cleanups from those of the block
15426 // itself.
15427 // FIXME: Is this appropriate even when the block itself occurs in an
15428 // unevaluated operand?
15429 EnterExpressionEvaluationContext EvalContext(
15430 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
15431
15432 SourceLocation Loc = Cap.getLocation();
15433
15434 ExprResult Result = BuildDeclarationNameExpr(
15435 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
15436
15437 // According to the blocks spec, the capture of a variable from
15438 // the stack requires a const copy constructor. This is not true
15439 // of the copy/move done to move a __block variable to the heap.
15440 if (!Result.isInvalid() &&
15441 !Result.get()->getType().isConstQualified()) {
15442 Result = ImpCastExprToType(Result.get(),
15443 Result.get()->getType().withConst(),
15444 CK_NoOp, VK_LValue);
15445 }
15446
15447 if (!Result.isInvalid()) {
15448 Result = PerformCopyInitialization(
15449 InitializedEntity::InitializeBlock(Var->getLocation(),
15450 Cap.getCaptureType(), false),
15451 Loc, Result.get());
15452 }
15453
15454 // Build a full-expression copy expression if initialization
15455 // succeeded and used a non-trivial constructor. Recover from
15456 // errors by pretending that the copy isn't necessary.
15457 if (!Result.isInvalid() &&
15458 !cast<CXXConstructExpr>(Result.get())->getConstructor()
15459 ->isTrivial()) {
15460 Result = MaybeCreateExprWithCleanups(Result);
15461 CopyExpr = Result.get();
15462 }
15463 }
15464 }
15465
15466 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
15467 CopyExpr);
15468 Captures.push_back(NewCap);
15469 }
15470 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
15471
15472 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
15473
15474 // If the block isn't obviously global, i.e. it captures anything at
15475 // all, then we need to do a few things in the surrounding context:
15476 if (Result->getBlockDecl()->hasCaptures()) {
15477 // First, this expression has a new cleanup object.
15478 ExprCleanupObjects.push_back(Result->getBlockDecl());
15479 Cleanup.setExprNeedsCleanups(true);
15480
15481 // It also gets a branch-protected scope if any of the captured
15482 // variables needs destruction.
15483 for (const auto &CI : Result->getBlockDecl()->captures()) {
15484 const VarDecl *var = CI.getVariable();
15485 if (var->getType().isDestructedType() != QualType::DK_none) {
15486 setFunctionHasBranchProtectedScope();
15487 break;
15488 }
15489 }
15490 }
15491
15492 if (getCurFunction())
15493 getCurFunction()->addBlock(BD);
15494
15495 return Result;
15496 }
15497
ActOnVAArg(SourceLocation BuiltinLoc,Expr * E,ParsedType Ty,SourceLocation RPLoc)15498 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
15499 SourceLocation RPLoc) {
15500 TypeSourceInfo *TInfo;
15501 GetTypeFromParser(Ty, &TInfo);
15502 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
15503 }
15504
BuildVAArgExpr(SourceLocation BuiltinLoc,Expr * E,TypeSourceInfo * TInfo,SourceLocation RPLoc)15505 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
15506 Expr *E, TypeSourceInfo *TInfo,
15507 SourceLocation RPLoc) {
15508 Expr *OrigExpr = E;
15509 bool IsMS = false;
15510
15511 // CUDA device code does not support varargs.
15512 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
15513 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
15514 CUDAFunctionTarget T = IdentifyCUDATarget(F);
15515 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
15516 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
15517 }
15518 }
15519
15520 // NVPTX does not support va_arg expression.
15521 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
15522 Context.getTargetInfo().getTriple().isNVPTX())
15523 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
15524
15525 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
15526 // as Microsoft ABI on an actual Microsoft platform, where
15527 // __builtin_ms_va_list and __builtin_va_list are the same.)
15528 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
15529 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
15530 QualType MSVaListType = Context.getBuiltinMSVaListType();
15531 if (Context.hasSameType(MSVaListType, E->getType())) {
15532 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
15533 return ExprError();
15534 IsMS = true;
15535 }
15536 }
15537
15538 // Get the va_list type
15539 QualType VaListType = Context.getBuiltinVaListType();
15540 if (!IsMS) {
15541 if (VaListType->isArrayType()) {
15542 // Deal with implicit array decay; for example, on x86-64,
15543 // va_list is an array, but it's supposed to decay to
15544 // a pointer for va_arg.
15545 VaListType = Context.getArrayDecayedType(VaListType);
15546 // Make sure the input expression also decays appropriately.
15547 ExprResult Result = UsualUnaryConversions(E);
15548 if (Result.isInvalid())
15549 return ExprError();
15550 E = Result.get();
15551 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
15552 // If va_list is a record type and we are compiling in C++ mode,
15553 // check the argument using reference binding.
15554 InitializedEntity Entity = InitializedEntity::InitializeParameter(
15555 Context, Context.getLValueReferenceType(VaListType), false);
15556 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
15557 if (Init.isInvalid())
15558 return ExprError();
15559 E = Init.getAs<Expr>();
15560 } else {
15561 // Otherwise, the va_list argument must be an l-value because
15562 // it is modified by va_arg.
15563 if (!E->isTypeDependent() &&
15564 CheckForModifiableLvalue(E, BuiltinLoc, *this))
15565 return ExprError();
15566 }
15567 }
15568
15569 if (!IsMS && !E->isTypeDependent() &&
15570 !Context.hasSameType(VaListType, E->getType()))
15571 return ExprError(
15572 Diag(E->getBeginLoc(),
15573 diag::err_first_argument_to_va_arg_not_of_type_va_list)
15574 << OrigExpr->getType() << E->getSourceRange());
15575
15576 if (!TInfo->getType()->isDependentType()) {
15577 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
15578 diag::err_second_parameter_to_va_arg_incomplete,
15579 TInfo->getTypeLoc()))
15580 return ExprError();
15581
15582 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
15583 TInfo->getType(),
15584 diag::err_second_parameter_to_va_arg_abstract,
15585 TInfo->getTypeLoc()))
15586 return ExprError();
15587
15588 if (!TInfo->getType().isPODType(Context)) {
15589 Diag(TInfo->getTypeLoc().getBeginLoc(),
15590 TInfo->getType()->isObjCLifetimeType()
15591 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
15592 : diag::warn_second_parameter_to_va_arg_not_pod)
15593 << TInfo->getType()
15594 << TInfo->getTypeLoc().getSourceRange();
15595 }
15596
15597 // Check for va_arg where arguments of the given type will be promoted
15598 // (i.e. this va_arg is guaranteed to have undefined behavior).
15599 QualType PromoteType;
15600 if (TInfo->getType()->isPromotableIntegerType()) {
15601 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
15602 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
15603 PromoteType = QualType();
15604 }
15605 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
15606 PromoteType = Context.DoubleTy;
15607 if (!PromoteType.isNull())
15608 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
15609 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
15610 << TInfo->getType()
15611 << PromoteType
15612 << TInfo->getTypeLoc().getSourceRange());
15613 }
15614
15615 QualType T = TInfo->getType().getNonLValueExprType(Context);
15616 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
15617 }
15618
ActOnGNUNullExpr(SourceLocation TokenLoc)15619 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
15620 // The type of __null will be int or long, depending on the size of
15621 // pointers on the target.
15622 QualType Ty;
15623 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
15624 if (pw == Context.getTargetInfo().getIntWidth())
15625 Ty = Context.IntTy;
15626 else if (pw == Context.getTargetInfo().getLongWidth())
15627 Ty = Context.LongTy;
15628 else if (pw == Context.getTargetInfo().getLongLongWidth())
15629 Ty = Context.LongLongTy;
15630 else {
15631 llvm_unreachable("I don't know size of pointer!");
15632 }
15633
15634 return new (Context) GNUNullExpr(Ty, TokenLoc);
15635 }
15636
ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,SourceLocation BuiltinLoc,SourceLocation RPLoc)15637 ExprResult Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
15638 SourceLocation BuiltinLoc,
15639 SourceLocation RPLoc) {
15640 return BuildSourceLocExpr(Kind, BuiltinLoc, RPLoc, CurContext);
15641 }
15642
BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,SourceLocation BuiltinLoc,SourceLocation RPLoc,DeclContext * ParentContext)15643 ExprResult Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
15644 SourceLocation BuiltinLoc,
15645 SourceLocation RPLoc,
15646 DeclContext *ParentContext) {
15647 return new (Context)
15648 SourceLocExpr(Context, Kind, BuiltinLoc, RPLoc, ParentContext);
15649 }
15650
CheckConversionToObjCLiteral(QualType DstType,Expr * & Exp,bool Diagnose)15651 bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
15652 bool Diagnose) {
15653 if (!getLangOpts().ObjC)
15654 return false;
15655
15656 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
15657 if (!PT)
15658 return false;
15659 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
15660
15661 // Ignore any parens, implicit casts (should only be
15662 // array-to-pointer decays), and not-so-opaque values. The last is
15663 // important for making this trigger for property assignments.
15664 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
15665 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
15666 if (OV->getSourceExpr())
15667 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
15668
15669 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
15670 if (!PT->isObjCIdType() &&
15671 !(ID && ID->getIdentifier()->isStr("NSString")))
15672 return false;
15673 if (!SL->isAscii())
15674 return false;
15675
15676 if (Diagnose) {
15677 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
15678 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
15679 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
15680 }
15681 return true;
15682 }
15683
15684 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
15685 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
15686 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
15687 !SrcExpr->isNullPointerConstant(
15688 getASTContext(), Expr::NPC_NeverValueDependent)) {
15689 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
15690 return false;
15691 if (Diagnose) {
15692 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
15693 << /*number*/1
15694 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
15695 Expr *NumLit =
15696 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
15697 if (NumLit)
15698 Exp = NumLit;
15699 }
15700 return true;
15701 }
15702
15703 return false;
15704 }
15705
maybeDiagnoseAssignmentToFunction(Sema & S,QualType DstType,const Expr * SrcExpr)15706 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
15707 const Expr *SrcExpr) {
15708 if (!DstType->isFunctionPointerType() ||
15709 !SrcExpr->getType()->isFunctionType())
15710 return false;
15711
15712 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
15713 if (!DRE)
15714 return false;
15715
15716 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
15717 if (!FD)
15718 return false;
15719
15720 return !S.checkAddressOfFunctionIsAvailable(FD,
15721 /*Complain=*/true,
15722 SrcExpr->getBeginLoc());
15723 }
15724
DiagnoseAssignmentResult(AssignConvertType ConvTy,SourceLocation Loc,QualType DstType,QualType SrcType,Expr * SrcExpr,AssignmentAction Action,bool * Complained)15725 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
15726 SourceLocation Loc,
15727 QualType DstType, QualType SrcType,
15728 Expr *SrcExpr, AssignmentAction Action,
15729 bool *Complained) {
15730 if (Complained)
15731 *Complained = false;
15732
15733 // Decode the result (notice that AST's are still created for extensions).
15734 bool CheckInferredResultType = false;
15735 bool isInvalid = false;
15736 unsigned DiagKind = 0;
15737 ConversionFixItGenerator ConvHints;
15738 bool MayHaveConvFixit = false;
15739 bool MayHaveFunctionDiff = false;
15740 const ObjCInterfaceDecl *IFace = nullptr;
15741 const ObjCProtocolDecl *PDecl = nullptr;
15742
15743 switch (ConvTy) {
15744 case Compatible:
15745 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
15746 return false;
15747
15748 case PointerToInt:
15749 if (getLangOpts().CPlusPlus) {
15750 DiagKind = diag::err_typecheck_convert_pointer_int;
15751 isInvalid = true;
15752 } else {
15753 DiagKind = diag::ext_typecheck_convert_pointer_int;
15754 }
15755 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15756 MayHaveConvFixit = true;
15757 break;
15758 case IntToPointer:
15759 if (getLangOpts().CPlusPlus) {
15760 DiagKind = diag::err_typecheck_convert_int_pointer;
15761 isInvalid = true;
15762 } else {
15763 DiagKind = diag::ext_typecheck_convert_int_pointer;
15764 }
15765 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15766 MayHaveConvFixit = true;
15767 break;
15768 case IncompatibleFunctionPointer:
15769 if (getLangOpts().CPlusPlus) {
15770 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
15771 isInvalid = true;
15772 } else {
15773 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
15774 }
15775 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15776 MayHaveConvFixit = true;
15777 break;
15778 case IncompatiblePointer:
15779 if (Action == AA_Passing_CFAudited) {
15780 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
15781 } else if (getLangOpts().CPlusPlus) {
15782 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
15783 isInvalid = true;
15784 } else {
15785 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
15786 }
15787 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
15788 SrcType->isObjCObjectPointerType();
15789 if (!CheckInferredResultType) {
15790 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15791 } else if (CheckInferredResultType) {
15792 SrcType = SrcType.getUnqualifiedType();
15793 DstType = DstType.getUnqualifiedType();
15794 }
15795 MayHaveConvFixit = true;
15796 break;
15797 case IncompatiblePointerSign:
15798 if (getLangOpts().CPlusPlus) {
15799 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
15800 isInvalid = true;
15801 } else {
15802 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
15803 }
15804 break;
15805 case FunctionVoidPointer:
15806 if (getLangOpts().CPlusPlus) {
15807 DiagKind = diag::err_typecheck_convert_pointer_void_func;
15808 isInvalid = true;
15809 } else {
15810 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
15811 }
15812 break;
15813 case IncompatiblePointerDiscardsQualifiers: {
15814 // Perform array-to-pointer decay if necessary.
15815 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
15816
15817 isInvalid = true;
15818
15819 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
15820 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
15821 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
15822 DiagKind = diag::err_typecheck_incompatible_address_space;
15823 break;
15824
15825 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
15826 DiagKind = diag::err_typecheck_incompatible_ownership;
15827 break;
15828 }
15829
15830 llvm_unreachable("unknown error case for discarding qualifiers!");
15831 // fallthrough
15832 }
15833 case CompatiblePointerDiscardsQualifiers:
15834 // If the qualifiers lost were because we were applying the
15835 // (deprecated) C++ conversion from a string literal to a char*
15836 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
15837 // Ideally, this check would be performed in
15838 // checkPointerTypesForAssignment. However, that would require a
15839 // bit of refactoring (so that the second argument is an
15840 // expression, rather than a type), which should be done as part
15841 // of a larger effort to fix checkPointerTypesForAssignment for
15842 // C++ semantics.
15843 if (getLangOpts().CPlusPlus &&
15844 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
15845 return false;
15846 if (getLangOpts().CPlusPlus) {
15847 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
15848 isInvalid = true;
15849 } else {
15850 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
15851 }
15852
15853 break;
15854 case IncompatibleNestedPointerQualifiers:
15855 if (getLangOpts().CPlusPlus) {
15856 isInvalid = true;
15857 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
15858 } else {
15859 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
15860 }
15861 break;
15862 case IncompatibleNestedPointerAddressSpaceMismatch:
15863 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
15864 isInvalid = true;
15865 break;
15866 case IntToBlockPointer:
15867 DiagKind = diag::err_int_to_block_pointer;
15868 isInvalid = true;
15869 break;
15870 case IncompatibleBlockPointer:
15871 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
15872 isInvalid = true;
15873 break;
15874 case IncompatibleObjCQualifiedId: {
15875 if (SrcType->isObjCQualifiedIdType()) {
15876 const ObjCObjectPointerType *srcOPT =
15877 SrcType->castAs<ObjCObjectPointerType>();
15878 for (auto *srcProto : srcOPT->quals()) {
15879 PDecl = srcProto;
15880 break;
15881 }
15882 if (const ObjCInterfaceType *IFaceT =
15883 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15884 IFace = IFaceT->getDecl();
15885 }
15886 else if (DstType->isObjCQualifiedIdType()) {
15887 const ObjCObjectPointerType *dstOPT =
15888 DstType->castAs<ObjCObjectPointerType>();
15889 for (auto *dstProto : dstOPT->quals()) {
15890 PDecl = dstProto;
15891 break;
15892 }
15893 if (const ObjCInterfaceType *IFaceT =
15894 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
15895 IFace = IFaceT->getDecl();
15896 }
15897 if (getLangOpts().CPlusPlus) {
15898 DiagKind = diag::err_incompatible_qualified_id;
15899 isInvalid = true;
15900 } else {
15901 DiagKind = diag::warn_incompatible_qualified_id;
15902 }
15903 break;
15904 }
15905 case IncompatibleVectors:
15906 if (getLangOpts().CPlusPlus) {
15907 DiagKind = diag::err_incompatible_vectors;
15908 isInvalid = true;
15909 } else {
15910 DiagKind = diag::warn_incompatible_vectors;
15911 }
15912 break;
15913 case IncompatibleObjCWeakRef:
15914 DiagKind = diag::err_arc_weak_unavailable_assign;
15915 isInvalid = true;
15916 break;
15917 case Incompatible:
15918 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
15919 if (Complained)
15920 *Complained = true;
15921 return true;
15922 }
15923
15924 DiagKind = diag::err_typecheck_convert_incompatible;
15925 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
15926 MayHaveConvFixit = true;
15927 isInvalid = true;
15928 MayHaveFunctionDiff = true;
15929 break;
15930 }
15931
15932 QualType FirstType, SecondType;
15933 switch (Action) {
15934 case AA_Assigning:
15935 case AA_Initializing:
15936 // The destination type comes first.
15937 FirstType = DstType;
15938 SecondType = SrcType;
15939 break;
15940
15941 case AA_Returning:
15942 case AA_Passing:
15943 case AA_Passing_CFAudited:
15944 case AA_Converting:
15945 case AA_Sending:
15946 case AA_Casting:
15947 // The source type comes first.
15948 FirstType = SrcType;
15949 SecondType = DstType;
15950 break;
15951 }
15952
15953 PartialDiagnostic FDiag = PDiag(DiagKind);
15954 if (Action == AA_Passing_CFAudited)
15955 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
15956 else
15957 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
15958
15959 // If we can fix the conversion, suggest the FixIts.
15960 if (!ConvHints.isNull()) {
15961 for (FixItHint &H : ConvHints.Hints)
15962 FDiag << H;
15963 }
15964
15965 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
15966
15967 if (MayHaveFunctionDiff)
15968 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
15969
15970 Diag(Loc, FDiag);
15971 if ((DiagKind == diag::warn_incompatible_qualified_id ||
15972 DiagKind == diag::err_incompatible_qualified_id) &&
15973 PDecl && IFace && !IFace->hasDefinition())
15974 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
15975 << IFace << PDecl;
15976
15977 if (SecondType == Context.OverloadTy)
15978 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
15979 FirstType, /*TakingAddress=*/true);
15980
15981 if (CheckInferredResultType)
15982 EmitRelatedResultTypeNote(SrcExpr);
15983
15984 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
15985 EmitRelatedResultTypeNoteForReturn(DstType);
15986
15987 if (Complained)
15988 *Complained = true;
15989 return isInvalid;
15990 }
15991
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,AllowFoldKind CanFold)15992 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
15993 llvm::APSInt *Result,
15994 AllowFoldKind CanFold) {
15995 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
15996 public:
15997 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
15998 QualType T) override {
15999 return S.Diag(Loc, diag::err_ice_not_integral)
16000 << T << S.LangOpts.CPlusPlus;
16001 }
16002 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16003 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16004 }
16005 } Diagnoser;
16006
16007 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16008 }
16009
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,unsigned DiagID,AllowFoldKind CanFold)16010 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
16011 llvm::APSInt *Result,
16012 unsigned DiagID,
16013 AllowFoldKind CanFold) {
16014 class IDDiagnoser : public VerifyICEDiagnoser {
16015 unsigned DiagID;
16016
16017 public:
16018 IDDiagnoser(unsigned DiagID)
16019 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16020
16021 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16022 return S.Diag(Loc, DiagID);
16023 }
16024 } Diagnoser(DiagID);
16025
16026 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16027 }
16028
16029 Sema::SemaDiagnosticBuilder
diagnoseNotICEType(Sema & S,SourceLocation Loc,QualType T)16030 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
16031 QualType T) {
16032 return diagnoseNotICE(S, Loc);
16033 }
16034
16035 Sema::SemaDiagnosticBuilder
diagnoseFold(Sema & S,SourceLocation Loc)16036 Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
16037 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16038 }
16039
16040 ExprResult
VerifyIntegerConstantExpression(Expr * E,llvm::APSInt * Result,VerifyICEDiagnoser & Diagnoser,AllowFoldKind CanFold)16041 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
16042 VerifyICEDiagnoser &Diagnoser,
16043 AllowFoldKind CanFold) {
16044 SourceLocation DiagLoc = E->getBeginLoc();
16045
16046 if (getLangOpts().CPlusPlus11) {
16047 // C++11 [expr.const]p5:
16048 // If an expression of literal class type is used in a context where an
16049 // integral constant expression is required, then that class type shall
16050 // have a single non-explicit conversion function to an integral or
16051 // unscoped enumeration type
16052 ExprResult Converted;
16053 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16054 VerifyICEDiagnoser &BaseDiagnoser;
16055 public:
16056 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16057 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16058 BaseDiagnoser.Suppress, true),
16059 BaseDiagnoser(BaseDiagnoser) {}
16060
16061 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16062 QualType T) override {
16063 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16064 }
16065
16066 SemaDiagnosticBuilder diagnoseIncomplete(
16067 Sema &S, SourceLocation Loc, QualType T) override {
16068 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16069 }
16070
16071 SemaDiagnosticBuilder diagnoseExplicitConv(
16072 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16073 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16074 }
16075
16076 SemaDiagnosticBuilder noteExplicitConv(
16077 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16078 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16079 << ConvTy->isEnumeralType() << ConvTy;
16080 }
16081
16082 SemaDiagnosticBuilder diagnoseAmbiguous(
16083 Sema &S, SourceLocation Loc, QualType T) override {
16084 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16085 }
16086
16087 SemaDiagnosticBuilder noteAmbiguous(
16088 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16089 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16090 << ConvTy->isEnumeralType() << ConvTy;
16091 }
16092
16093 SemaDiagnosticBuilder diagnoseConversion(
16094 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16095 llvm_unreachable("conversion functions are permitted");
16096 }
16097 } ConvertDiagnoser(Diagnoser);
16098
16099 Converted = PerformContextualImplicitConversion(DiagLoc, E,
16100 ConvertDiagnoser);
16101 if (Converted.isInvalid())
16102 return Converted;
16103 E = Converted.get();
16104 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
16105 return ExprError();
16106 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16107 // An ICE must be of integral or unscoped enumeration type.
16108 if (!Diagnoser.Suppress)
16109 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16110 << E->getSourceRange();
16111 return ExprError();
16112 }
16113
16114 ExprResult RValueExpr = DefaultLvalueConversion(E);
16115 if (RValueExpr.isInvalid())
16116 return ExprError();
16117
16118 E = RValueExpr.get();
16119
16120 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
16121 // in the non-ICE case.
16122 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
16123 if (Result)
16124 *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
16125 if (!isa<ConstantExpr>(E))
16126 E = ConstantExpr::Create(Context, E);
16127 return E;
16128 }
16129
16130 Expr::EvalResult EvalResult;
16131 SmallVector<PartialDiagnosticAt, 8> Notes;
16132 EvalResult.Diag = &Notes;
16133
16134 // Try to evaluate the expression, and produce diagnostics explaining why it's
16135 // not a constant expression as a side-effect.
16136 bool Folded =
16137 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
16138 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
16139
16140 if (!isa<ConstantExpr>(E))
16141 E = ConstantExpr::Create(Context, E, EvalResult.Val);
16142
16143 // In C++11, we can rely on diagnostics being produced for any expression
16144 // which is not a constant expression. If no diagnostics were produced, then
16145 // this is a constant expression.
16146 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
16147 if (Result)
16148 *Result = EvalResult.Val.getInt();
16149 return E;
16150 }
16151
16152 // If our only note is the usual "invalid subexpression" note, just point
16153 // the caret at its location rather than producing an essentially
16154 // redundant note.
16155 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
16156 diag::note_invalid_subexpr_in_const_expr) {
16157 DiagLoc = Notes[0].first;
16158 Notes.clear();
16159 }
16160
16161 if (!Folded || !CanFold) {
16162 if (!Diagnoser.Suppress) {
16163 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
16164 for (const PartialDiagnosticAt &Note : Notes)
16165 Diag(Note.first, Note.second);
16166 }
16167
16168 return ExprError();
16169 }
16170
16171 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
16172 for (const PartialDiagnosticAt &Note : Notes)
16173 Diag(Note.first, Note.second);
16174
16175 if (Result)
16176 *Result = EvalResult.Val.getInt();
16177 return E;
16178 }
16179
16180 namespace {
16181 // Handle the case where we conclude a expression which we speculatively
16182 // considered to be unevaluated is actually evaluated.
16183 class TransformToPE : public TreeTransform<TransformToPE> {
16184 typedef TreeTransform<TransformToPE> BaseTransform;
16185
16186 public:
TransformToPE(Sema & SemaRef)16187 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
16188
16189 // Make sure we redo semantic analysis
AlwaysRebuild()16190 bool AlwaysRebuild() { return true; }
ReplacingOriginal()16191 bool ReplacingOriginal() { return true; }
16192
16193 // We need to special-case DeclRefExprs referring to FieldDecls which
16194 // are not part of a member pointer formation; normal TreeTransforming
16195 // doesn't catch this case because of the way we represent them in the AST.
16196 // FIXME: This is a bit ugly; is it really the best way to handle this
16197 // case?
16198 //
16199 // Error on DeclRefExprs referring to FieldDecls.
TransformDeclRefExpr(DeclRefExpr * E)16200 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16201 if (isa<FieldDecl>(E->getDecl()) &&
16202 !SemaRef.isUnevaluatedContext())
16203 return SemaRef.Diag(E->getLocation(),
16204 diag::err_invalid_non_static_member_use)
16205 << E->getDecl() << E->getSourceRange();
16206
16207 return BaseTransform::TransformDeclRefExpr(E);
16208 }
16209
16210 // Exception: filter out member pointer formation
TransformUnaryOperator(UnaryOperator * E)16211 ExprResult TransformUnaryOperator(UnaryOperator *E) {
16212 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
16213 return E;
16214
16215 return BaseTransform::TransformUnaryOperator(E);
16216 }
16217
16218 // The body of a lambda-expression is in a separate expression evaluation
16219 // context so never needs to be transformed.
16220 // FIXME: Ideally we wouldn't transform the closure type either, and would
16221 // just recreate the capture expressions and lambda expression.
TransformLambdaBody(LambdaExpr * E,Stmt * Body)16222 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
16223 return SkipLambdaBody(E, Body);
16224 }
16225 };
16226 }
16227
TransformToPotentiallyEvaluated(Expr * E)16228 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
16229 assert(isUnevaluatedContext() &&
16230 "Should only transform unevaluated expressions");
16231 ExprEvalContexts.back().Context =
16232 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
16233 if (isUnevaluatedContext())
16234 return E;
16235 return TransformToPE(*this).TransformExpr(E);
16236 }
16237
16238 void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,Decl * LambdaContextDecl,ExpressionEvaluationContextRecord::ExpressionKind ExprContext)16239 Sema::PushExpressionEvaluationContext(
16240 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
16241 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16242 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
16243 LambdaContextDecl, ExprContext);
16244 Cleanup.reset();
16245 if (!MaybeODRUseExprs.empty())
16246 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
16247 }
16248
16249 void
PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,ReuseLambdaContextDecl_t,ExpressionEvaluationContextRecord::ExpressionKind ExprContext)16250 Sema::PushExpressionEvaluationContext(
16251 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
16252 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
16253 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
16254 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
16255 }
16256
16257 namespace {
16258
CheckPossibleDeref(Sema & S,const Expr * PossibleDeref)16259 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
16260 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
16261 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
16262 if (E->getOpcode() == UO_Deref)
16263 return CheckPossibleDeref(S, E->getSubExpr());
16264 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
16265 return CheckPossibleDeref(S, E->getBase());
16266 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
16267 return CheckPossibleDeref(S, E->getBase());
16268 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
16269 QualType Inner;
16270 QualType Ty = E->getType();
16271 if (const auto *Ptr = Ty->getAs<PointerType>())
16272 Inner = Ptr->getPointeeType();
16273 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
16274 Inner = Arr->getElementType();
16275 else
16276 return nullptr;
16277
16278 if (Inner->hasAttr(attr::NoDeref))
16279 return E;
16280 }
16281 return nullptr;
16282 }
16283
16284 } // namespace
16285
WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord & Rec)16286 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
16287 for (const Expr *E : Rec.PossibleDerefs) {
16288 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
16289 if (DeclRef) {
16290 const ValueDecl *Decl = DeclRef->getDecl();
16291 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
16292 << Decl->getName() << E->getSourceRange();
16293 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
16294 } else {
16295 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
16296 << E->getSourceRange();
16297 }
16298 }
16299 Rec.PossibleDerefs.clear();
16300 }
16301
16302 /// Check whether E, which is either a discarded-value expression or an
16303 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
16304 /// and if so, remove it from the list of volatile-qualified assignments that
16305 /// we are going to warn are deprecated.
CheckUnusedVolatileAssignment(Expr * E)16306 void Sema::CheckUnusedVolatileAssignment(Expr *E) {
16307 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
16308 return;
16309
16310 // Note: ignoring parens here is not justified by the standard rules, but
16311 // ignoring parentheses seems like a more reasonable approach, and this only
16312 // drives a deprecation warning so doesn't affect conformance.
16313 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
16314 if (BO->getOpcode() == BO_Assign) {
16315 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
16316 LHSs.erase(std::remove(LHSs.begin(), LHSs.end(), BO->getLHS()),
16317 LHSs.end());
16318 }
16319 }
16320 }
16321
CheckForImmediateInvocation(ExprResult E,FunctionDecl * Decl)16322 ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
16323 if (!E.isUsable() || !Decl || !Decl->isConsteval() || isConstantEvaluated() ||
16324 RebuildingImmediateInvocation)
16325 return E;
16326
16327 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
16328 /// It's OK if this fails; we'll also remove this in
16329 /// HandleImmediateInvocations, but catching it here allows us to avoid
16330 /// walking the AST looking for it in simple cases.
16331 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
16332 if (auto *DeclRef =
16333 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
16334 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
16335
16336 E = MaybeCreateExprWithCleanups(E);
16337
16338 ConstantExpr *Res = ConstantExpr::Create(
16339 getASTContext(), E.get(),
16340 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
16341 getASTContext()),
16342 /*IsImmediateInvocation*/ true);
16343 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
16344 return Res;
16345 }
16346
EvaluateAndDiagnoseImmediateInvocation(Sema & SemaRef,Sema::ImmediateInvocationCandidate Candidate)16347 static void EvaluateAndDiagnoseImmediateInvocation(
16348 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
16349 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
16350 Expr::EvalResult Eval;
16351 Eval.Diag = &Notes;
16352 ConstantExpr *CE = Candidate.getPointer();
16353 bool Result = CE->EvaluateAsConstantExpr(
16354 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
16355 if (!Result || !Notes.empty()) {
16356 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
16357 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
16358 InnerExpr = FunctionalCast->getSubExpr();
16359 FunctionDecl *FD = nullptr;
16360 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
16361 FD = cast<FunctionDecl>(Call->getCalleeDecl());
16362 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
16363 FD = Call->getConstructor();
16364 else
16365 llvm_unreachable("unhandled decl kind");
16366 assert(FD->isConsteval());
16367 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call) << FD;
16368 for (auto &Note : Notes)
16369 SemaRef.Diag(Note.first, Note.second);
16370 return;
16371 }
16372 CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());
16373 }
16374
RemoveNestedImmediateInvocation(Sema & SemaRef,Sema::ExpressionEvaluationContextRecord & Rec,SmallVector<Sema::ImmediateInvocationCandidate,4>::reverse_iterator It)16375 static void RemoveNestedImmediateInvocation(
16376 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
16377 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
16378 struct ComplexRemove : TreeTransform<ComplexRemove> {
16379 using Base = TreeTransform<ComplexRemove>;
16380 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16381 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
16382 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
16383 CurrentII;
16384 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
16385 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
16386 SmallVector<Sema::ImmediateInvocationCandidate,
16387 4>::reverse_iterator Current)
16388 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
16389 void RemoveImmediateInvocation(ConstantExpr* E) {
16390 auto It = std::find_if(CurrentII, IISet.rend(),
16391 [E](Sema::ImmediateInvocationCandidate Elem) {
16392 return Elem.getPointer() == E;
16393 });
16394 assert(It != IISet.rend() &&
16395 "ConstantExpr marked IsImmediateInvocation should "
16396 "be present");
16397 It->setInt(1); // Mark as deleted
16398 }
16399 ExprResult TransformConstantExpr(ConstantExpr *E) {
16400 if (!E->isImmediateInvocation())
16401 return Base::TransformConstantExpr(E);
16402 RemoveImmediateInvocation(E);
16403 return Base::TransformExpr(E->getSubExpr());
16404 }
16405 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
16406 /// we need to remove its DeclRefExpr from the DRSet.
16407 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
16408 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
16409 return Base::TransformCXXOperatorCallExpr(E);
16410 }
16411 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
16412 /// here.
16413 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
16414 if (!Init)
16415 return Init;
16416 /// ConstantExpr are the first layer of implicit node to be removed so if
16417 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
16418 if (auto *CE = dyn_cast<ConstantExpr>(Init))
16419 if (CE->isImmediateInvocation())
16420 RemoveImmediateInvocation(CE);
16421 return Base::TransformInitializer(Init, NotCopyInit);
16422 }
16423 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
16424 DRSet.erase(E);
16425 return E;
16426 }
16427 bool AlwaysRebuild() { return false; }
16428 bool ReplacingOriginal() { return true; }
16429 bool AllowSkippingCXXConstructExpr() {
16430 bool Res = AllowSkippingFirstCXXConstructExpr;
16431 AllowSkippingFirstCXXConstructExpr = true;
16432 return Res;
16433 }
16434 bool AllowSkippingFirstCXXConstructExpr = true;
16435 } Transformer(SemaRef, Rec.ReferenceToConsteval,
16436 Rec.ImmediateInvocationCandidates, It);
16437
16438 /// CXXConstructExpr with a single argument are getting skipped by
16439 /// TreeTransform in some situtation because they could be implicit. This
16440 /// can only occur for the top-level CXXConstructExpr because it is used
16441 /// nowhere in the expression being transformed therefore will not be rebuilt.
16442 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
16443 /// skipping the first CXXConstructExpr.
16444 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
16445 Transformer.AllowSkippingFirstCXXConstructExpr = false;
16446
16447 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
16448 assert(Res.isUsable());
16449 Res = SemaRef.MaybeCreateExprWithCleanups(Res);
16450 It->getPointer()->setSubExpr(Res.get());
16451 }
16452
16453 static void
HandleImmediateInvocations(Sema & SemaRef,Sema::ExpressionEvaluationContextRecord & Rec)16454 HandleImmediateInvocations(Sema &SemaRef,
16455 Sema::ExpressionEvaluationContextRecord &Rec) {
16456 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
16457 Rec.ReferenceToConsteval.size() == 0) ||
16458 SemaRef.RebuildingImmediateInvocation)
16459 return;
16460
16461 /// When we have more then 1 ImmediateInvocationCandidates we need to check
16462 /// for nested ImmediateInvocationCandidates. when we have only 1 we only
16463 /// need to remove ReferenceToConsteval in the immediate invocation.
16464 if (Rec.ImmediateInvocationCandidates.size() > 1) {
16465
16466 /// Prevent sema calls during the tree transform from adding pointers that
16467 /// are already in the sets.
16468 llvm::SaveAndRestore<bool> DisableIITracking(
16469 SemaRef.RebuildingImmediateInvocation, true);
16470
16471 /// Prevent diagnostic during tree transfrom as they are duplicates
16472 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
16473
16474 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
16475 It != Rec.ImmediateInvocationCandidates.rend(); It++)
16476 if (!It->getInt())
16477 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
16478 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
16479 Rec.ReferenceToConsteval.size()) {
16480 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
16481 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
16482 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
16483 bool VisitDeclRefExpr(DeclRefExpr *E) {
16484 DRSet.erase(E);
16485 return DRSet.size();
16486 }
16487 } Visitor(Rec.ReferenceToConsteval);
16488 Visitor.TraverseStmt(
16489 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
16490 }
16491 for (auto CE : Rec.ImmediateInvocationCandidates)
16492 if (!CE.getInt())
16493 EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);
16494 for (auto DR : Rec.ReferenceToConsteval) {
16495 auto *FD = cast<FunctionDecl>(DR->getDecl());
16496 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
16497 << FD;
16498 SemaRef.Diag(FD->getLocation(), diag::note_declared_at);
16499 }
16500 }
16501
PopExpressionEvaluationContext()16502 void Sema::PopExpressionEvaluationContext() {
16503 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
16504 unsigned NumTypos = Rec.NumTypos;
16505
16506 if (!Rec.Lambdas.empty()) {
16507 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
16508 if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
16509 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
16510 unsigned D;
16511 if (Rec.isUnevaluated()) {
16512 // C++11 [expr.prim.lambda]p2:
16513 // A lambda-expression shall not appear in an unevaluated operand
16514 // (Clause 5).
16515 D = diag::err_lambda_unevaluated_operand;
16516 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
16517 // C++1y [expr.const]p2:
16518 // A conditional-expression e is a core constant expression unless the
16519 // evaluation of e, following the rules of the abstract machine, would
16520 // evaluate [...] a lambda-expression.
16521 D = diag::err_lambda_in_constant_expression;
16522 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
16523 // C++17 [expr.prim.lamda]p2:
16524 // A lambda-expression shall not appear [...] in a template-argument.
16525 D = diag::err_lambda_in_invalid_context;
16526 } else
16527 llvm_unreachable("Couldn't infer lambda error message.");
16528
16529 for (const auto *L : Rec.Lambdas)
16530 Diag(L->getBeginLoc(), D);
16531 }
16532 }
16533
16534 WarnOnPendingNoDerefs(Rec);
16535 HandleImmediateInvocations(*this, Rec);
16536
16537 // Warn on any volatile-qualified simple-assignments that are not discarded-
16538 // value expressions nor unevaluated operands (those cases get removed from
16539 // this list by CheckUnusedVolatileAssignment).
16540 for (auto *BO : Rec.VolatileAssignmentLHSs)
16541 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
16542 << BO->getType();
16543
16544 // When are coming out of an unevaluated context, clear out any
16545 // temporaries that we may have created as part of the evaluation of
16546 // the expression in that context: they aren't relevant because they
16547 // will never be constructed.
16548 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
16549 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
16550 ExprCleanupObjects.end());
16551 Cleanup = Rec.ParentCleanup;
16552 CleanupVarDeclMarking();
16553 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
16554 // Otherwise, merge the contexts together.
16555 } else {
16556 Cleanup.mergeFrom(Rec.ParentCleanup);
16557 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
16558 Rec.SavedMaybeODRUseExprs.end());
16559 }
16560
16561 // Pop the current expression evaluation context off the stack.
16562 ExprEvalContexts.pop_back();
16563
16564 // The global expression evaluation context record is never popped.
16565 ExprEvalContexts.back().NumTypos += NumTypos;
16566 }
16567
DiscardCleanupsInEvaluationContext()16568 void Sema::DiscardCleanupsInEvaluationContext() {
16569 ExprCleanupObjects.erase(
16570 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
16571 ExprCleanupObjects.end());
16572 Cleanup.reset();
16573 MaybeODRUseExprs.clear();
16574 }
16575
HandleExprEvaluationContextForTypeof(Expr * E)16576 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
16577 ExprResult Result = CheckPlaceholderExpr(E);
16578 if (Result.isInvalid())
16579 return ExprError();
16580 E = Result.get();
16581 if (!E->getType()->isVariablyModifiedType())
16582 return E;
16583 return TransformToPotentiallyEvaluated(E);
16584 }
16585
16586 /// Are we in a context that is potentially constant evaluated per C++20
16587 /// [expr.const]p12?
isPotentiallyConstantEvaluatedContext(Sema & SemaRef)16588 static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
16589 /// C++2a [expr.const]p12:
16590 // An expression or conversion is potentially constant evaluated if it is
16591 switch (SemaRef.ExprEvalContexts.back().Context) {
16592 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16593 // -- a manifestly constant-evaluated expression,
16594 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16595 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16596 case Sema::ExpressionEvaluationContext::DiscardedStatement:
16597 // -- a potentially-evaluated expression,
16598 case Sema::ExpressionEvaluationContext::UnevaluatedList:
16599 // -- an immediate subexpression of a braced-init-list,
16600
16601 // -- [FIXME] an expression of the form & cast-expression that occurs
16602 // within a templated entity
16603 // -- a subexpression of one of the above that is not a subexpression of
16604 // a nested unevaluated operand.
16605 return true;
16606
16607 case Sema::ExpressionEvaluationContext::Unevaluated:
16608 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16609 // Expressions in this context are never evaluated.
16610 return false;
16611 }
16612 llvm_unreachable("Invalid context");
16613 }
16614
16615 /// Return true if this function has a calling convention that requires mangling
16616 /// in the size of the parameter pack.
funcHasParameterSizeMangling(Sema & S,FunctionDecl * FD)16617 static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
16618 // These manglings don't do anything on non-Windows or non-x86 platforms, so
16619 // we don't need parameter type sizes.
16620 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
16621 if (!TT.isOSWindows() || !TT.isX86())
16622 return false;
16623
16624 // If this is C++ and this isn't an extern "C" function, parameters do not
16625 // need to be complete. In this case, C++ mangling will apply, which doesn't
16626 // use the size of the parameters.
16627 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
16628 return false;
16629
16630 // Stdcall, fastcall, and vectorcall need this special treatment.
16631 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16632 switch (CC) {
16633 case CC_X86StdCall:
16634 case CC_X86FastCall:
16635 case CC_X86VectorCall:
16636 return true;
16637 default:
16638 break;
16639 }
16640 return false;
16641 }
16642
16643 /// Require that all of the parameter types of function be complete. Normally,
16644 /// parameter types are only required to be complete when a function is called
16645 /// or defined, but to mangle functions with certain calling conventions, the
16646 /// mangler needs to know the size of the parameter list. In this situation,
16647 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
16648 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
16649 /// result in a linker error. Clang doesn't implement this behavior, and instead
16650 /// attempts to error at compile time.
CheckCompleteParameterTypesForMangler(Sema & S,FunctionDecl * FD,SourceLocation Loc)16651 static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
16652 SourceLocation Loc) {
16653 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
16654 FunctionDecl *FD;
16655 ParmVarDecl *Param;
16656
16657 public:
16658 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
16659 : FD(FD), Param(Param) {}
16660
16661 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16662 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
16663 StringRef CCName;
16664 switch (CC) {
16665 case CC_X86StdCall:
16666 CCName = "stdcall";
16667 break;
16668 case CC_X86FastCall:
16669 CCName = "fastcall";
16670 break;
16671 case CC_X86VectorCall:
16672 CCName = "vectorcall";
16673 break;
16674 default:
16675 llvm_unreachable("CC does not need mangling");
16676 }
16677
16678 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
16679 << Param->getDeclName() << FD->getDeclName() << CCName;
16680 }
16681 };
16682
16683 for (ParmVarDecl *Param : FD->parameters()) {
16684 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
16685 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
16686 }
16687 }
16688
16689 namespace {
16690 enum class OdrUseContext {
16691 /// Declarations in this context are not odr-used.
16692 None,
16693 /// Declarations in this context are formally odr-used, but this is a
16694 /// dependent context.
16695 Dependent,
16696 /// Declarations in this context are odr-used but not actually used (yet).
16697 FormallyOdrUsed,
16698 /// Declarations in this context are used.
16699 Used
16700 };
16701 }
16702
16703 /// Are we within a context in which references to resolved functions or to
16704 /// variables result in odr-use?
isOdrUseContext(Sema & SemaRef)16705 static OdrUseContext isOdrUseContext(Sema &SemaRef) {
16706 OdrUseContext Result;
16707
16708 switch (SemaRef.ExprEvalContexts.back().Context) {
16709 case Sema::ExpressionEvaluationContext::Unevaluated:
16710 case Sema::ExpressionEvaluationContext::UnevaluatedList:
16711 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
16712 return OdrUseContext::None;
16713
16714 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
16715 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
16716 Result = OdrUseContext::Used;
16717 break;
16718
16719 case Sema::ExpressionEvaluationContext::DiscardedStatement:
16720 Result = OdrUseContext::FormallyOdrUsed;
16721 break;
16722
16723 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16724 // A default argument formally results in odr-use, but doesn't actually
16725 // result in a use in any real sense until it itself is used.
16726 Result = OdrUseContext::FormallyOdrUsed;
16727 break;
16728 }
16729
16730 if (SemaRef.CurContext->isDependentContext())
16731 return OdrUseContext::Dependent;
16732
16733 return Result;
16734 }
16735
isImplicitlyDefinableConstexprFunction(FunctionDecl * Func)16736 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
16737 if (!Func->isConstexpr())
16738 return false;
16739
16740 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
16741 return true;
16742 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
16743 return CCD && CCD->getInheritedConstructor();
16744 }
16745
16746 /// Mark a function referenced, and check whether it is odr-used
16747 /// (C++ [basic.def.odr]p2, C99 6.9p3)
MarkFunctionReferenced(SourceLocation Loc,FunctionDecl * Func,bool MightBeOdrUse)16748 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
16749 bool MightBeOdrUse) {
16750 assert(Func && "No function?");
16751
16752 Func->setReferenced();
16753
16754 // Recursive functions aren't really used until they're used from some other
16755 // context.
16756 bool IsRecursiveCall = CurContext == Func;
16757
16758 // C++11 [basic.def.odr]p3:
16759 // A function whose name appears as a potentially-evaluated expression is
16760 // odr-used if it is the unique lookup result or the selected member of a
16761 // set of overloaded functions [...].
16762 //
16763 // We (incorrectly) mark overload resolution as an unevaluated context, so we
16764 // can just check that here.
16765 OdrUseContext OdrUse =
16766 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
16767 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
16768 OdrUse = OdrUseContext::FormallyOdrUsed;
16769
16770 // Trivial default constructors and destructors are never actually used.
16771 // FIXME: What about other special members?
16772 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
16773 OdrUse == OdrUseContext::Used) {
16774 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
16775 if (Constructor->isDefaultConstructor())
16776 OdrUse = OdrUseContext::FormallyOdrUsed;
16777 if (isa<CXXDestructorDecl>(Func))
16778 OdrUse = OdrUseContext::FormallyOdrUsed;
16779 }
16780
16781 // C++20 [expr.const]p12:
16782 // A function [...] is needed for constant evaluation if it is [...] a
16783 // constexpr function that is named by an expression that is potentially
16784 // constant evaluated
16785 bool NeededForConstantEvaluation =
16786 isPotentiallyConstantEvaluatedContext(*this) &&
16787 isImplicitlyDefinableConstexprFunction(Func);
16788
16789 // Determine whether we require a function definition to exist, per
16790 // C++11 [temp.inst]p3:
16791 // Unless a function template specialization has been explicitly
16792 // instantiated or explicitly specialized, the function template
16793 // specialization is implicitly instantiated when the specialization is
16794 // referenced in a context that requires a function definition to exist.
16795 // C++20 [temp.inst]p7:
16796 // The existence of a definition of a [...] function is considered to
16797 // affect the semantics of the program if the [...] function is needed for
16798 // constant evaluation by an expression
16799 // C++20 [basic.def.odr]p10:
16800 // Every program shall contain exactly one definition of every non-inline
16801 // function or variable that is odr-used in that program outside of a
16802 // discarded statement
16803 // C++20 [special]p1:
16804 // The implementation will implicitly define [defaulted special members]
16805 // if they are odr-used or needed for constant evaluation.
16806 //
16807 // Note that we skip the implicit instantiation of templates that are only
16808 // used in unused default arguments or by recursive calls to themselves.
16809 // This is formally non-conforming, but seems reasonable in practice.
16810 bool NeedDefinition = !IsRecursiveCall && (OdrUse == OdrUseContext::Used ||
16811 NeededForConstantEvaluation);
16812
16813 // C++14 [temp.expl.spec]p6:
16814 // If a template [...] is explicitly specialized then that specialization
16815 // shall be declared before the first use of that specialization that would
16816 // cause an implicit instantiation to take place, in every translation unit
16817 // in which such a use occurs
16818 if (NeedDefinition &&
16819 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
16820 Func->getMemberSpecializationInfo()))
16821 checkSpecializationVisibility(Loc, Func);
16822
16823 if (getLangOpts().CUDA)
16824 CheckCUDACall(Loc, Func);
16825
16826 if (getLangOpts().SYCLIsDevice)
16827 checkSYCLDeviceFunction(Loc, Func);
16828
16829 // If we need a definition, try to create one.
16830 if (NeedDefinition && !Func->getBody()) {
16831 runWithSufficientStackSpace(Loc, [&] {
16832 if (CXXConstructorDecl *Constructor =
16833 dyn_cast<CXXConstructorDecl>(Func)) {
16834 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
16835 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
16836 if (Constructor->isDefaultConstructor()) {
16837 if (Constructor->isTrivial() &&
16838 !Constructor->hasAttr<DLLExportAttr>())
16839 return;
16840 DefineImplicitDefaultConstructor(Loc, Constructor);
16841 } else if (Constructor->isCopyConstructor()) {
16842 DefineImplicitCopyConstructor(Loc, Constructor);
16843 } else if (Constructor->isMoveConstructor()) {
16844 DefineImplicitMoveConstructor(Loc, Constructor);
16845 }
16846 } else if (Constructor->getInheritedConstructor()) {
16847 DefineInheritingConstructor(Loc, Constructor);
16848 }
16849 } else if (CXXDestructorDecl *Destructor =
16850 dyn_cast<CXXDestructorDecl>(Func)) {
16851 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
16852 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
16853 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
16854 return;
16855 DefineImplicitDestructor(Loc, Destructor);
16856 }
16857 if (Destructor->isVirtual() && getLangOpts().AppleKext)
16858 MarkVTableUsed(Loc, Destructor->getParent());
16859 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
16860 if (MethodDecl->isOverloadedOperator() &&
16861 MethodDecl->getOverloadedOperator() == OO_Equal) {
16862 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
16863 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
16864 if (MethodDecl->isCopyAssignmentOperator())
16865 DefineImplicitCopyAssignment(Loc, MethodDecl);
16866 else if (MethodDecl->isMoveAssignmentOperator())
16867 DefineImplicitMoveAssignment(Loc, MethodDecl);
16868 }
16869 } else if (isa<CXXConversionDecl>(MethodDecl) &&
16870 MethodDecl->getParent()->isLambda()) {
16871 CXXConversionDecl *Conversion =
16872 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
16873 if (Conversion->isLambdaToBlockPointerConversion())
16874 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
16875 else
16876 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
16877 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
16878 MarkVTableUsed(Loc, MethodDecl->getParent());
16879 }
16880
16881 if (Func->isDefaulted() && !Func->isDeleted()) {
16882 DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);
16883 if (DCK != DefaultedComparisonKind::None)
16884 DefineDefaultedComparison(Loc, Func, DCK);
16885 }
16886
16887 // Implicit instantiation of function templates and member functions of
16888 // class templates.
16889 if (Func->isImplicitlyInstantiable()) {
16890 TemplateSpecializationKind TSK =
16891 Func->getTemplateSpecializationKindForInstantiation();
16892 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
16893 bool FirstInstantiation = PointOfInstantiation.isInvalid();
16894 if (FirstInstantiation) {
16895 PointOfInstantiation = Loc;
16896 if (auto *MSI = Func->getMemberSpecializationInfo())
16897 MSI->setPointOfInstantiation(Loc);
16898 // FIXME: Notify listener.
16899 else
16900 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
16901 } else if (TSK != TSK_ImplicitInstantiation) {
16902 // Use the point of use as the point of instantiation, instead of the
16903 // point of explicit instantiation (which we track as the actual point
16904 // of instantiation). This gives better backtraces in diagnostics.
16905 PointOfInstantiation = Loc;
16906 }
16907
16908 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
16909 Func->isConstexpr()) {
16910 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
16911 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
16912 CodeSynthesisContexts.size())
16913 PendingLocalImplicitInstantiations.push_back(
16914 std::make_pair(Func, PointOfInstantiation));
16915 else if (Func->isConstexpr())
16916 // Do not defer instantiations of constexpr functions, to avoid the
16917 // expression evaluator needing to call back into Sema if it sees a
16918 // call to such a function.
16919 InstantiateFunctionDefinition(PointOfInstantiation, Func);
16920 else {
16921 Func->setInstantiationIsPending(true);
16922 PendingInstantiations.push_back(
16923 std::make_pair(Func, PointOfInstantiation));
16924 // Notify the consumer that a function was implicitly instantiated.
16925 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
16926 }
16927 }
16928 } else {
16929 // Walk redefinitions, as some of them may be instantiable.
16930 for (auto i : Func->redecls()) {
16931 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
16932 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
16933 }
16934 }
16935 });
16936 }
16937
16938 // C++14 [except.spec]p17:
16939 // An exception-specification is considered to be needed when:
16940 // - the function is odr-used or, if it appears in an unevaluated operand,
16941 // would be odr-used if the expression were potentially-evaluated;
16942 //
16943 // Note, we do this even if MightBeOdrUse is false. That indicates that the
16944 // function is a pure virtual function we're calling, and in that case the
16945 // function was selected by overload resolution and we need to resolve its
16946 // exception specification for a different reason.
16947 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
16948 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
16949 ResolveExceptionSpec(Loc, FPT);
16950
16951 // If this is the first "real" use, act on that.
16952 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
16953 // Keep track of used but undefined functions.
16954 if (!Func->isDefined()) {
16955 if (mightHaveNonExternalLinkage(Func))
16956 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16957 else if (Func->getMostRecentDecl()->isInlined() &&
16958 !LangOpts.GNUInline &&
16959 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
16960 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16961 else if (isExternalWithNoLinkageType(Func))
16962 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
16963 }
16964
16965 // Some x86 Windows calling conventions mangle the size of the parameter
16966 // pack into the name. Computing the size of the parameters requires the
16967 // parameter types to be complete. Check that now.
16968 if (funcHasParameterSizeMangling(*this, Func))
16969 CheckCompleteParameterTypesForMangler(*this, Func, Loc);
16970
16971 // In the MS C++ ABI, the compiler emits destructor variants where they are
16972 // used. If the destructor is used here but defined elsewhere, mark the
16973 // virtual base destructors referenced. If those virtual base destructors
16974 // are inline, this will ensure they are defined when emitting the complete
16975 // destructor variant. This checking may be redundant if the destructor is
16976 // provided later in this TU.
16977 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
16978 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
16979 CXXRecordDecl *Parent = Dtor->getParent();
16980 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
16981 CheckCompleteDestructorVariant(Loc, Dtor);
16982 }
16983 }
16984
16985 Func->markUsed(Context);
16986 }
16987 }
16988
16989 /// Directly mark a variable odr-used. Given a choice, prefer to use
16990 /// MarkVariableReferenced since it does additional checks and then
16991 /// calls MarkVarDeclODRUsed.
16992 /// If the variable must be captured:
16993 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
16994 /// - else capture it in the DeclContext that maps to the
16995 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
16996 static void
MarkVarDeclODRUsed(VarDecl * Var,SourceLocation Loc,Sema & SemaRef,const unsigned * const FunctionScopeIndexToStopAt=nullptr)16997 MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef,
16998 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
16999 // Keep track of used but undefined variables.
17000 // FIXME: We shouldn't suppress this warning for static data members.
17001 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
17002 (!Var->isExternallyVisible() || Var->isInline() ||
17003 SemaRef.isExternalWithNoLinkageType(Var)) &&
17004 !(Var->isStaticDataMember() && Var->hasInit())) {
17005 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
17006 if (old.isInvalid())
17007 old = Loc;
17008 }
17009 QualType CaptureType, DeclRefType;
17010 if (SemaRef.LangOpts.OpenMP)
17011 SemaRef.tryCaptureOpenMPLambdas(Var);
17012 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
17013 /*EllipsisLoc*/ SourceLocation(),
17014 /*BuildAndDiagnose*/ true,
17015 CaptureType, DeclRefType,
17016 FunctionScopeIndexToStopAt);
17017
17018 Var->markUsed(SemaRef.Context);
17019 }
17020
MarkCaptureUsedInEnclosingContext(VarDecl * Capture,SourceLocation Loc,unsigned CapturingScopeIndex)17021 void Sema::MarkCaptureUsedInEnclosingContext(VarDecl *Capture,
17022 SourceLocation Loc,
17023 unsigned CapturingScopeIndex) {
17024 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
17025 }
17026
17027 static void
diagnoseUncapturableValueReference(Sema & S,SourceLocation loc,ValueDecl * var,DeclContext * DC)17028 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
17029 ValueDecl *var, DeclContext *DC) {
17030 DeclContext *VarDC = var->getDeclContext();
17031
17032 // If the parameter still belongs to the translation unit, then
17033 // we're actually just using one parameter in the declaration of
17034 // the next.
17035 if (isa<ParmVarDecl>(var) &&
17036 isa<TranslationUnitDecl>(VarDC))
17037 return;
17038
17039 // For C code, don't diagnose about capture if we're not actually in code
17040 // right now; it's impossible to write a non-constant expression outside of
17041 // function context, so we'll get other (more useful) diagnostics later.
17042 //
17043 // For C++, things get a bit more nasty... it would be nice to suppress this
17044 // diagnostic for certain cases like using a local variable in an array bound
17045 // for a member of a local class, but the correct predicate is not obvious.
17046 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
17047 return;
17048
17049 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
17050 unsigned ContextKind = 3; // unknown
17051 if (isa<CXXMethodDecl>(VarDC) &&
17052 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
17053 ContextKind = 2;
17054 } else if (isa<FunctionDecl>(VarDC)) {
17055 ContextKind = 0;
17056 } else if (isa<BlockDecl>(VarDC)) {
17057 ContextKind = 1;
17058 }
17059
17060 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
17061 << var << ValueKind << ContextKind << VarDC;
17062 S.Diag(var->getLocation(), diag::note_entity_declared_at)
17063 << var;
17064
17065 // FIXME: Add additional diagnostic info about class etc. which prevents
17066 // capture.
17067 }
17068
17069
isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo * CSI,VarDecl * Var,bool & SubCapturesAreNested,QualType & CaptureType,QualType & DeclRefType)17070 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
17071 bool &SubCapturesAreNested,
17072 QualType &CaptureType,
17073 QualType &DeclRefType) {
17074 // Check whether we've already captured it.
17075 if (CSI->CaptureMap.count(Var)) {
17076 // If we found a capture, any subcaptures are nested.
17077 SubCapturesAreNested = true;
17078
17079 // Retrieve the capture type for this variable.
17080 CaptureType = CSI->getCapture(Var).getCaptureType();
17081
17082 // Compute the type of an expression that refers to this variable.
17083 DeclRefType = CaptureType.getNonReferenceType();
17084
17085 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
17086 // are mutable in the sense that user can change their value - they are
17087 // private instances of the captured declarations.
17088 const Capture &Cap = CSI->getCapture(Var);
17089 if (Cap.isCopyCapture() &&
17090 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
17091 !(isa<CapturedRegionScopeInfo>(CSI) &&
17092 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
17093 DeclRefType.addConst();
17094 return true;
17095 }
17096 return false;
17097 }
17098
17099 // Only block literals, captured statements, and lambda expressions can
17100 // capture; other scopes don't work.
getParentOfCapturingContextOrNull(DeclContext * DC,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)17101 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
17102 SourceLocation Loc,
17103 const bool Diagnose, Sema &S) {
17104 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
17105 return getLambdaAwareParentOfDeclContext(DC);
17106 else if (Var->hasLocalStorage()) {
17107 if (Diagnose)
17108 diagnoseUncapturableValueReference(S, Loc, Var, DC);
17109 }
17110 return nullptr;
17111 }
17112
17113 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17114 // certain types of variables (unnamed, variably modified types etc.)
17115 // so check for eligibility.
isVariableCapturable(CapturingScopeInfo * CSI,VarDecl * Var,SourceLocation Loc,const bool Diagnose,Sema & S)17116 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
17117 SourceLocation Loc,
17118 const bool Diagnose, Sema &S) {
17119
17120 bool IsBlock = isa<BlockScopeInfo>(CSI);
17121 bool IsLambda = isa<LambdaScopeInfo>(CSI);
17122
17123 // Lambdas are not allowed to capture unnamed variables
17124 // (e.g. anonymous unions).
17125 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
17126 // assuming that's the intent.
17127 if (IsLambda && !Var->getDeclName()) {
17128 if (Diagnose) {
17129 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
17130 S.Diag(Var->getLocation(), diag::note_declared_at);
17131 }
17132 return false;
17133 }
17134
17135 // Prohibit variably-modified types in blocks; they're difficult to deal with.
17136 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
17137 if (Diagnose) {
17138 S.Diag(Loc, diag::err_ref_vm_type);
17139 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17140 }
17141 return false;
17142 }
17143 // Prohibit structs with flexible array members too.
17144 // We cannot capture what is in the tail end of the struct.
17145 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
17146 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
17147 if (Diagnose) {
17148 if (IsBlock)
17149 S.Diag(Loc, diag::err_ref_flexarray_type);
17150 else
17151 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
17152 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17153 }
17154 return false;
17155 }
17156 }
17157 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17158 // Lambdas and captured statements are not allowed to capture __block
17159 // variables; they don't support the expected semantics.
17160 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
17161 if (Diagnose) {
17162 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
17163 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17164 }
17165 return false;
17166 }
17167 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
17168 if (S.getLangOpts().OpenCL && IsBlock &&
17169 Var->getType()->isBlockPointerType()) {
17170 if (Diagnose)
17171 S.Diag(Loc, diag::err_opencl_block_ref_block);
17172 return false;
17173 }
17174
17175 return true;
17176 }
17177
17178 // 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)17179 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
17180 SourceLocation Loc,
17181 const bool BuildAndDiagnose,
17182 QualType &CaptureType,
17183 QualType &DeclRefType,
17184 const bool Nested,
17185 Sema &S, bool Invalid) {
17186 bool ByRef = false;
17187
17188 // Blocks are not allowed to capture arrays, excepting OpenCL.
17189 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
17190 // (decayed to pointers).
17191 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
17192 if (BuildAndDiagnose) {
17193 S.Diag(Loc, diag::err_ref_array_type);
17194 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17195 Invalid = true;
17196 } else {
17197 return false;
17198 }
17199 }
17200
17201 // Forbid the block-capture of autoreleasing variables.
17202 if (!Invalid &&
17203 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17204 if (BuildAndDiagnose) {
17205 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
17206 << /*block*/ 0;
17207 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17208 Invalid = true;
17209 } else {
17210 return false;
17211 }
17212 }
17213
17214 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
17215 if (const auto *PT = CaptureType->getAs<PointerType>()) {
17216 QualType PointeeTy = PT->getPointeeType();
17217
17218 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
17219 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
17220 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
17221 if (BuildAndDiagnose) {
17222 SourceLocation VarLoc = Var->getLocation();
17223 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
17224 S.Diag(VarLoc, diag::note_declare_parameter_strong);
17225 }
17226 }
17227 }
17228
17229 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
17230 if (HasBlocksAttr || CaptureType->isReferenceType() ||
17231 (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
17232 // Block capture by reference does not change the capture or
17233 // declaration reference types.
17234 ByRef = true;
17235 } else {
17236 // Block capture by copy introduces 'const'.
17237 CaptureType = CaptureType.getNonReferenceType().withConst();
17238 DeclRefType = CaptureType;
17239 }
17240
17241 // Actually capture the variable.
17242 if (BuildAndDiagnose)
17243 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
17244 CaptureType, Invalid);
17245
17246 return !Invalid;
17247 }
17248
17249
17250 /// 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 & S,bool Invalid)17251 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
17252 VarDecl *Var,
17253 SourceLocation Loc,
17254 const bool BuildAndDiagnose,
17255 QualType &CaptureType,
17256 QualType &DeclRefType,
17257 const bool RefersToCapturedVariable,
17258 Sema &S, bool Invalid) {
17259 // By default, capture variables by reference.
17260 bool ByRef = true;
17261 // Using an LValue reference type is consistent with Lambdas (see below).
17262 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
17263 if (S.isOpenMPCapturedDecl(Var)) {
17264 bool HasConst = DeclRefType.isConstQualified();
17265 DeclRefType = DeclRefType.getUnqualifiedType();
17266 // Don't lose diagnostics about assignments to const.
17267 if (HasConst)
17268 DeclRefType.addConst();
17269 }
17270 // Do not capture firstprivates in tasks.
17271 if (S.isOpenMPPrivateDecl(Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel) !=
17272 OMPC_unknown)
17273 return true;
17274 ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
17275 RSI->OpenMPCaptureLevel);
17276 }
17277
17278 if (ByRef)
17279 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17280 else
17281 CaptureType = DeclRefType;
17282
17283 // Actually capture the variable.
17284 if (BuildAndDiagnose)
17285 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
17286 Loc, SourceLocation(), CaptureType, Invalid);
17287
17288 return !Invalid;
17289 }
17290
17291 /// 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)17292 static bool captureInLambda(LambdaScopeInfo *LSI,
17293 VarDecl *Var,
17294 SourceLocation Loc,
17295 const bool BuildAndDiagnose,
17296 QualType &CaptureType,
17297 QualType &DeclRefType,
17298 const bool RefersToCapturedVariable,
17299 const Sema::TryCaptureKind Kind,
17300 SourceLocation EllipsisLoc,
17301 const bool IsTopScope,
17302 Sema &S, bool Invalid) {
17303 // Determine whether we are capturing by reference or by value.
17304 bool ByRef = false;
17305 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
17306 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
17307 } else {
17308 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
17309 }
17310
17311 // Compute the type of the field that will capture this variable.
17312 if (ByRef) {
17313 // C++11 [expr.prim.lambda]p15:
17314 // An entity is captured by reference if it is implicitly or
17315 // explicitly captured but not captured by copy. It is
17316 // unspecified whether additional unnamed non-static data
17317 // members are declared in the closure type for entities
17318 // captured by reference.
17319 //
17320 // FIXME: It is not clear whether we want to build an lvalue reference
17321 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
17322 // to do the former, while EDG does the latter. Core issue 1249 will
17323 // clarify, but for now we follow GCC because it's a more permissive and
17324 // easily defensible position.
17325 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
17326 } else {
17327 // C++11 [expr.prim.lambda]p14:
17328 // For each entity captured by copy, an unnamed non-static
17329 // data member is declared in the closure type. The
17330 // declaration order of these members is unspecified. The type
17331 // of such a data member is the type of the corresponding
17332 // captured entity if the entity is not a reference to an
17333 // object, or the referenced type otherwise. [Note: If the
17334 // captured entity is a reference to a function, the
17335 // corresponding data member is also a reference to a
17336 // function. - end note ]
17337 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
17338 if (!RefType->getPointeeType()->isFunctionType())
17339 CaptureType = RefType->getPointeeType();
17340 }
17341
17342 // Forbid the lambda copy-capture of autoreleasing variables.
17343 if (!Invalid &&
17344 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
17345 if (BuildAndDiagnose) {
17346 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
17347 S.Diag(Var->getLocation(), diag::note_previous_decl)
17348 << Var->getDeclName();
17349 Invalid = true;
17350 } else {
17351 return false;
17352 }
17353 }
17354
17355 // Make sure that by-copy captures are of a complete and non-abstract type.
17356 if (!Invalid && BuildAndDiagnose) {
17357 if (!CaptureType->isDependentType() &&
17358 S.RequireCompleteSizedType(
17359 Loc, CaptureType,
17360 diag::err_capture_of_incomplete_or_sizeless_type,
17361 Var->getDeclName()))
17362 Invalid = true;
17363 else if (S.RequireNonAbstractType(Loc, CaptureType,
17364 diag::err_capture_of_abstract_type))
17365 Invalid = true;
17366 }
17367 }
17368
17369 // Compute the type of a reference to this captured variable.
17370 if (ByRef)
17371 DeclRefType = CaptureType.getNonReferenceType();
17372 else {
17373 // C++ [expr.prim.lambda]p5:
17374 // The closure type for a lambda-expression has a public inline
17375 // function call operator [...]. This function call operator is
17376 // declared const (9.3.1) if and only if the lambda-expression's
17377 // parameter-declaration-clause is not followed by mutable.
17378 DeclRefType = CaptureType.getNonReferenceType();
17379 if (!LSI->Mutable && !CaptureType->isReferenceType())
17380 DeclRefType.addConst();
17381 }
17382
17383 // Add the capture.
17384 if (BuildAndDiagnose)
17385 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
17386 Loc, EllipsisLoc, CaptureType, Invalid);
17387
17388 return !Invalid;
17389 }
17390
tryCaptureVariable(VarDecl * Var,SourceLocation ExprLoc,TryCaptureKind Kind,SourceLocation EllipsisLoc,bool BuildAndDiagnose,QualType & CaptureType,QualType & DeclRefType,const unsigned * const FunctionScopeIndexToStopAt)17391 bool Sema::tryCaptureVariable(
17392 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
17393 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
17394 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
17395 // An init-capture is notionally from the context surrounding its
17396 // declaration, but its parent DC is the lambda class.
17397 DeclContext *VarDC = Var->getDeclContext();
17398 if (Var->isInitCapture())
17399 VarDC = VarDC->getParent();
17400
17401 DeclContext *DC = CurContext;
17402 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
17403 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
17404 // We need to sync up the Declaration Context with the
17405 // FunctionScopeIndexToStopAt
17406 if (FunctionScopeIndexToStopAt) {
17407 unsigned FSIndex = FunctionScopes.size() - 1;
17408 while (FSIndex != MaxFunctionScopesIndex) {
17409 DC = getLambdaAwareParentOfDeclContext(DC);
17410 --FSIndex;
17411 }
17412 }
17413
17414
17415 // If the variable is declared in the current context, there is no need to
17416 // capture it.
17417 if (VarDC == DC) return true;
17418
17419 // Capture global variables if it is required to use private copy of this
17420 // variable.
17421 bool IsGlobal = !Var->hasLocalStorage();
17422 if (IsGlobal &&
17423 !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
17424 MaxFunctionScopesIndex)))
17425 return true;
17426 Var = Var->getCanonicalDecl();
17427
17428 // Walk up the stack to determine whether we can capture the variable,
17429 // performing the "simple" checks that don't depend on type. We stop when
17430 // we've either hit the declared scope of the variable or find an existing
17431 // capture of that variable. We start from the innermost capturing-entity
17432 // (the DC) and ensure that all intervening capturing-entities
17433 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
17434 // declcontext can either capture the variable or have already captured
17435 // the variable.
17436 CaptureType = Var->getType();
17437 DeclRefType = CaptureType.getNonReferenceType();
17438 bool Nested = false;
17439 bool Explicit = (Kind != TryCapture_Implicit);
17440 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
17441 do {
17442 // Only block literals, captured statements, and lambda expressions can
17443 // capture; other scopes don't work.
17444 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
17445 ExprLoc,
17446 BuildAndDiagnose,
17447 *this);
17448 // We need to check for the parent *first* because, if we *have*
17449 // private-captured a global variable, we need to recursively capture it in
17450 // intermediate blocks, lambdas, etc.
17451 if (!ParentDC) {
17452 if (IsGlobal) {
17453 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
17454 break;
17455 }
17456 return true;
17457 }
17458
17459 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
17460 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
17461
17462
17463 // Check whether we've already captured it.
17464 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
17465 DeclRefType)) {
17466 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
17467 break;
17468 }
17469 // If we are instantiating a generic lambda call operator body,
17470 // we do not want to capture new variables. What was captured
17471 // during either a lambdas transformation or initial parsing
17472 // should be used.
17473 if (isGenericLambdaCallOperatorSpecialization(DC)) {
17474 if (BuildAndDiagnose) {
17475 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17476 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
17477 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17478 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17479 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
17480 } else
17481 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
17482 }
17483 return true;
17484 }
17485
17486 // Try to capture variable-length arrays types.
17487 if (Var->getType()->isVariablyModifiedType()) {
17488 // We're going to walk down into the type and look for VLA
17489 // expressions.
17490 QualType QTy = Var->getType();
17491 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17492 QTy = PVD->getOriginalType();
17493 captureVariablyModifiedType(Context, QTy, CSI);
17494 }
17495
17496 if (getLangOpts().OpenMP) {
17497 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17498 // OpenMP private variables should not be captured in outer scope, so
17499 // just break here. Similarly, global variables that are captured in a
17500 // target region should not be captured outside the scope of the region.
17501 if (RSI->CapRegionKind == CR_OpenMP) {
17502 OpenMPClauseKind IsOpenMPPrivateDecl = isOpenMPPrivateDecl(
17503 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
17504 // If the variable is private (i.e. not captured) and has variably
17505 // modified type, we still need to capture the type for correct
17506 // codegen in all regions, associated with the construct. Currently,
17507 // it is captured in the innermost captured region only.
17508 if (IsOpenMPPrivateDecl != OMPC_unknown &&
17509 Var->getType()->isVariablyModifiedType()) {
17510 QualType QTy = Var->getType();
17511 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
17512 QTy = PVD->getOriginalType();
17513 for (int I = 1, E = getNumberOfConstructScopes(RSI->OpenMPLevel);
17514 I < E; ++I) {
17515 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
17516 FunctionScopes[FunctionScopesIndex - I]);
17517 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
17518 "Wrong number of captured regions associated with the "
17519 "OpenMP construct.");
17520 captureVariablyModifiedType(Context, QTy, OuterRSI);
17521 }
17522 }
17523 bool IsTargetCap =
17524 IsOpenMPPrivateDecl != OMPC_private &&
17525 isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
17526 RSI->OpenMPCaptureLevel);
17527 // Do not capture global if it is not privatized in outer regions.
17528 bool IsGlobalCap =
17529 IsGlobal && isOpenMPGlobalCapturedDecl(Var, RSI->OpenMPLevel,
17530 RSI->OpenMPCaptureLevel);
17531
17532 // When we detect target captures we are looking from inside the
17533 // target region, therefore we need to propagate the capture from the
17534 // enclosing region. Therefore, the capture is not initially nested.
17535 if (IsTargetCap)
17536 adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
17537
17538 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
17539 (IsGlobal && !IsGlobalCap)) {
17540 Nested = !IsTargetCap;
17541 bool HasConst = DeclRefType.isConstQualified();
17542 DeclRefType = DeclRefType.getUnqualifiedType();
17543 // Don't lose diagnostics about assignments to const.
17544 if (HasConst)
17545 DeclRefType.addConst();
17546 CaptureType = Context.getLValueReferenceType(DeclRefType);
17547 break;
17548 }
17549 }
17550 }
17551 }
17552 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
17553 // No capture-default, and this is not an explicit capture
17554 // so cannot capture this variable.
17555 if (BuildAndDiagnose) {
17556 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
17557 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
17558 if (cast<LambdaScopeInfo>(CSI)->Lambda)
17559 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
17560 diag::note_lambda_decl);
17561 // FIXME: If we error out because an outer lambda can not implicitly
17562 // capture a variable that an inner lambda explicitly captures, we
17563 // should have the inner lambda do the explicit capture - because
17564 // it makes for cleaner diagnostics later. This would purely be done
17565 // so that the diagnostic does not misleadingly claim that a variable
17566 // can not be captured by a lambda implicitly even though it is captured
17567 // explicitly. Suggestion:
17568 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
17569 // at the function head
17570 // - cache the StartingDeclContext - this must be a lambda
17571 // - captureInLambda in the innermost lambda the variable.
17572 }
17573 return true;
17574 }
17575
17576 FunctionScopesIndex--;
17577 DC = ParentDC;
17578 Explicit = false;
17579 } while (!VarDC->Equals(DC));
17580
17581 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
17582 // computing the type of the capture at each step, checking type-specific
17583 // requirements, and adding captures if requested.
17584 // If the variable had already been captured previously, we start capturing
17585 // at the lambda nested within that one.
17586 bool Invalid = false;
17587 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
17588 ++I) {
17589 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
17590
17591 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
17592 // certain types of variables (unnamed, variably modified types etc.)
17593 // so check for eligibility.
17594 if (!Invalid)
17595 Invalid =
17596 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
17597
17598 // After encountering an error, if we're actually supposed to capture, keep
17599 // capturing in nested contexts to suppress any follow-on diagnostics.
17600 if (Invalid && !BuildAndDiagnose)
17601 return true;
17602
17603 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
17604 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17605 DeclRefType, Nested, *this, Invalid);
17606 Nested = true;
17607 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
17608 Invalid = !captureInCapturedRegion(RSI, Var, ExprLoc, BuildAndDiagnose,
17609 CaptureType, DeclRefType, Nested,
17610 *this, Invalid);
17611 Nested = true;
17612 } else {
17613 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
17614 Invalid =
17615 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
17616 DeclRefType, Nested, Kind, EllipsisLoc,
17617 /*IsTopScope*/ I == N - 1, *this, Invalid);
17618 Nested = true;
17619 }
17620
17621 if (Invalid && !BuildAndDiagnose)
17622 return true;
17623 }
17624 return Invalid;
17625 }
17626
tryCaptureVariable(VarDecl * Var,SourceLocation Loc,TryCaptureKind Kind,SourceLocation EllipsisLoc)17627 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
17628 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
17629 QualType CaptureType;
17630 QualType DeclRefType;
17631 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
17632 /*BuildAndDiagnose=*/true, CaptureType,
17633 DeclRefType, nullptr);
17634 }
17635
NeedToCaptureVariable(VarDecl * Var,SourceLocation Loc)17636 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
17637 QualType CaptureType;
17638 QualType DeclRefType;
17639 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17640 /*BuildAndDiagnose=*/false, CaptureType,
17641 DeclRefType, nullptr);
17642 }
17643
getCapturedDeclRefType(VarDecl * Var,SourceLocation Loc)17644 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
17645 QualType CaptureType;
17646 QualType DeclRefType;
17647
17648 // Determine whether we can capture this variable.
17649 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
17650 /*BuildAndDiagnose=*/false, CaptureType,
17651 DeclRefType, nullptr))
17652 return QualType();
17653
17654 return DeclRefType;
17655 }
17656
17657 namespace {
17658 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
17659 // The produced TemplateArgumentListInfo* points to data stored within this
17660 // object, so should only be used in contexts where the pointer will not be
17661 // used after the CopiedTemplateArgs object is destroyed.
17662 class CopiedTemplateArgs {
17663 bool HasArgs;
17664 TemplateArgumentListInfo TemplateArgStorage;
17665 public:
17666 template<typename RefExpr>
CopiedTemplateArgs(RefExpr * E)17667 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
17668 if (HasArgs)
17669 E->copyTemplateArgumentsInto(TemplateArgStorage);
17670 }
operator TemplateArgumentListInfo*()17671 operator TemplateArgumentListInfo*()
17672 #ifdef __has_cpp_attribute
17673 #if __has_cpp_attribute(clang::lifetimebound)
17674 [[clang::lifetimebound]]
17675 #endif
17676 #endif
17677 {
17678 return HasArgs ? &TemplateArgStorage : nullptr;
17679 }
17680 };
17681 }
17682
17683 /// Walk the set of potential results of an expression and mark them all as
17684 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
17685 ///
17686 /// \return A new expression if we found any potential results, ExprEmpty() if
17687 /// not, and ExprError() if we diagnosed an error.
rebuildPotentialResultsAsNonOdrUsed(Sema & S,Expr * E,NonOdrUseReason NOUR)17688 static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
17689 NonOdrUseReason NOUR) {
17690 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
17691 // an object that satisfies the requirements for appearing in a
17692 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
17693 // is immediately applied." This function handles the lvalue-to-rvalue
17694 // conversion part.
17695 //
17696 // If we encounter a node that claims to be an odr-use but shouldn't be, we
17697 // transform it into the relevant kind of non-odr-use node and rebuild the
17698 // tree of nodes leading to it.
17699 //
17700 // This is a mini-TreeTransform that only transforms a restricted subset of
17701 // nodes (and only certain operands of them).
17702
17703 // Rebuild a subexpression.
17704 auto Rebuild = [&](Expr *Sub) {
17705 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
17706 };
17707
17708 // Check whether a potential result satisfies the requirements of NOUR.
17709 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
17710 // Any entity other than a VarDecl is always odr-used whenever it's named
17711 // in a potentially-evaluated expression.
17712 auto *VD = dyn_cast<VarDecl>(D);
17713 if (!VD)
17714 return true;
17715
17716 // C++2a [basic.def.odr]p4:
17717 // A variable x whose name appears as a potentially-evalauted expression
17718 // e is odr-used by e unless
17719 // -- x is a reference that is usable in constant expressions, or
17720 // -- x is a variable of non-reference type that is usable in constant
17721 // expressions and has no mutable subobjects, and e is an element of
17722 // the set of potential results of an expression of
17723 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
17724 // conversion is applied, or
17725 // -- x is a variable of non-reference type, and e is an element of the
17726 // set of potential results of a discarded-value expression to which
17727 // the lvalue-to-rvalue conversion is not applied
17728 //
17729 // We check the first bullet and the "potentially-evaluated" condition in
17730 // BuildDeclRefExpr. We check the type requirements in the second bullet
17731 // in CheckLValueToRValueConversionOperand below.
17732 switch (NOUR) {
17733 case NOUR_None:
17734 case NOUR_Unevaluated:
17735 llvm_unreachable("unexpected non-odr-use-reason");
17736
17737 case NOUR_Constant:
17738 // Constant references were handled when they were built.
17739 if (VD->getType()->isReferenceType())
17740 return true;
17741 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
17742 if (RD->hasMutableFields())
17743 return true;
17744 if (!VD->isUsableInConstantExpressions(S.Context))
17745 return true;
17746 break;
17747
17748 case NOUR_Discarded:
17749 if (VD->getType()->isReferenceType())
17750 return true;
17751 break;
17752 }
17753 return false;
17754 };
17755
17756 // Mark that this expression does not constitute an odr-use.
17757 auto MarkNotOdrUsed = [&] {
17758 S.MaybeODRUseExprs.remove(E);
17759 if (LambdaScopeInfo *LSI = S.getCurLambda())
17760 LSI->markVariableExprAsNonODRUsed(E);
17761 };
17762
17763 // C++2a [basic.def.odr]p2:
17764 // The set of potential results of an expression e is defined as follows:
17765 switch (E->getStmtClass()) {
17766 // -- If e is an id-expression, ...
17767 case Expr::DeclRefExprClass: {
17768 auto *DRE = cast<DeclRefExpr>(E);
17769 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
17770 break;
17771
17772 // Rebuild as a non-odr-use DeclRefExpr.
17773 MarkNotOdrUsed();
17774 return DeclRefExpr::Create(
17775 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
17776 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
17777 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
17778 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
17779 }
17780
17781 case Expr::FunctionParmPackExprClass: {
17782 auto *FPPE = cast<FunctionParmPackExpr>(E);
17783 // If any of the declarations in the pack is odr-used, then the expression
17784 // as a whole constitutes an odr-use.
17785 for (VarDecl *D : *FPPE)
17786 if (IsPotentialResultOdrUsed(D))
17787 return ExprEmpty();
17788
17789 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
17790 // nothing cares about whether we marked this as an odr-use, but it might
17791 // be useful for non-compiler tools.
17792 MarkNotOdrUsed();
17793 break;
17794 }
17795
17796 // -- If e is a subscripting operation with an array operand...
17797 case Expr::ArraySubscriptExprClass: {
17798 auto *ASE = cast<ArraySubscriptExpr>(E);
17799 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
17800 if (!OldBase->getType()->isArrayType())
17801 break;
17802 ExprResult Base = Rebuild(OldBase);
17803 if (!Base.isUsable())
17804 return Base;
17805 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
17806 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
17807 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
17808 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
17809 ASE->getRBracketLoc());
17810 }
17811
17812 case Expr::MemberExprClass: {
17813 auto *ME = cast<MemberExpr>(E);
17814 // -- If e is a class member access expression [...] naming a non-static
17815 // data member...
17816 if (isa<FieldDecl>(ME->getMemberDecl())) {
17817 ExprResult Base = Rebuild(ME->getBase());
17818 if (!Base.isUsable())
17819 return Base;
17820 return MemberExpr::Create(
17821 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
17822 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
17823 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
17824 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
17825 ME->getObjectKind(), ME->isNonOdrUse());
17826 }
17827
17828 if (ME->getMemberDecl()->isCXXInstanceMember())
17829 break;
17830
17831 // -- If e is a class member access expression naming a static data member,
17832 // ...
17833 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
17834 break;
17835
17836 // Rebuild as a non-odr-use MemberExpr.
17837 MarkNotOdrUsed();
17838 return MemberExpr::Create(
17839 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
17840 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
17841 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
17842 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
17843 return ExprEmpty();
17844 }
17845
17846 case Expr::BinaryOperatorClass: {
17847 auto *BO = cast<BinaryOperator>(E);
17848 Expr *LHS = BO->getLHS();
17849 Expr *RHS = BO->getRHS();
17850 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
17851 if (BO->getOpcode() == BO_PtrMemD) {
17852 ExprResult Sub = Rebuild(LHS);
17853 if (!Sub.isUsable())
17854 return Sub;
17855 LHS = Sub.get();
17856 // -- If e is a comma expression, ...
17857 } else if (BO->getOpcode() == BO_Comma) {
17858 ExprResult Sub = Rebuild(RHS);
17859 if (!Sub.isUsable())
17860 return Sub;
17861 RHS = Sub.get();
17862 } else {
17863 break;
17864 }
17865 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
17866 LHS, RHS);
17867 }
17868
17869 // -- If e has the form (e1)...
17870 case Expr::ParenExprClass: {
17871 auto *PE = cast<ParenExpr>(E);
17872 ExprResult Sub = Rebuild(PE->getSubExpr());
17873 if (!Sub.isUsable())
17874 return Sub;
17875 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
17876 }
17877
17878 // -- If e is a glvalue conditional expression, ...
17879 // We don't apply this to a binary conditional operator. FIXME: Should we?
17880 case Expr::ConditionalOperatorClass: {
17881 auto *CO = cast<ConditionalOperator>(E);
17882 ExprResult LHS = Rebuild(CO->getLHS());
17883 if (LHS.isInvalid())
17884 return ExprError();
17885 ExprResult RHS = Rebuild(CO->getRHS());
17886 if (RHS.isInvalid())
17887 return ExprError();
17888 if (!LHS.isUsable() && !RHS.isUsable())
17889 return ExprEmpty();
17890 if (!LHS.isUsable())
17891 LHS = CO->getLHS();
17892 if (!RHS.isUsable())
17893 RHS = CO->getRHS();
17894 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
17895 CO->getCond(), LHS.get(), RHS.get());
17896 }
17897
17898 // [Clang extension]
17899 // -- If e has the form __extension__ e1...
17900 case Expr::UnaryOperatorClass: {
17901 auto *UO = cast<UnaryOperator>(E);
17902 if (UO->getOpcode() != UO_Extension)
17903 break;
17904 ExprResult Sub = Rebuild(UO->getSubExpr());
17905 if (!Sub.isUsable())
17906 return Sub;
17907 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
17908 Sub.get());
17909 }
17910
17911 // [Clang extension]
17912 // -- If e has the form _Generic(...), the set of potential results is the
17913 // union of the sets of potential results of the associated expressions.
17914 case Expr::GenericSelectionExprClass: {
17915 auto *GSE = cast<GenericSelectionExpr>(E);
17916
17917 SmallVector<Expr *, 4> AssocExprs;
17918 bool AnyChanged = false;
17919 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
17920 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
17921 if (AssocExpr.isInvalid())
17922 return ExprError();
17923 if (AssocExpr.isUsable()) {
17924 AssocExprs.push_back(AssocExpr.get());
17925 AnyChanged = true;
17926 } else {
17927 AssocExprs.push_back(OrigAssocExpr);
17928 }
17929 }
17930
17931 return AnyChanged ? S.CreateGenericSelectionExpr(
17932 GSE->getGenericLoc(), GSE->getDefaultLoc(),
17933 GSE->getRParenLoc(), GSE->getControllingExpr(),
17934 GSE->getAssocTypeSourceInfos(), AssocExprs)
17935 : ExprEmpty();
17936 }
17937
17938 // [Clang extension]
17939 // -- If e has the form __builtin_choose_expr(...), the set of potential
17940 // results is the union of the sets of potential results of the
17941 // second and third subexpressions.
17942 case Expr::ChooseExprClass: {
17943 auto *CE = cast<ChooseExpr>(E);
17944
17945 ExprResult LHS = Rebuild(CE->getLHS());
17946 if (LHS.isInvalid())
17947 return ExprError();
17948
17949 ExprResult RHS = Rebuild(CE->getLHS());
17950 if (RHS.isInvalid())
17951 return ExprError();
17952
17953 if (!LHS.get() && !RHS.get())
17954 return ExprEmpty();
17955 if (!LHS.isUsable())
17956 LHS = CE->getLHS();
17957 if (!RHS.isUsable())
17958 RHS = CE->getRHS();
17959
17960 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
17961 RHS.get(), CE->getRParenLoc());
17962 }
17963
17964 // Step through non-syntactic nodes.
17965 case Expr::ConstantExprClass: {
17966 auto *CE = cast<ConstantExpr>(E);
17967 ExprResult Sub = Rebuild(CE->getSubExpr());
17968 if (!Sub.isUsable())
17969 return Sub;
17970 return ConstantExpr::Create(S.Context, Sub.get());
17971 }
17972
17973 // We could mostly rely on the recursive rebuilding to rebuild implicit
17974 // casts, but not at the top level, so rebuild them here.
17975 case Expr::ImplicitCastExprClass: {
17976 auto *ICE = cast<ImplicitCastExpr>(E);
17977 // Only step through the narrow set of cast kinds we expect to encounter.
17978 // Anything else suggests we've left the region in which potential results
17979 // can be found.
17980 switch (ICE->getCastKind()) {
17981 case CK_NoOp:
17982 case CK_DerivedToBase:
17983 case CK_UncheckedDerivedToBase: {
17984 ExprResult Sub = Rebuild(ICE->getSubExpr());
17985 if (!Sub.isUsable())
17986 return Sub;
17987 CXXCastPath Path(ICE->path());
17988 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
17989 ICE->getValueKind(), &Path);
17990 }
17991
17992 default:
17993 break;
17994 }
17995 break;
17996 }
17997
17998 default:
17999 break;
18000 }
18001
18002 // Can't traverse through this node. Nothing to do.
18003 return ExprEmpty();
18004 }
18005
CheckLValueToRValueConversionOperand(Expr * E)18006 ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
18007 // Check whether the operand is or contains an object of non-trivial C union
18008 // type.
18009 if (E->getType().isVolatileQualified() &&
18010 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
18011 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
18012 checkNonTrivialCUnion(E->getType(), E->getExprLoc(),
18013 Sema::NTCUC_LValueToRValueVolatile,
18014 NTCUK_Destruct|NTCUK_Copy);
18015
18016 // C++2a [basic.def.odr]p4:
18017 // [...] an expression of non-volatile-qualified non-class type to which
18018 // the lvalue-to-rvalue conversion is applied [...]
18019 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
18020 return E;
18021
18022 ExprResult Result =
18023 rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);
18024 if (Result.isInvalid())
18025 return ExprError();
18026 return Result.get() ? Result : E;
18027 }
18028
ActOnConstantExpression(ExprResult Res)18029 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
18030 Res = CorrectDelayedTyposInExpr(Res);
18031
18032 if (!Res.isUsable())
18033 return Res;
18034
18035 // If a constant-expression is a reference to a variable where we delay
18036 // deciding whether it is an odr-use, just assume we will apply the
18037 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
18038 // (a non-type template argument), we have special handling anyway.
18039 return CheckLValueToRValueConversionOperand(Res.get());
18040 }
18041
CleanupVarDeclMarking()18042 void Sema::CleanupVarDeclMarking() {
18043 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
18044 // call.
18045 MaybeODRUseExprSet LocalMaybeODRUseExprs;
18046 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
18047
18048 for (Expr *E : LocalMaybeODRUseExprs) {
18049 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
18050 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
18051 DRE->getLocation(), *this);
18052 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
18053 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
18054 *this);
18055 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
18056 for (VarDecl *VD : *FP)
18057 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
18058 } else {
18059 llvm_unreachable("Unexpected expression");
18060 }
18061 }
18062
18063 assert(MaybeODRUseExprs.empty() &&
18064 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
18065 }
18066
DoMarkVarDeclReferenced(Sema & SemaRef,SourceLocation Loc,VarDecl * Var,Expr * E)18067 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
18068 VarDecl *Var, Expr *E) {
18069 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
18070 isa<FunctionParmPackExpr>(E)) &&
18071 "Invalid Expr argument to DoMarkVarDeclReferenced");
18072 Var->setReferenced();
18073
18074 if (Var->isInvalidDecl())
18075 return;
18076
18077 // Record a CUDA/HIP static device/constant variable if it is referenced
18078 // by host code. This is done conservatively, when the variable is referenced
18079 // in any of the following contexts:
18080 // - a non-function context
18081 // - a host function
18082 // - a host device function
18083 // This also requires the reference of the static device/constant variable by
18084 // host code to be visible in the device compilation for the compiler to be
18085 // able to externalize the static device/constant variable.
18086 if (SemaRef.getASTContext().mayExternalizeStaticVar(Var)) {
18087 auto *CurContext = SemaRef.CurContext;
18088 if (!CurContext || !isa<FunctionDecl>(CurContext) ||
18089 cast<FunctionDecl>(CurContext)->hasAttr<CUDAHostAttr>() ||
18090 (!cast<FunctionDecl>(CurContext)->hasAttr<CUDADeviceAttr>() &&
18091 !cast<FunctionDecl>(CurContext)->hasAttr<CUDAGlobalAttr>()))
18092 SemaRef.getASTContext().CUDAStaticDeviceVarReferencedByHost.insert(Var);
18093 }
18094
18095 auto *MSI = Var->getMemberSpecializationInfo();
18096 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
18097 : Var->getTemplateSpecializationKind();
18098
18099 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
18100 bool UsableInConstantExpr =
18101 Var->mightBeUsableInConstantExpressions(SemaRef.Context);
18102
18103 // C++20 [expr.const]p12:
18104 // A variable [...] is needed for constant evaluation if it is [...] a
18105 // variable whose name appears as a potentially constant evaluated
18106 // expression that is either a contexpr variable or is of non-volatile
18107 // const-qualified integral type or of reference type
18108 bool NeededForConstantEvaluation =
18109 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
18110
18111 bool NeedDefinition =
18112 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
18113
18114 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
18115 "Can't instantiate a partial template specialization.");
18116
18117 // If this might be a member specialization of a static data member, check
18118 // the specialization is visible. We already did the checks for variable
18119 // template specializations when we created them.
18120 if (NeedDefinition && TSK != TSK_Undeclared &&
18121 !isa<VarTemplateSpecializationDecl>(Var))
18122 SemaRef.checkSpecializationVisibility(Loc, Var);
18123
18124 // Perform implicit instantiation of static data members, static data member
18125 // templates of class templates, and variable template specializations. Delay
18126 // instantiations of variable templates, except for those that could be used
18127 // in a constant expression.
18128 if (NeedDefinition && isTemplateInstantiation(TSK)) {
18129 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
18130 // instantiation declaration if a variable is usable in a constant
18131 // expression (among other cases).
18132 bool TryInstantiating =
18133 TSK == TSK_ImplicitInstantiation ||
18134 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
18135
18136 if (TryInstantiating) {
18137 SourceLocation PointOfInstantiation =
18138 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
18139 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18140 if (FirstInstantiation) {
18141 PointOfInstantiation = Loc;
18142 if (MSI)
18143 MSI->setPointOfInstantiation(PointOfInstantiation);
18144 // FIXME: Notify listener.
18145 else
18146 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18147 }
18148
18149 if (UsableInConstantExpr) {
18150 // Do not defer instantiations of variables that could be used in a
18151 // constant expression.
18152 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
18153 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
18154 });
18155
18156 // Re-set the member to trigger a recomputation of the dependence bits
18157 // for the expression.
18158 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18159 DRE->setDecl(DRE->getDecl());
18160 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
18161 ME->setMemberDecl(ME->getMemberDecl());
18162 } else if (FirstInstantiation ||
18163 isa<VarTemplateSpecializationDecl>(Var)) {
18164 // FIXME: For a specialization of a variable template, we don't
18165 // distinguish between "declaration and type implicitly instantiated"
18166 // and "implicit instantiation of definition requested", so we have
18167 // no direct way to avoid enqueueing the pending instantiation
18168 // multiple times.
18169 SemaRef.PendingInstantiations
18170 .push_back(std::make_pair(Var, PointOfInstantiation));
18171 }
18172 }
18173 }
18174
18175 // C++2a [basic.def.odr]p4:
18176 // A variable x whose name appears as a potentially-evaluated expression e
18177 // is odr-used by e unless
18178 // -- x is a reference that is usable in constant expressions
18179 // -- x is a variable of non-reference type that is usable in constant
18180 // expressions and has no mutable subobjects [FIXME], and e is an
18181 // element of the set of potential results of an expression of
18182 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
18183 // conversion is applied
18184 // -- x is a variable of non-reference type, and e is an element of the set
18185 // of potential results of a discarded-value expression to which the
18186 // lvalue-to-rvalue conversion is not applied [FIXME]
18187 //
18188 // We check the first part of the second bullet here, and
18189 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
18190 // FIXME: To get the third bullet right, we need to delay this even for
18191 // variables that are not usable in constant expressions.
18192
18193 // If we already know this isn't an odr-use, there's nothing more to do.
18194 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
18195 if (DRE->isNonOdrUse())
18196 return;
18197 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
18198 if (ME->isNonOdrUse())
18199 return;
18200
18201 switch (OdrUse) {
18202 case OdrUseContext::None:
18203 assert((!E || isa<FunctionParmPackExpr>(E)) &&
18204 "missing non-odr-use marking for unevaluated decl ref");
18205 break;
18206
18207 case OdrUseContext::FormallyOdrUsed:
18208 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
18209 // behavior.
18210 break;
18211
18212 case OdrUseContext::Used:
18213 // If we might later find that this expression isn't actually an odr-use,
18214 // delay the marking.
18215 if (E && Var->isUsableInConstantExpressions(SemaRef.Context))
18216 SemaRef.MaybeODRUseExprs.insert(E);
18217 else
18218 MarkVarDeclODRUsed(Var, Loc, SemaRef);
18219 break;
18220
18221 case OdrUseContext::Dependent:
18222 // If this is a dependent context, we don't need to mark variables as
18223 // odr-used, but we may still need to track them for lambda capture.
18224 // FIXME: Do we also need to do this inside dependent typeid expressions
18225 // (which are modeled as unevaluated at this point)?
18226 const bool RefersToEnclosingScope =
18227 (SemaRef.CurContext != Var->getDeclContext() &&
18228 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
18229 if (RefersToEnclosingScope) {
18230 LambdaScopeInfo *const LSI =
18231 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
18232 if (LSI && (!LSI->CallOperator ||
18233 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
18234 // If a variable could potentially be odr-used, defer marking it so
18235 // until we finish analyzing the full expression for any
18236 // lvalue-to-rvalue
18237 // or discarded value conversions that would obviate odr-use.
18238 // Add it to the list of potential captures that will be analyzed
18239 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
18240 // unless the variable is a reference that was initialized by a constant
18241 // expression (this will never need to be captured or odr-used).
18242 //
18243 // FIXME: We can simplify this a lot after implementing P0588R1.
18244 assert(E && "Capture variable should be used in an expression.");
18245 if (!Var->getType()->isReferenceType() ||
18246 !Var->isUsableInConstantExpressions(SemaRef.Context))
18247 LSI->addPotentialCapture(E->IgnoreParens());
18248 }
18249 }
18250 break;
18251 }
18252 }
18253
18254 /// Mark a variable referenced, and check whether it is odr-used
18255 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
18256 /// used directly for normal expressions referring to VarDecl.
MarkVariableReferenced(SourceLocation Loc,VarDecl * Var)18257 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
18258 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
18259 }
18260
MarkExprReferenced(Sema & SemaRef,SourceLocation Loc,Decl * D,Expr * E,bool MightBeOdrUse)18261 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
18262 Decl *D, Expr *E, bool MightBeOdrUse) {
18263 if (SemaRef.isInOpenMPDeclareTargetContext())
18264 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
18265
18266 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
18267 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
18268 return;
18269 }
18270
18271 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
18272
18273 // If this is a call to a method via a cast, also mark the method in the
18274 // derived class used in case codegen can devirtualize the call.
18275 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
18276 if (!ME)
18277 return;
18278 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
18279 if (!MD)
18280 return;
18281 // Only attempt to devirtualize if this is truly a virtual call.
18282 bool IsVirtualCall = MD->isVirtual() &&
18283 ME->performsVirtualDispatch(SemaRef.getLangOpts());
18284 if (!IsVirtualCall)
18285 return;
18286
18287 // If it's possible to devirtualize the call, mark the called function
18288 // referenced.
18289 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
18290 ME->getBase(), SemaRef.getLangOpts().AppleKext);
18291 if (DM)
18292 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
18293 }
18294
18295 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
18296 ///
18297 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
18298 /// handled with care if the DeclRefExpr is not newly-created.
MarkDeclRefReferenced(DeclRefExpr * E,const Expr * Base)18299 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
18300 // TODO: update this with DR# once a defect report is filed.
18301 // C++11 defect. The address of a pure member should not be an ODR use, even
18302 // if it's a qualified reference.
18303 bool OdrUse = true;
18304 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
18305 if (Method->isVirtual() &&
18306 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
18307 OdrUse = false;
18308
18309 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl()))
18310 if (!isConstantEvaluated() && FD->isConsteval() &&
18311 !RebuildingImmediateInvocation)
18312 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
18313 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
18314 }
18315
18316 /// Perform reference-marking and odr-use handling for a MemberExpr.
MarkMemberReferenced(MemberExpr * E)18317 void Sema::MarkMemberReferenced(MemberExpr *E) {
18318 // C++11 [basic.def.odr]p2:
18319 // A non-overloaded function whose name appears as a potentially-evaluated
18320 // expression or a member of a set of candidate functions, if selected by
18321 // overload resolution when referred to from a potentially-evaluated
18322 // expression, is odr-used, unless it is a pure virtual function and its
18323 // name is not explicitly qualified.
18324 bool MightBeOdrUse = true;
18325 if (E->performsVirtualDispatch(getLangOpts())) {
18326 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
18327 if (Method->isPure())
18328 MightBeOdrUse = false;
18329 }
18330 SourceLocation Loc =
18331 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
18332 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
18333 }
18334
18335 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
MarkFunctionParmPackReferenced(FunctionParmPackExpr * E)18336 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
18337 for (VarDecl *VD : *E)
18338 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true);
18339 }
18340
18341 /// Perform marking for a reference to an arbitrary declaration. It
18342 /// marks the declaration referenced, and performs odr-use checking for
18343 /// functions and variables. This method should not be used when building a
18344 /// normal expression which refers to a variable.
MarkAnyDeclReferenced(SourceLocation Loc,Decl * D,bool MightBeOdrUse)18345 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
18346 bool MightBeOdrUse) {
18347 if (MightBeOdrUse) {
18348 if (auto *VD = dyn_cast<VarDecl>(D)) {
18349 MarkVariableReferenced(Loc, VD);
18350 return;
18351 }
18352 }
18353 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
18354 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
18355 return;
18356 }
18357 D->setReferenced();
18358 }
18359
18360 namespace {
18361 // Mark all of the declarations used by a type as referenced.
18362 // FIXME: Not fully implemented yet! We need to have a better understanding
18363 // of when we're entering a context we should not recurse into.
18364 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
18365 // TreeTransforms rebuilding the type in a new context. Rather than
18366 // duplicating the TreeTransform logic, we should consider reusing it here.
18367 // Currently that causes problems when rebuilding LambdaExprs.
18368 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
18369 Sema &S;
18370 SourceLocation Loc;
18371
18372 public:
18373 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
18374
MarkReferencedDecls(Sema & S,SourceLocation Loc)18375 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
18376
18377 bool TraverseTemplateArgument(const TemplateArgument &Arg);
18378 };
18379 }
18380
TraverseTemplateArgument(const TemplateArgument & Arg)18381 bool MarkReferencedDecls::TraverseTemplateArgument(
18382 const TemplateArgument &Arg) {
18383 {
18384 // A non-type template argument is a constant-evaluated context.
18385 EnterExpressionEvaluationContext Evaluated(
18386 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
18387 if (Arg.getKind() == TemplateArgument::Declaration) {
18388 if (Decl *D = Arg.getAsDecl())
18389 S.MarkAnyDeclReferenced(Loc, D, true);
18390 } else if (Arg.getKind() == TemplateArgument::Expression) {
18391 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
18392 }
18393 }
18394
18395 return Inherited::TraverseTemplateArgument(Arg);
18396 }
18397
MarkDeclarationsReferencedInType(SourceLocation Loc,QualType T)18398 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
18399 MarkReferencedDecls Marker(*this, Loc);
18400 Marker.TraverseType(T);
18401 }
18402
18403 namespace {
18404 /// Helper class that marks all of the declarations referenced by
18405 /// potentially-evaluated subexpressions as "referenced".
18406 class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
18407 public:
18408 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
18409 bool SkipLocalVariables;
18410
EvaluatedExprMarker(Sema & S,bool SkipLocalVariables)18411 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
18412 : Inherited(S), SkipLocalVariables(SkipLocalVariables) {}
18413
visitUsedDecl(SourceLocation Loc,Decl * D)18414 void visitUsedDecl(SourceLocation Loc, Decl *D) {
18415 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
18416 }
18417
VisitDeclRefExpr(DeclRefExpr * E)18418 void VisitDeclRefExpr(DeclRefExpr *E) {
18419 // If we were asked not to visit local variables, don't.
18420 if (SkipLocalVariables) {
18421 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
18422 if (VD->hasLocalStorage())
18423 return;
18424 }
18425
18426 // FIXME: This can trigger the instantiation of the initializer of a
18427 // variable, which can cause the expression to become value-dependent
18428 // or error-dependent. Do we need to propagate the new dependence bits?
18429 S.MarkDeclRefReferenced(E);
18430 }
18431
VisitMemberExpr(MemberExpr * E)18432 void VisitMemberExpr(MemberExpr *E) {
18433 S.MarkMemberReferenced(E);
18434 Visit(E->getBase());
18435 }
18436 };
18437 } // namespace
18438
18439 /// Mark any declarations that appear within this expression or any
18440 /// potentially-evaluated subexpressions as "referenced".
18441 ///
18442 /// \param SkipLocalVariables If true, don't mark local variables as
18443 /// 'referenced'.
MarkDeclarationsReferencedInExpr(Expr * E,bool SkipLocalVariables)18444 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
18445 bool SkipLocalVariables) {
18446 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
18447 }
18448
18449 /// Emit a diagnostic that describes an effect on the run-time behavior
18450 /// of the program being compiled.
18451 ///
18452 /// This routine emits the given diagnostic when the code currently being
18453 /// type-checked is "potentially evaluated", meaning that there is a
18454 /// possibility that the code will actually be executable. Code in sizeof()
18455 /// expressions, code used only during overload resolution, etc., are not
18456 /// potentially evaluated. This routine will suppress such diagnostics or,
18457 /// in the absolutely nutty case of potentially potentially evaluated
18458 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
18459 /// later.
18460 ///
18461 /// This routine should be used for all diagnostics that describe the run-time
18462 /// behavior of a program, such as passing a non-POD value through an ellipsis.
18463 /// Failure to do so will likely result in spurious diagnostics or failures
18464 /// during overload resolution or within sizeof/alignof/typeof/typeid.
DiagRuntimeBehavior(SourceLocation Loc,ArrayRef<const Stmt * > Stmts,const PartialDiagnostic & PD)18465 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
18466 const PartialDiagnostic &PD) {
18467 switch (ExprEvalContexts.back().Context) {
18468 case ExpressionEvaluationContext::Unevaluated:
18469 case ExpressionEvaluationContext::UnevaluatedList:
18470 case ExpressionEvaluationContext::UnevaluatedAbstract:
18471 case ExpressionEvaluationContext::DiscardedStatement:
18472 // The argument will never be evaluated, so don't complain.
18473 break;
18474
18475 case ExpressionEvaluationContext::ConstantEvaluated:
18476 // Relevant diagnostics should be produced by constant evaluation.
18477 break;
18478
18479 case ExpressionEvaluationContext::PotentiallyEvaluated:
18480 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18481 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
18482 FunctionScopes.back()->PossiblyUnreachableDiags.
18483 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
18484 return true;
18485 }
18486
18487 // The initializer of a constexpr variable or of the first declaration of a
18488 // static data member is not syntactically a constant evaluated constant,
18489 // but nonetheless is always required to be a constant expression, so we
18490 // can skip diagnosing.
18491 // FIXME: Using the mangling context here is a hack.
18492 if (auto *VD = dyn_cast_or_null<VarDecl>(
18493 ExprEvalContexts.back().ManglingContextDecl)) {
18494 if (VD->isConstexpr() ||
18495 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
18496 break;
18497 // FIXME: For any other kind of variable, we should build a CFG for its
18498 // initializer and check whether the context in question is reachable.
18499 }
18500
18501 Diag(Loc, PD);
18502 return true;
18503 }
18504
18505 return false;
18506 }
18507
DiagRuntimeBehavior(SourceLocation Loc,const Stmt * Statement,const PartialDiagnostic & PD)18508 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
18509 const PartialDiagnostic &PD) {
18510 return DiagRuntimeBehavior(
18511 Loc, Statement ? llvm::makeArrayRef(Statement) : llvm::None, PD);
18512 }
18513
CheckCallReturnType(QualType ReturnType,SourceLocation Loc,CallExpr * CE,FunctionDecl * FD)18514 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
18515 CallExpr *CE, FunctionDecl *FD) {
18516 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
18517 return false;
18518
18519 // If we're inside a decltype's expression, don't check for a valid return
18520 // type or construct temporaries until we know whether this is the last call.
18521 if (ExprEvalContexts.back().ExprContext ==
18522 ExpressionEvaluationContextRecord::EK_Decltype) {
18523 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
18524 return false;
18525 }
18526
18527 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
18528 FunctionDecl *FD;
18529 CallExpr *CE;
18530
18531 public:
18532 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
18533 : FD(FD), CE(CE) { }
18534
18535 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18536 if (!FD) {
18537 S.Diag(Loc, diag::err_call_incomplete_return)
18538 << T << CE->getSourceRange();
18539 return;
18540 }
18541
18542 S.Diag(Loc, diag::err_call_function_incomplete_return)
18543 << CE->getSourceRange() << FD << T;
18544 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
18545 << FD->getDeclName();
18546 }
18547 } Diagnoser(FD, CE);
18548
18549 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
18550 return true;
18551
18552 return false;
18553 }
18554
18555 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
18556 // will prevent this condition from triggering, which is what we want.
DiagnoseAssignmentAsCondition(Expr * E)18557 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
18558 SourceLocation Loc;
18559
18560 unsigned diagnostic = diag::warn_condition_is_assignment;
18561 bool IsOrAssign = false;
18562
18563 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
18564 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
18565 return;
18566
18567 IsOrAssign = Op->getOpcode() == BO_OrAssign;
18568
18569 // Greylist some idioms by putting them into a warning subcategory.
18570 if (ObjCMessageExpr *ME
18571 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
18572 Selector Sel = ME->getSelector();
18573
18574 // self = [<foo> init...]
18575 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
18576 diagnostic = diag::warn_condition_is_idiomatic_assignment;
18577
18578 // <foo> = [<bar> nextObject]
18579 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
18580 diagnostic = diag::warn_condition_is_idiomatic_assignment;
18581 }
18582
18583 Loc = Op->getOperatorLoc();
18584 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
18585 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
18586 return;
18587
18588 IsOrAssign = Op->getOperator() == OO_PipeEqual;
18589 Loc = Op->getOperatorLoc();
18590 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
18591 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
18592 else {
18593 // Not an assignment.
18594 return;
18595 }
18596
18597 Diag(Loc, diagnostic) << E->getSourceRange();
18598
18599 SourceLocation Open = E->getBeginLoc();
18600 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
18601 Diag(Loc, diag::note_condition_assign_silence)
18602 << FixItHint::CreateInsertion(Open, "(")
18603 << FixItHint::CreateInsertion(Close, ")");
18604
18605 if (IsOrAssign)
18606 Diag(Loc, diag::note_condition_or_assign_to_comparison)
18607 << FixItHint::CreateReplacement(Loc, "!=");
18608 else
18609 Diag(Loc, diag::note_condition_assign_to_comparison)
18610 << FixItHint::CreateReplacement(Loc, "==");
18611 }
18612
18613 /// Redundant parentheses over an equality comparison can indicate
18614 /// that the user intended an assignment used as condition.
DiagnoseEqualityWithExtraParens(ParenExpr * ParenE)18615 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
18616 // Don't warn if the parens came from a macro.
18617 SourceLocation parenLoc = ParenE->getBeginLoc();
18618 if (parenLoc.isInvalid() || parenLoc.isMacroID())
18619 return;
18620 // Don't warn for dependent expressions.
18621 if (ParenE->isTypeDependent())
18622 return;
18623
18624 Expr *E = ParenE->IgnoreParens();
18625
18626 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
18627 if (opE->getOpcode() == BO_EQ &&
18628 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
18629 == Expr::MLV_Valid) {
18630 SourceLocation Loc = opE->getOperatorLoc();
18631
18632 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
18633 SourceRange ParenERange = ParenE->getSourceRange();
18634 Diag(Loc, diag::note_equality_comparison_silence)
18635 << FixItHint::CreateRemoval(ParenERange.getBegin())
18636 << FixItHint::CreateRemoval(ParenERange.getEnd());
18637 Diag(Loc, diag::note_equality_comparison_to_assign)
18638 << FixItHint::CreateReplacement(Loc, "=");
18639 }
18640 }
18641
CheckBooleanCondition(SourceLocation Loc,Expr * E,bool IsConstexpr)18642 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
18643 bool IsConstexpr) {
18644 DiagnoseAssignmentAsCondition(E);
18645 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
18646 DiagnoseEqualityWithExtraParens(parenE);
18647
18648 ExprResult result = CheckPlaceholderExpr(E);
18649 if (result.isInvalid()) return ExprError();
18650 E = result.get();
18651
18652 if (!E->isTypeDependent()) {
18653 if (getLangOpts().CPlusPlus)
18654 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
18655
18656 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
18657 if (ERes.isInvalid())
18658 return ExprError();
18659 E = ERes.get();
18660
18661 QualType T = E->getType();
18662 if (!T->isScalarType()) { // C99 6.8.4.1p1
18663 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
18664 << T << E->getSourceRange();
18665 return ExprError();
18666 }
18667 CheckBoolLikeConversion(E, Loc);
18668 }
18669
18670 return E;
18671 }
18672
ActOnCondition(Scope * S,SourceLocation Loc,Expr * SubExpr,ConditionKind CK)18673 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
18674 Expr *SubExpr, ConditionKind CK) {
18675 // Empty conditions are valid in for-statements.
18676 if (!SubExpr)
18677 return ConditionResult();
18678
18679 ExprResult Cond;
18680 switch (CK) {
18681 case ConditionKind::Boolean:
18682 Cond = CheckBooleanCondition(Loc, SubExpr);
18683 break;
18684
18685 case ConditionKind::ConstexprIf:
18686 Cond = CheckBooleanCondition(Loc, SubExpr, true);
18687 break;
18688
18689 case ConditionKind::Switch:
18690 Cond = CheckSwitchCondition(Loc, SubExpr);
18691 break;
18692 }
18693 if (Cond.isInvalid()) {
18694 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
18695 {SubExpr});
18696 if (!Cond.get())
18697 return ConditionError();
18698 }
18699 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
18700 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
18701 if (!FullExpr.get())
18702 return ConditionError();
18703
18704 return ConditionResult(*this, nullptr, FullExpr,
18705 CK == ConditionKind::ConstexprIf);
18706 }
18707
18708 namespace {
18709 /// A visitor for rebuilding a call to an __unknown_any expression
18710 /// to have an appropriate type.
18711 struct RebuildUnknownAnyFunction
18712 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
18713
18714 Sema &S;
18715
RebuildUnknownAnyFunction__anona30d30eb2411::RebuildUnknownAnyFunction18716 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
18717
VisitStmt__anona30d30eb2411::RebuildUnknownAnyFunction18718 ExprResult VisitStmt(Stmt *S) {
18719 llvm_unreachable("unexpected statement!");
18720 }
18721
VisitExpr__anona30d30eb2411::RebuildUnknownAnyFunction18722 ExprResult VisitExpr(Expr *E) {
18723 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
18724 << E->getSourceRange();
18725 return ExprError();
18726 }
18727
18728 /// Rebuild an expression which simply semantically wraps another
18729 /// expression which it shares the type and value kind of.
rebuildSugarExpr__anona30d30eb2411::RebuildUnknownAnyFunction18730 template <class T> ExprResult rebuildSugarExpr(T *E) {
18731 ExprResult SubResult = Visit(E->getSubExpr());
18732 if (SubResult.isInvalid()) return ExprError();
18733
18734 Expr *SubExpr = SubResult.get();
18735 E->setSubExpr(SubExpr);
18736 E->setType(SubExpr->getType());
18737 E->setValueKind(SubExpr->getValueKind());
18738 assert(E->getObjectKind() == OK_Ordinary);
18739 return E;
18740 }
18741
VisitParenExpr__anona30d30eb2411::RebuildUnknownAnyFunction18742 ExprResult VisitParenExpr(ParenExpr *E) {
18743 return rebuildSugarExpr(E);
18744 }
18745
VisitUnaryExtension__anona30d30eb2411::RebuildUnknownAnyFunction18746 ExprResult VisitUnaryExtension(UnaryOperator *E) {
18747 return rebuildSugarExpr(E);
18748 }
18749
VisitUnaryAddrOf__anona30d30eb2411::RebuildUnknownAnyFunction18750 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18751 ExprResult SubResult = Visit(E->getSubExpr());
18752 if (SubResult.isInvalid()) return ExprError();
18753
18754 Expr *SubExpr = SubResult.get();
18755 E->setSubExpr(SubExpr);
18756 E->setType(S.Context.getPointerType(SubExpr->getType()));
18757 assert(E->getValueKind() == VK_RValue);
18758 assert(E->getObjectKind() == OK_Ordinary);
18759 return E;
18760 }
18761
resolveDecl__anona30d30eb2411::RebuildUnknownAnyFunction18762 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
18763 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
18764
18765 E->setType(VD->getType());
18766
18767 assert(E->getValueKind() == VK_RValue);
18768 if (S.getLangOpts().CPlusPlus &&
18769 !(isa<CXXMethodDecl>(VD) &&
18770 cast<CXXMethodDecl>(VD)->isInstance()))
18771 E->setValueKind(VK_LValue);
18772
18773 return E;
18774 }
18775
VisitMemberExpr__anona30d30eb2411::RebuildUnknownAnyFunction18776 ExprResult VisitMemberExpr(MemberExpr *E) {
18777 return resolveDecl(E, E->getMemberDecl());
18778 }
18779
VisitDeclRefExpr__anona30d30eb2411::RebuildUnknownAnyFunction18780 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18781 return resolveDecl(E, E->getDecl());
18782 }
18783 };
18784 }
18785
18786 /// Given a function expression of unknown-any type, try to rebuild it
18787 /// to have a function type.
rebuildUnknownAnyFunction(Sema & S,Expr * FunctionExpr)18788 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
18789 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
18790 if (Result.isInvalid()) return ExprError();
18791 return S.DefaultFunctionArrayConversion(Result.get());
18792 }
18793
18794 namespace {
18795 /// A visitor for rebuilding an expression of type __unknown_anytype
18796 /// into one which resolves the type directly on the referring
18797 /// expression. Strict preservation of the original source
18798 /// structure is not a goal.
18799 struct RebuildUnknownAnyExpr
18800 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
18801
18802 Sema &S;
18803
18804 /// The current destination type.
18805 QualType DestType;
18806
RebuildUnknownAnyExpr__anona30d30eb2511::RebuildUnknownAnyExpr18807 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
18808 : S(S), DestType(CastType) {}
18809
VisitStmt__anona30d30eb2511::RebuildUnknownAnyExpr18810 ExprResult VisitStmt(Stmt *S) {
18811 llvm_unreachable("unexpected statement!");
18812 }
18813
VisitExpr__anona30d30eb2511::RebuildUnknownAnyExpr18814 ExprResult VisitExpr(Expr *E) {
18815 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
18816 << E->getSourceRange();
18817 return ExprError();
18818 }
18819
18820 ExprResult VisitCallExpr(CallExpr *E);
18821 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
18822
18823 /// Rebuild an expression which simply semantically wraps another
18824 /// expression which it shares the type and value kind of.
rebuildSugarExpr__anona30d30eb2511::RebuildUnknownAnyExpr18825 template <class T> ExprResult rebuildSugarExpr(T *E) {
18826 ExprResult SubResult = Visit(E->getSubExpr());
18827 if (SubResult.isInvalid()) return ExprError();
18828 Expr *SubExpr = SubResult.get();
18829 E->setSubExpr(SubExpr);
18830 E->setType(SubExpr->getType());
18831 E->setValueKind(SubExpr->getValueKind());
18832 assert(E->getObjectKind() == OK_Ordinary);
18833 return E;
18834 }
18835
VisitParenExpr__anona30d30eb2511::RebuildUnknownAnyExpr18836 ExprResult VisitParenExpr(ParenExpr *E) {
18837 return rebuildSugarExpr(E);
18838 }
18839
VisitUnaryExtension__anona30d30eb2511::RebuildUnknownAnyExpr18840 ExprResult VisitUnaryExtension(UnaryOperator *E) {
18841 return rebuildSugarExpr(E);
18842 }
18843
VisitUnaryAddrOf__anona30d30eb2511::RebuildUnknownAnyExpr18844 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
18845 const PointerType *Ptr = DestType->getAs<PointerType>();
18846 if (!Ptr) {
18847 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
18848 << E->getSourceRange();
18849 return ExprError();
18850 }
18851
18852 if (isa<CallExpr>(E->getSubExpr())) {
18853 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
18854 << E->getSourceRange();
18855 return ExprError();
18856 }
18857
18858 assert(E->getValueKind() == VK_RValue);
18859 assert(E->getObjectKind() == OK_Ordinary);
18860 E->setType(DestType);
18861
18862 // Build the sub-expression as if it were an object of the pointee type.
18863 DestType = Ptr->getPointeeType();
18864 ExprResult SubResult = Visit(E->getSubExpr());
18865 if (SubResult.isInvalid()) return ExprError();
18866 E->setSubExpr(SubResult.get());
18867 return E;
18868 }
18869
18870 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
18871
18872 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
18873
VisitMemberExpr__anona30d30eb2511::RebuildUnknownAnyExpr18874 ExprResult VisitMemberExpr(MemberExpr *E) {
18875 return resolveDecl(E, E->getMemberDecl());
18876 }
18877
VisitDeclRefExpr__anona30d30eb2511::RebuildUnknownAnyExpr18878 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
18879 return resolveDecl(E, E->getDecl());
18880 }
18881 };
18882 }
18883
18884 /// Rebuilds a call expression which yielded __unknown_anytype.
VisitCallExpr(CallExpr * E)18885 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
18886 Expr *CalleeExpr = E->getCallee();
18887
18888 enum FnKind {
18889 FK_MemberFunction,
18890 FK_FunctionPointer,
18891 FK_BlockPointer
18892 };
18893
18894 FnKind Kind;
18895 QualType CalleeType = CalleeExpr->getType();
18896 if (CalleeType == S.Context.BoundMemberTy) {
18897 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
18898 Kind = FK_MemberFunction;
18899 CalleeType = Expr::findBoundMemberType(CalleeExpr);
18900 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
18901 CalleeType = Ptr->getPointeeType();
18902 Kind = FK_FunctionPointer;
18903 } else {
18904 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
18905 Kind = FK_BlockPointer;
18906 }
18907 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
18908
18909 // Verify that this is a legal result type of a function.
18910 if (DestType->isArrayType() || DestType->isFunctionType()) {
18911 unsigned diagID = diag::err_func_returning_array_function;
18912 if (Kind == FK_BlockPointer)
18913 diagID = diag::err_block_returning_array_function;
18914
18915 S.Diag(E->getExprLoc(), diagID)
18916 << DestType->isFunctionType() << DestType;
18917 return ExprError();
18918 }
18919
18920 // Otherwise, go ahead and set DestType as the call's result.
18921 E->setType(DestType.getNonLValueExprType(S.Context));
18922 E->setValueKind(Expr::getValueKindForType(DestType));
18923 assert(E->getObjectKind() == OK_Ordinary);
18924
18925 // Rebuild the function type, replacing the result type with DestType.
18926 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
18927 if (Proto) {
18928 // __unknown_anytype(...) is a special case used by the debugger when
18929 // it has no idea what a function's signature is.
18930 //
18931 // We want to build this call essentially under the K&R
18932 // unprototyped rules, but making a FunctionNoProtoType in C++
18933 // would foul up all sorts of assumptions. However, we cannot
18934 // simply pass all arguments as variadic arguments, nor can we
18935 // portably just call the function under a non-variadic type; see
18936 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
18937 // However, it turns out that in practice it is generally safe to
18938 // call a function declared as "A foo(B,C,D);" under the prototype
18939 // "A foo(B,C,D,...);". The only known exception is with the
18940 // Windows ABI, where any variadic function is implicitly cdecl
18941 // regardless of its normal CC. Therefore we change the parameter
18942 // types to match the types of the arguments.
18943 //
18944 // This is a hack, but it is far superior to moving the
18945 // corresponding target-specific code from IR-gen to Sema/AST.
18946
18947 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
18948 SmallVector<QualType, 8> ArgTypes;
18949 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
18950 ArgTypes.reserve(E->getNumArgs());
18951 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
18952 Expr *Arg = E->getArg(i);
18953 QualType ArgType = Arg->getType();
18954 if (E->isLValue()) {
18955 ArgType = S.Context.getLValueReferenceType(ArgType);
18956 } else if (E->isXValue()) {
18957 ArgType = S.Context.getRValueReferenceType(ArgType);
18958 }
18959 ArgTypes.push_back(ArgType);
18960 }
18961 ParamTypes = ArgTypes;
18962 }
18963 DestType = S.Context.getFunctionType(DestType, ParamTypes,
18964 Proto->getExtProtoInfo());
18965 } else {
18966 DestType = S.Context.getFunctionNoProtoType(DestType,
18967 FnType->getExtInfo());
18968 }
18969
18970 // Rebuild the appropriate pointer-to-function type.
18971 switch (Kind) {
18972 case FK_MemberFunction:
18973 // Nothing to do.
18974 break;
18975
18976 case FK_FunctionPointer:
18977 DestType = S.Context.getPointerType(DestType);
18978 break;
18979
18980 case FK_BlockPointer:
18981 DestType = S.Context.getBlockPointerType(DestType);
18982 break;
18983 }
18984
18985 // Finally, we can recurse.
18986 ExprResult CalleeResult = Visit(CalleeExpr);
18987 if (!CalleeResult.isUsable()) return ExprError();
18988 E->setCallee(CalleeResult.get());
18989
18990 // Bind a temporary if necessary.
18991 return S.MaybeBindToTemporary(E);
18992 }
18993
VisitObjCMessageExpr(ObjCMessageExpr * E)18994 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
18995 // Verify that this is a legal result type of a call.
18996 if (DestType->isArrayType() || DestType->isFunctionType()) {
18997 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
18998 << DestType->isFunctionType() << DestType;
18999 return ExprError();
19000 }
19001
19002 // Rewrite the method result type if available.
19003 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
19004 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
19005 Method->setReturnType(DestType);
19006 }
19007
19008 // Change the type of the message.
19009 E->setType(DestType.getNonReferenceType());
19010 E->setValueKind(Expr::getValueKindForType(DestType));
19011
19012 return S.MaybeBindToTemporary(E);
19013 }
19014
VisitImplicitCastExpr(ImplicitCastExpr * E)19015 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
19016 // The only case we should ever see here is a function-to-pointer decay.
19017 if (E->getCastKind() == CK_FunctionToPointerDecay) {
19018 assert(E->getValueKind() == VK_RValue);
19019 assert(E->getObjectKind() == OK_Ordinary);
19020
19021 E->setType(DestType);
19022
19023 // Rebuild the sub-expression as the pointee (function) type.
19024 DestType = DestType->castAs<PointerType>()->getPointeeType();
19025
19026 ExprResult Result = Visit(E->getSubExpr());
19027 if (!Result.isUsable()) return ExprError();
19028
19029 E->setSubExpr(Result.get());
19030 return E;
19031 } else if (E->getCastKind() == CK_LValueToRValue) {
19032 assert(E->getValueKind() == VK_RValue);
19033 assert(E->getObjectKind() == OK_Ordinary);
19034
19035 assert(isa<BlockPointerType>(E->getType()));
19036
19037 E->setType(DestType);
19038
19039 // The sub-expression has to be a lvalue reference, so rebuild it as such.
19040 DestType = S.Context.getLValueReferenceType(DestType);
19041
19042 ExprResult Result = Visit(E->getSubExpr());
19043 if (!Result.isUsable()) return ExprError();
19044
19045 E->setSubExpr(Result.get());
19046 return E;
19047 } else {
19048 llvm_unreachable("Unhandled cast type!");
19049 }
19050 }
19051
resolveDecl(Expr * E,ValueDecl * VD)19052 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
19053 ExprValueKind ValueKind = VK_LValue;
19054 QualType Type = DestType;
19055
19056 // We know how to make this work for certain kinds of decls:
19057
19058 // - functions
19059 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
19060 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
19061 DestType = Ptr->getPointeeType();
19062 ExprResult Result = resolveDecl(E, VD);
19063 if (Result.isInvalid()) return ExprError();
19064 return S.ImpCastExprToType(Result.get(), Type,
19065 CK_FunctionToPointerDecay, VK_RValue);
19066 }
19067
19068 if (!Type->isFunctionType()) {
19069 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
19070 << VD << E->getSourceRange();
19071 return ExprError();
19072 }
19073 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
19074 // We must match the FunctionDecl's type to the hack introduced in
19075 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
19076 // type. See the lengthy commentary in that routine.
19077 QualType FDT = FD->getType();
19078 const FunctionType *FnType = FDT->castAs<FunctionType>();
19079 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
19080 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
19081 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
19082 SourceLocation Loc = FD->getLocation();
19083 FunctionDecl *NewFD = FunctionDecl::Create(
19084 S.Context, FD->getDeclContext(), Loc, Loc,
19085 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
19086 SC_None, false /*isInlineSpecified*/, FD->hasPrototype(),
19087 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
19088
19089 if (FD->getQualifier())
19090 NewFD->setQualifierInfo(FD->getQualifierLoc());
19091
19092 SmallVector<ParmVarDecl*, 16> Params;
19093 for (const auto &AI : FT->param_types()) {
19094 ParmVarDecl *Param =
19095 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
19096 Param->setScopeInfo(0, Params.size());
19097 Params.push_back(Param);
19098 }
19099 NewFD->setParams(Params);
19100 DRE->setDecl(NewFD);
19101 VD = DRE->getDecl();
19102 }
19103 }
19104
19105 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
19106 if (MD->isInstance()) {
19107 ValueKind = VK_RValue;
19108 Type = S.Context.BoundMemberTy;
19109 }
19110
19111 // Function references aren't l-values in C.
19112 if (!S.getLangOpts().CPlusPlus)
19113 ValueKind = VK_RValue;
19114
19115 // - variables
19116 } else if (isa<VarDecl>(VD)) {
19117 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
19118 Type = RefTy->getPointeeType();
19119 } else if (Type->isFunctionType()) {
19120 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
19121 << VD << E->getSourceRange();
19122 return ExprError();
19123 }
19124
19125 // - nothing else
19126 } else {
19127 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
19128 << VD << E->getSourceRange();
19129 return ExprError();
19130 }
19131
19132 // Modifying the declaration like this is friendly to IR-gen but
19133 // also really dangerous.
19134 VD->setType(DestType);
19135 E->setType(Type);
19136 E->setValueKind(ValueKind);
19137 return E;
19138 }
19139
19140 /// Check a cast of an unknown-any type. We intentionally only
19141 /// trigger this for C-style casts.
checkUnknownAnyCast(SourceRange TypeRange,QualType CastType,Expr * CastExpr,CastKind & CastKind,ExprValueKind & VK,CXXCastPath & Path)19142 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
19143 Expr *CastExpr, CastKind &CastKind,
19144 ExprValueKind &VK, CXXCastPath &Path) {
19145 // The type we're casting to must be either void or complete.
19146 if (!CastType->isVoidType() &&
19147 RequireCompleteType(TypeRange.getBegin(), CastType,
19148 diag::err_typecheck_cast_to_incomplete))
19149 return ExprError();
19150
19151 // Rewrite the casted expression from scratch.
19152 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
19153 if (!result.isUsable()) return ExprError();
19154
19155 CastExpr = result.get();
19156 VK = CastExpr->getValueKind();
19157 CastKind = CK_NoOp;
19158
19159 return CastExpr;
19160 }
19161
forceUnknownAnyToType(Expr * E,QualType ToType)19162 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
19163 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
19164 }
19165
checkUnknownAnyArg(SourceLocation callLoc,Expr * arg,QualType & paramType)19166 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
19167 Expr *arg, QualType ¶mType) {
19168 // If the syntactic form of the argument is not an explicit cast of
19169 // any sort, just do default argument promotion.
19170 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
19171 if (!castArg) {
19172 ExprResult result = DefaultArgumentPromotion(arg);
19173 if (result.isInvalid()) return ExprError();
19174 paramType = result.get()->getType();
19175 return result;
19176 }
19177
19178 // Otherwise, use the type that was written in the explicit cast.
19179 assert(!arg->hasPlaceholderType());
19180 paramType = castArg->getTypeAsWritten();
19181
19182 // Copy-initialize a parameter of that type.
19183 InitializedEntity entity =
19184 InitializedEntity::InitializeParameter(Context, paramType,
19185 /*consumed*/ false);
19186 return PerformCopyInitialization(entity, callLoc, arg);
19187 }
19188
diagnoseUnknownAnyExpr(Sema & S,Expr * E)19189 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
19190 Expr *orig = E;
19191 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
19192 while (true) {
19193 E = E->IgnoreParenImpCasts();
19194 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
19195 E = call->getCallee();
19196 diagID = diag::err_uncasted_call_of_unknown_any;
19197 } else {
19198 break;
19199 }
19200 }
19201
19202 SourceLocation loc;
19203 NamedDecl *d;
19204 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
19205 loc = ref->getLocation();
19206 d = ref->getDecl();
19207 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
19208 loc = mem->getMemberLoc();
19209 d = mem->getMemberDecl();
19210 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
19211 diagID = diag::err_uncasted_call_of_unknown_any;
19212 loc = msg->getSelectorStartLoc();
19213 d = msg->getMethodDecl();
19214 if (!d) {
19215 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
19216 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
19217 << orig->getSourceRange();
19218 return ExprError();
19219 }
19220 } else {
19221 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
19222 << E->getSourceRange();
19223 return ExprError();
19224 }
19225
19226 S.Diag(loc, diagID) << d << orig->getSourceRange();
19227
19228 // Never recoverable.
19229 return ExprError();
19230 }
19231
19232 /// Check for operands with placeholder types and complain if found.
19233 /// Returns ExprError() if there was an error and no recovery was possible.
CheckPlaceholderExpr(Expr * E)19234 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
19235 if (!Context.isDependenceAllowed()) {
19236 // C cannot handle TypoExpr nodes on either side of a binop because it
19237 // doesn't handle dependent types properly, so make sure any TypoExprs have
19238 // been dealt with before checking the operands.
19239 ExprResult Result = CorrectDelayedTyposInExpr(E);
19240 if (!Result.isUsable()) return ExprError();
19241 E = Result.get();
19242 }
19243
19244 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
19245 if (!placeholderType) return E;
19246
19247 switch (placeholderType->getKind()) {
19248
19249 // Overloaded expressions.
19250 case BuiltinType::Overload: {
19251 // Try to resolve a single function template specialization.
19252 // This is obligatory.
19253 ExprResult Result = E;
19254 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
19255 return Result;
19256
19257 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
19258 // leaves Result unchanged on failure.
19259 Result = E;
19260 if (resolveAndFixAddressOfSingleOverloadCandidate(Result))
19261 return Result;
19262
19263 // If that failed, try to recover with a call.
19264 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
19265 /*complain*/ true);
19266 return Result;
19267 }
19268
19269 // Bound member functions.
19270 case BuiltinType::BoundMember: {
19271 ExprResult result = E;
19272 const Expr *BME = E->IgnoreParens();
19273 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
19274 // Try to give a nicer diagnostic if it is a bound member that we recognize.
19275 if (isa<CXXPseudoDestructorExpr>(BME)) {
19276 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
19277 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
19278 if (ME->getMemberNameInfo().getName().getNameKind() ==
19279 DeclarationName::CXXDestructorName)
19280 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
19281 }
19282 tryToRecoverWithCall(result, PD,
19283 /*complain*/ true);
19284 return result;
19285 }
19286
19287 // ARC unbridged casts.
19288 case BuiltinType::ARCUnbridgedCast: {
19289 Expr *realCast = stripARCUnbridgedCast(E);
19290 diagnoseARCUnbridgedCast(realCast);
19291 return realCast;
19292 }
19293
19294 // Expressions of unknown type.
19295 case BuiltinType::UnknownAny:
19296 return diagnoseUnknownAnyExpr(*this, E);
19297
19298 // Pseudo-objects.
19299 case BuiltinType::PseudoObject:
19300 return checkPseudoObjectRValue(E);
19301
19302 case BuiltinType::BuiltinFn: {
19303 // Accept __noop without parens by implicitly converting it to a call expr.
19304 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
19305 if (DRE) {
19306 auto *FD = cast<FunctionDecl>(DRE->getDecl());
19307 if (FD->getBuiltinID() == Builtin::BI__noop) {
19308 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
19309 CK_BuiltinFnToFnPtr)
19310 .get();
19311 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
19312 VK_RValue, SourceLocation(),
19313 FPOptionsOverride());
19314 }
19315 }
19316
19317 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
19318 return ExprError();
19319 }
19320
19321 case BuiltinType::IncompleteMatrixIdx:
19322 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
19323 ->getRowIdx()
19324 ->getBeginLoc(),
19325 diag::err_matrix_incomplete_index);
19326 return ExprError();
19327
19328 // Expressions of unknown type.
19329 case BuiltinType::OMPArraySection:
19330 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
19331 return ExprError();
19332
19333 // Expressions of unknown type.
19334 case BuiltinType::OMPArrayShaping:
19335 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
19336
19337 case BuiltinType::OMPIterator:
19338 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
19339
19340 // Everything else should be impossible.
19341 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
19342 case BuiltinType::Id:
19343 #include "clang/Basic/OpenCLImageTypes.def"
19344 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
19345 case BuiltinType::Id:
19346 #include "clang/Basic/OpenCLExtensionTypes.def"
19347 #define SVE_TYPE(Name, Id, SingletonId) \
19348 case BuiltinType::Id:
19349 #include "clang/Basic/AArch64SVEACLETypes.def"
19350 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \
19351 case BuiltinType::Id:
19352 #include "clang/Basic/PPCTypes.def"
19353 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
19354 #define PLACEHOLDER_TYPE(Id, SingletonId)
19355 #include "clang/AST/BuiltinTypes.def"
19356 break;
19357 }
19358
19359 llvm_unreachable("invalid placeholder type!");
19360 }
19361
CheckCaseExpression(Expr * E)19362 bool Sema::CheckCaseExpression(Expr *E) {
19363 if (E->isTypeDependent())
19364 return true;
19365 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
19366 return E->getType()->isIntegralOrEnumerationType();
19367 return false;
19368 }
19369
19370 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
19371 ExprResult
ActOnObjCBoolLiteral(SourceLocation OpLoc,tok::TokenKind Kind)19372 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
19373 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
19374 "Unknown Objective-C Boolean value!");
19375 QualType BoolT = Context.ObjCBuiltinBoolTy;
19376 if (!Context.getBOOLDecl()) {
19377 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
19378 Sema::LookupOrdinaryName);
19379 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
19380 NamedDecl *ND = Result.getFoundDecl();
19381 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
19382 Context.setBOOLDecl(TD);
19383 }
19384 }
19385 if (Context.getBOOLDecl())
19386 BoolT = Context.getBOOLType();
19387 return new (Context)
19388 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
19389 }
19390
ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,SourceLocation AtLoc,SourceLocation RParen)19391 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
19392 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
19393 SourceLocation RParen) {
19394
19395 StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
19396
19397 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
19398 return Spec.getPlatform() == Platform;
19399 });
19400
19401 VersionTuple Version;
19402 if (Spec != AvailSpecs.end())
19403 Version = Spec->getVersion();
19404
19405 // The use of `@available` in the enclosing function should be analyzed to
19406 // warn when it's used inappropriately (i.e. not if(@available)).
19407 if (getCurFunctionOrMethodDecl())
19408 getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
19409 else if (getCurBlock() || getCurLambda())
19410 getCurFunction()->HasPotentialAvailabilityViolations = true;
19411
19412 return new (Context)
19413 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
19414 }
19415
CreateRecoveryExpr(SourceLocation Begin,SourceLocation End,ArrayRef<Expr * > SubExprs,QualType T)19416 ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
19417 ArrayRef<Expr *> SubExprs, QualType T) {
19418 if (!Context.getLangOpts().RecoveryAST)
19419 return ExprError();
19420
19421 if (isSFINAEContext())
19422 return ExprError();
19423
19424 if (T.isNull() || !Context.getLangOpts().RecoveryASTType)
19425 // We don't know the concrete type, fallback to dependent type.
19426 T = Context.DependentTy;
19427 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
19428 }
19429