1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for expressions.
12 //===----------------------------------------------------------------------===//
14 #include "TreeTransform.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/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/Support/ConvertUTF.h"
47 using namespace clang;
50 /// \brief Determine whether the use of this declaration is valid, without
51 /// emitting diagnostics.
52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53 // See if this is an auto-typed variable whose initializer we are parsing.
54 if (ParsingInitForAutoVars.count(D))
57 // See if this is a deleted function.
58 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
62 // If the function has a deduced return type, and we can't deduce it,
63 // then we can't use it either.
64 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
69 // See if this function is unavailable.
70 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
71 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78 // Warn if this is used but marked unused.
79 if (const auto *A = D->getAttr<UnusedAttr>()) {
80 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81 // should diagnose them.
82 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused) {
83 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84 if (DC && !DC->hasAttr<UnusedAttr>())
85 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
91 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
94 const ObjCInterfaceDecl *OID = OMD->getClassInterface();
98 for (const ObjCCategoryDecl *Cat : OID->visible_categories())
99 if (ObjCMethodDecl *CatMeth =
100 Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
101 if (!CatMeth->hasAttr<AvailabilityAttr>())
107 Sema::ShouldDiagnoseAvailabilityOfDecl(NamedDecl *&D, std::string *Message) {
108 AvailabilityResult Result = D->getAvailability(Message);
110 // For typedefs, if the typedef declaration appears available look
111 // to the underlying type to see if it is more restrictive.
112 while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
113 if (Result == AR_Available) {
114 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
116 Result = D->getAvailability(Message);
123 // Forward class declarations get their attributes from their definition.
124 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
125 if (IDecl->getDefinition()) {
126 D = IDecl->getDefinition();
127 Result = D->getAvailability(Message);
131 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
132 if (Result == AR_Available) {
133 const DeclContext *DC = ECD->getDeclContext();
134 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
135 Result = TheEnumDecl->getAvailability(Message);
138 if (Result == AR_NotYetIntroduced) {
139 // Don't do this for enums, they can't be redeclared.
140 if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
143 bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
144 // Objective-C method declarations in categories are not modelled as
145 // redeclarations, so manually look for a redeclaration in a category
147 if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
149 // In general, D will point to the most recent redeclaration. However,
150 // for `@class A;` decls, this isn't true -- manually go through the
151 // redecl chain in that case.
152 if (Warn && isa<ObjCInterfaceDecl>(D))
153 for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
154 Redecl = Redecl->getPreviousDecl())
155 if (!Redecl->hasAttr<AvailabilityAttr>() ||
156 Redecl->getAttr<AvailabilityAttr>()->isInherited())
159 return Warn ? AR_NotYetIntroduced : AR_Available;
166 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
167 const ObjCInterfaceDecl *UnknownObjCClass,
168 bool ObjCPropertyAccess) {
170 // See if this declaration is unavailable, deprecated, or partial.
171 if (AvailabilityResult Result =
172 S.ShouldDiagnoseAvailabilityOfDecl(D, &Message)) {
174 if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) {
175 S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
179 const ObjCPropertyDecl *ObjCPDecl = nullptr;
180 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
181 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
182 AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
183 if (PDeclResult == Result)
188 S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
189 ObjCPDecl, ObjCPropertyAccess);
193 /// \brief Emit a note explaining that this function is deleted.
194 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
195 assert(Decl->isDeleted());
197 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
199 if (Method && Method->isDeleted() && Method->isDefaulted()) {
200 // If the method was explicitly defaulted, point at that declaration.
201 if (!Method->isImplicit())
202 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
204 // Try to diagnose why this special member function was implicitly
205 // deleted. This might fail, if that reason no longer applies.
206 CXXSpecialMember CSM = getSpecialMember(Method);
207 if (CSM != CXXInvalid)
208 ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
213 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
214 if (Ctor && Ctor->isInheritingConstructor())
215 return NoteDeletedInheritingConstructor(Ctor);
217 Diag(Decl->getLocation(), diag::note_availability_specified_here)
221 /// \brief Determine whether a FunctionDecl was ever declared with an
222 /// explicit storage class.
223 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
224 for (auto I : D->redecls()) {
225 if (I->getStorageClass() != SC_None)
231 /// \brief Check whether we're in an extern inline function and referring to a
232 /// variable or function with internal linkage (C11 6.7.4p3).
234 /// This is only a warning because we used to silently accept this code, but
235 /// in many cases it will not behave correctly. This is not enabled in C++ mode
236 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
237 /// and so while there may still be user mistakes, most of the time we can't
238 /// prove that there are errors.
239 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
241 SourceLocation Loc) {
242 // This is disabled under C++; there are too many ways for this to fire in
243 // contexts where the warning is a false positive, or where it is technically
244 // correct but benign.
245 if (S.getLangOpts().CPlusPlus)
248 // Check if this is an inlined function or method.
249 FunctionDecl *Current = S.getCurFunctionDecl();
252 if (!Current->isInlined())
254 if (!Current->isExternallyVisible())
257 // Check if the decl has internal linkage.
258 if (D->getFormalLinkage() != InternalLinkage)
261 // Downgrade from ExtWarn to Extension if
262 // (1) the supposedly external inline function is in the main file,
263 // and probably won't be included anywhere else.
264 // (2) the thing we're referencing is a pure function.
265 // (3) the thing we're referencing is another inline function.
266 // This last can give us false negatives, but it's better than warning on
267 // wrappers for simple C library functions.
268 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
269 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
270 if (!DowngradeWarning && UsedFn)
271 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
273 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
274 : diag::ext_internal_in_extern_inline)
275 << /*IsVar=*/!UsedFn << D;
277 S.MaybeSuggestAddingStaticToDecl(Current);
279 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
283 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
284 const FunctionDecl *First = Cur->getFirstDecl();
286 // Suggest "static" on the function, if possible.
287 if (!hasAnyExplicitStorageClass(First)) {
288 SourceLocation DeclBegin = First->getSourceRange().getBegin();
289 Diag(DeclBegin, diag::note_convert_inline_to_static)
290 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
294 /// \brief Determine whether the use of this declaration is valid, and
295 /// emit any corresponding diagnostics.
297 /// This routine diagnoses various problems with referencing
298 /// declarations that can occur when using a declaration. For example,
299 /// it might warn if a deprecated or unavailable declaration is being
300 /// used, or produce an error (and return true) if a C++0x deleted
301 /// function is being used.
303 /// \returns true if there was an error (this declaration cannot be
304 /// referenced), false otherwise.
306 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
307 const ObjCInterfaceDecl *UnknownObjCClass,
308 bool ObjCPropertyAccess) {
309 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
310 // If there were any diagnostics suppressed by template argument deduction,
312 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
313 if (Pos != SuppressedDiagnostics.end()) {
314 for (const PartialDiagnosticAt &Suppressed : Pos->second)
315 Diag(Suppressed.first, Suppressed.second);
317 // Clear out the list of suppressed diagnostics, so that we don't emit
318 // them again for this specialization. However, we don't obsolete this
319 // entry from the table, because we want to avoid ever emitting these
320 // diagnostics again.
324 // C++ [basic.start.main]p3:
325 // The function 'main' shall not be used within a program.
326 if (cast<FunctionDecl>(D)->isMain())
327 Diag(Loc, diag::ext_main_used);
330 // See if this is an auto-typed variable whose initializer we are parsing.
331 if (ParsingInitForAutoVars.count(D)) {
332 if (isa<BindingDecl>(D)) {
333 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
336 const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
338 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
339 << D->getDeclName() << (unsigned)AT->getKeyword();
344 // See if this is a deleted function.
345 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
346 if (FD->isDeleted()) {
347 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
348 if (Ctor && Ctor->isInheritingConstructor())
349 Diag(Loc, diag::err_deleted_inherited_ctor_use)
351 << Ctor->getInheritedConstructor().getConstructor()->getParent();
353 Diag(Loc, diag::err_deleted_function_use);
354 NoteDeletedFunction(FD);
358 // If the function has a deduced return type, and we can't deduce it,
359 // then we can't use it either.
360 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
361 DeduceReturnType(FD, Loc))
364 if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
367 if (diagnoseArgIndependentDiagnoseIfAttrs(FD, Loc))
371 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
372 // Only the variables omp_in and omp_out are allowed in the combiner.
373 // Only the variables omp_priv and omp_orig are allowed in the
374 // initializer-clause.
375 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
376 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
378 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
379 << getCurFunction()->HasOMPDeclareReductionCombiner;
380 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
384 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
387 DiagnoseUnusedOfDecl(*this, D, Loc);
389 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
394 /// \brief Retrieve the message suffix that should be added to a
395 /// diagnostic complaining about the given function being deleted or
397 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
399 if (FD->getAvailability(&Message))
400 return ": " + Message;
402 return std::string();
405 /// DiagnoseSentinelCalls - This routine checks whether a call or
406 /// message-send is to a declaration with the sentinel attribute, and
407 /// if so, it checks that the requirements of the sentinel are
409 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
410 ArrayRef<Expr *> Args) {
411 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
415 // The number of formal parameters of the declaration.
416 unsigned numFormalParams;
418 // The kind of declaration. This is also an index into a %select in
420 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
422 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
423 numFormalParams = MD->param_size();
424 calleeType = CT_Method;
425 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
426 numFormalParams = FD->param_size();
427 calleeType = CT_Function;
428 } else if (isa<VarDecl>(D)) {
429 QualType type = cast<ValueDecl>(D)->getType();
430 const FunctionType *fn = nullptr;
431 if (const PointerType *ptr = type->getAs<PointerType>()) {
432 fn = ptr->getPointeeType()->getAs<FunctionType>();
434 calleeType = CT_Function;
435 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
436 fn = ptr->getPointeeType()->castAs<FunctionType>();
437 calleeType = CT_Block;
442 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
443 numFormalParams = proto->getNumParams();
451 // "nullPos" is the number of formal parameters at the end which
452 // effectively count as part of the variadic arguments. This is
453 // useful if you would prefer to not have *any* formal parameters,
454 // but the language forces you to have at least one.
455 unsigned nullPos = attr->getNullPos();
456 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
457 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
459 // The number of arguments which should follow the sentinel.
460 unsigned numArgsAfterSentinel = attr->getSentinel();
462 // If there aren't enough arguments for all the formal parameters,
463 // the sentinel, and the args after the sentinel, complain.
464 if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
465 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
466 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
470 // Otherwise, find the sentinel expression.
471 Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
472 if (!sentinelExpr) return;
473 if (sentinelExpr->isValueDependent()) return;
474 if (Context.isSentinelNullExpr(sentinelExpr)) return;
476 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
477 // or 'NULL' if those are actually defined in the context. Only use
478 // 'nil' for ObjC methods, where it's much more likely that the
479 // variadic arguments form a list of object pointers.
480 SourceLocation MissingNilLoc
481 = getLocForEndOfToken(sentinelExpr->getLocEnd());
482 std::string NullValue;
483 if (calleeType == CT_Method && PP.isMacroDefined("nil"))
485 else if (getLangOpts().CPlusPlus11)
486 NullValue = "nullptr";
487 else if (PP.isMacroDefined("NULL"))
490 NullValue = "(void*) 0";
492 if (MissingNilLoc.isInvalid())
493 Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
495 Diag(MissingNilLoc, diag::warn_missing_sentinel)
497 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
498 Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
501 SourceRange Sema::getExprRange(Expr *E) const {
502 return E ? E->getSourceRange() : SourceRange();
505 //===----------------------------------------------------------------------===//
506 // Standard Promotions and Conversions
507 //===----------------------------------------------------------------------===//
509 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
510 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
511 // Handle any placeholder expressions which made it here.
512 if (E->getType()->isPlaceholderType()) {
513 ExprResult result = CheckPlaceholderExpr(E);
514 if (result.isInvalid()) return ExprError();
518 QualType Ty = E->getType();
519 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
521 if (Ty->isFunctionType()) {
522 // If we are here, we are not calling a function but taking
523 // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
524 if (getLangOpts().OpenCL) {
526 Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
530 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
531 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
532 if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
535 E = ImpCastExprToType(E, Context.getPointerType(Ty),
536 CK_FunctionToPointerDecay).get();
537 } else if (Ty->isArrayType()) {
538 // In C90 mode, arrays only promote to pointers if the array expression is
539 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
540 // type 'array of type' is converted to an expression that has type 'pointer
541 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
542 // that has type 'array of type' ...". The relevant change is "an lvalue"
543 // (C90) to "an expression" (C99).
546 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
547 // T" can be converted to an rvalue of type "pointer to T".
549 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
550 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
551 CK_ArrayToPointerDecay).get();
556 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
557 // Check to see if we are dereferencing a null pointer. If so,
558 // and if not volatile-qualified, this is undefined behavior that the
559 // optimizer will delete, so warn about it. People sometimes try to use this
560 // to get a deterministic trap and are surprised by clang's behavior. This
561 // only handles the pattern "*null", which is a very syntactic check.
562 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
563 if (UO->getOpcode() == UO_Deref &&
564 UO->getSubExpr()->IgnoreParenCasts()->
565 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
566 !UO->getType().isVolatileQualified()) {
567 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
568 S.PDiag(diag::warn_indirection_through_null)
569 << UO->getSubExpr()->getSourceRange());
570 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
571 S.PDiag(diag::note_indirection_through_null));
575 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
576 SourceLocation AssignLoc,
578 const ObjCIvarDecl *IV = OIRE->getDecl();
582 DeclarationName MemberName = IV->getDeclName();
583 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
584 if (!Member || !Member->isStr("isa"))
587 const Expr *Base = OIRE->getBase();
588 QualType BaseType = Base->getType();
590 BaseType = BaseType->getPointeeType();
591 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
592 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
593 ObjCInterfaceDecl *ClassDeclared = nullptr;
594 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
595 if (!ClassDeclared->getSuperClass()
596 && (*ClassDeclared->ivar_begin()) == IV) {
598 NamedDecl *ObjectSetClass =
599 S.LookupSingleName(S.TUScope,
600 &S.Context.Idents.get("object_setClass"),
601 SourceLocation(), S.LookupOrdinaryName);
602 if (ObjectSetClass) {
603 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
604 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
605 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
606 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
608 FixItHint::CreateInsertion(RHSLocEnd, ")");
611 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
613 NamedDecl *ObjectGetClass =
614 S.LookupSingleName(S.TUScope,
615 &S.Context.Idents.get("object_getClass"),
616 SourceLocation(), S.LookupOrdinaryName);
618 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
619 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
620 FixItHint::CreateReplacement(
621 SourceRange(OIRE->getOpLoc(),
622 OIRE->getLocEnd()), ")");
624 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
626 S.Diag(IV->getLocation(), diag::note_ivar_decl);
631 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
632 // Handle any placeholder expressions which made it here.
633 if (E->getType()->isPlaceholderType()) {
634 ExprResult result = CheckPlaceholderExpr(E);
635 if (result.isInvalid()) return ExprError();
639 // C++ [conv.lval]p1:
640 // A glvalue of a non-function, non-array type T can be
641 // converted to a prvalue.
642 if (!E->isGLValue()) return E;
644 QualType T = E->getType();
645 assert(!T.isNull() && "r-value conversion on typeless expression?");
647 // We don't want to throw lvalue-to-rvalue casts on top of
648 // expressions of certain types in C++.
649 if (getLangOpts().CPlusPlus &&
650 (E->getType() == Context.OverloadTy ||
651 T->isDependentType() ||
655 // The C standard is actually really unclear on this point, and
656 // DR106 tells us what the result should be but not why. It's
657 // generally best to say that void types just doesn't undergo
658 // lvalue-to-rvalue at all. Note that expressions of unqualified
659 // 'void' type are never l-values, but qualified void can be.
663 // OpenCL usually rejects direct accesses to values of 'half' type.
664 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
666 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
671 CheckForNullPointerDereference(*this, E);
672 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
673 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
674 &Context.Idents.get("object_getClass"),
675 SourceLocation(), LookupOrdinaryName);
677 Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
678 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
679 FixItHint::CreateReplacement(
680 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
682 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
684 else if (const ObjCIvarRefExpr *OIRE =
685 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
686 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
688 // C++ [conv.lval]p1:
689 // [...] If T is a non-class type, the type of the prvalue is the
690 // cv-unqualified version of T. Otherwise, the type of the
694 // If the lvalue has qualified type, the value has the unqualified
695 // version of the type of the lvalue; otherwise, the value has the
696 // type of the lvalue.
697 if (T.hasQualifiers())
698 T = T.getUnqualifiedType();
700 // Under the MS ABI, lock down the inheritance model now.
701 if (T->isMemberPointerType() &&
702 Context.getTargetInfo().getCXXABI().isMicrosoft())
703 (void)isCompleteType(E->getExprLoc(), T);
705 UpdateMarkingForLValueToRValue(E);
707 // Loading a __weak object implicitly retains the value, so we need a cleanup to
709 if (getLangOpts().ObjCAutoRefCount &&
710 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
711 Cleanup.setExprNeedsCleanups(true);
713 ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
717 // ... if the lvalue has atomic type, the value has the non-atomic version
718 // of the type of the lvalue ...
719 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
720 T = Atomic->getValueType().getUnqualifiedType();
721 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
728 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
729 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
732 Res = DefaultLvalueConversion(Res.get());
738 /// CallExprUnaryConversions - a special case of an unary conversion
739 /// performed on a function designator of a call expression.
740 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
741 QualType Ty = E->getType();
743 // Only do implicit cast for a function type, but not for a pointer
745 if (Ty->isFunctionType()) {
746 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
747 CK_FunctionToPointerDecay).get();
751 Res = DefaultLvalueConversion(Res.get());
757 /// UsualUnaryConversions - Performs various conversions that are common to most
758 /// operators (C99 6.3). The conversions of array and function types are
759 /// sometimes suppressed. For example, the array->pointer conversion doesn't
760 /// apply if the array is an argument to the sizeof or address (&) operators.
761 /// In these instances, this routine should *not* be called.
762 ExprResult Sema::UsualUnaryConversions(Expr *E) {
763 // First, convert to an r-value.
764 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
769 QualType Ty = E->getType();
770 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
772 // Half FP have to be promoted to float unless it is natively supported
773 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
774 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
776 // Try to perform integral promotions if the object has a theoretically
778 if (Ty->isIntegralOrUnscopedEnumerationType()) {
781 // The following may be used in an expression wherever an int or
782 // unsigned int may be used:
783 // - an object or expression with an integer type whose integer
784 // conversion rank is less than or equal to the rank of int
786 // - A bit-field of type _Bool, int, signed int, or unsigned int.
788 // If an int can represent all values of the original type, the
789 // value is converted to an int; otherwise, it is converted to an
790 // unsigned int. These are called the integer promotions. All
791 // other types are unchanged by the integer promotions.
793 QualType PTy = Context.isPromotableBitField(E);
795 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
798 if (Ty->isPromotableIntegerType()) {
799 QualType PT = Context.getPromotedIntegerType(Ty);
800 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
807 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
808 /// do not have a prototype. Arguments that have type float or __fp16
809 /// are promoted to double. All other argument types are converted by
810 /// UsualUnaryConversions().
811 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
812 QualType Ty = E->getType();
813 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
815 ExprResult Res = UsualUnaryConversions(E);
820 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
822 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
823 if (BTy && (BTy->getKind() == BuiltinType::Half ||
824 BTy->getKind() == BuiltinType::Float)) {
825 if (getLangOpts().OpenCL &&
826 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
827 if (BTy->getKind() == BuiltinType::Half) {
828 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
831 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
835 // C++ performs lvalue-to-rvalue conversion as a default argument
836 // promotion, even on class types, but note:
837 // C++11 [conv.lval]p2:
838 // When an lvalue-to-rvalue conversion occurs in an unevaluated
839 // operand or a subexpression thereof the value contained in the
840 // referenced object is not accessed. Otherwise, if the glvalue
841 // has a class type, the conversion copy-initializes a temporary
842 // of type T from the glvalue and the result of the conversion
843 // is a prvalue for the temporary.
844 // FIXME: add some way to gate this entire thing for correctness in
845 // potentially potentially evaluated contexts.
846 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
847 ExprResult Temp = PerformCopyInitialization(
848 InitializedEntity::InitializeTemporary(E->getType()),
850 if (Temp.isInvalid())
858 /// Determine the degree of POD-ness for an expression.
859 /// Incomplete types are considered POD, since this check can be performed
860 /// when we're in an unevaluated context.
861 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
862 if (Ty->isIncompleteType()) {
863 // C++11 [expr.call]p7:
864 // After these conversions, if the argument does not have arithmetic,
865 // enumeration, pointer, pointer to member, or class type, the program
868 // Since we've already performed array-to-pointer and function-to-pointer
869 // decay, the only such type in C++ is cv void. This also handles
870 // initializer lists as variadic arguments.
871 if (Ty->isVoidType())
874 if (Ty->isObjCObjectType())
879 if (Ty.isCXX98PODType(Context))
882 // C++11 [expr.call]p7:
883 // Passing a potentially-evaluated argument of class type (Clause 9)
884 // having a non-trivial copy constructor, a non-trivial move constructor,
885 // or a non-trivial destructor, with no corresponding parameter,
886 // is conditionally-supported with implementation-defined semantics.
887 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
888 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
889 if (!Record->hasNonTrivialCopyConstructor() &&
890 !Record->hasNonTrivialMoveConstructor() &&
891 !Record->hasNonTrivialDestructor())
892 return VAK_ValidInCXX11;
894 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
897 if (Ty->isObjCObjectType())
900 if (getLangOpts().MSVCCompat)
901 return VAK_MSVCUndefined;
903 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
904 // permitted to reject them. We should consider doing so.
905 return VAK_Undefined;
908 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
909 // Don't allow one to pass an Objective-C interface to a vararg.
910 const QualType &Ty = E->getType();
911 VarArgKind VAK = isValidVarArgType(Ty);
913 // Complain about passing non-POD types through varargs.
915 case VAK_ValidInCXX11:
917 E->getLocStart(), nullptr,
918 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
922 if (Ty->isRecordType()) {
923 // This is unlikely to be what the user intended. If the class has a
924 // 'c_str' member function, the user probably meant to call that.
925 DiagRuntimeBehavior(E->getLocStart(), nullptr,
926 PDiag(diag::warn_pass_class_arg_to_vararg)
927 << Ty << CT << hasCStrMethod(E) << ".c_str()");
932 case VAK_MSVCUndefined:
934 E->getLocStart(), nullptr,
935 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
936 << getLangOpts().CPlusPlus11 << Ty << CT);
940 if (Ty->isObjCObjectType())
942 E->getLocStart(), nullptr,
943 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
946 Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
947 << isa<InitListExpr>(E) << Ty << CT;
952 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
953 /// will create a trap if the resulting type is not a POD type.
954 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
955 FunctionDecl *FDecl) {
956 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
957 // Strip the unbridged-cast placeholder expression off, if applicable.
958 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
959 (CT == VariadicMethod ||
960 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
961 E = stripARCUnbridgedCast(E);
963 // Otherwise, do normal placeholder checking.
965 ExprResult ExprRes = CheckPlaceholderExpr(E);
966 if (ExprRes.isInvalid())
972 ExprResult ExprRes = DefaultArgumentPromotion(E);
973 if (ExprRes.isInvalid())
977 // Diagnostics regarding non-POD argument types are
978 // emitted along with format string checking in Sema::CheckFunctionCall().
979 if (isValidVarArgType(E->getType()) == VAK_Undefined) {
980 // Turn this into a trap.
982 SourceLocation TemplateKWLoc;
984 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
986 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
988 if (TrapFn.isInvalid())
991 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
992 E->getLocStart(), None,
994 if (Call.isInvalid())
997 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
999 if (Comma.isInvalid())
1004 if (!getLangOpts().CPlusPlus &&
1005 RequireCompleteType(E->getExprLoc(), E->getType(),
1006 diag::err_call_incomplete_argument))
1012 /// \brief Converts an integer to complex float type. Helper function of
1013 /// UsualArithmeticConversions()
1015 /// \return false if the integer expression is an integer type and is
1016 /// successfully converted to the complex type.
1017 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1018 ExprResult &ComplexExpr,
1022 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1023 if (SkipCast) return false;
1024 if (IntTy->isIntegerType()) {
1025 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1026 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1027 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1028 CK_FloatingRealToComplex);
1030 assert(IntTy->isComplexIntegerType());
1031 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1032 CK_IntegralComplexToFloatingComplex);
1037 /// \brief Handle arithmetic conversion with complex types. Helper function of
1038 /// UsualArithmeticConversions()
1039 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1040 ExprResult &RHS, QualType LHSType,
1042 bool IsCompAssign) {
1043 // if we have an integer operand, the result is the complex type.
1044 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1047 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1048 /*skipCast*/IsCompAssign))
1051 // This handles complex/complex, complex/float, or float/complex.
1052 // When both operands are complex, the shorter operand is converted to the
1053 // type of the longer, and that is the type of the result. This corresponds
1054 // to what is done when combining two real floating-point operands.
1055 // The fun begins when size promotion occur across type domains.
1056 // From H&S 6.3.4: When one operand is complex and the other is a real
1057 // floating-point type, the less precise type is converted, within it's
1058 // real or complex domain, to the precision of the other type. For example,
1059 // when combining a "long double" with a "double _Complex", the
1060 // "double _Complex" is promoted to "long double _Complex".
1062 // Compute the rank of the two types, regardless of whether they are complex.
1063 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1065 auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1066 auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1067 QualType LHSElementType =
1068 LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1069 QualType RHSElementType =
1070 RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1072 QualType ResultType = S.Context.getComplexType(LHSElementType);
1074 // Promote the precision of the LHS if not an assignment.
1075 ResultType = S.Context.getComplexType(RHSElementType);
1076 if (!IsCompAssign) {
1079 S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1081 LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1083 } else if (Order > 0) {
1084 // Promote the precision of the RHS.
1086 RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1088 RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1093 /// \brief Hande arithmetic conversion from integer to float. Helper function
1094 /// of UsualArithmeticConversions()
1095 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1096 ExprResult &IntExpr,
1097 QualType FloatTy, QualType IntTy,
1098 bool ConvertFloat, bool ConvertInt) {
1099 if (IntTy->isIntegerType()) {
1101 // Convert intExpr to the lhs floating point type.
1102 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1103 CK_IntegralToFloating);
1107 // Convert both sides to the appropriate complex float.
1108 assert(IntTy->isComplexIntegerType());
1109 QualType result = S.Context.getComplexType(FloatTy);
1111 // _Complex int -> _Complex float
1113 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1114 CK_IntegralComplexToFloatingComplex);
1116 // float -> _Complex float
1118 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1119 CK_FloatingRealToComplex);
1124 /// \brief Handle arithmethic conversion with floating point types. Helper
1125 /// function of UsualArithmeticConversions()
1126 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1127 ExprResult &RHS, QualType LHSType,
1128 QualType RHSType, bool IsCompAssign) {
1129 bool LHSFloat = LHSType->isRealFloatingType();
1130 bool RHSFloat = RHSType->isRealFloatingType();
1132 // If we have two real floating types, convert the smaller operand
1133 // to the bigger result.
1134 if (LHSFloat && RHSFloat) {
1135 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1137 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1141 assert(order < 0 && "illegal float comparison");
1143 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1148 // Half FP has to be promoted to float unless it is natively supported
1149 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1150 LHSType = S.Context.FloatTy;
1152 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1153 /*convertFloat=*/!IsCompAssign,
1154 /*convertInt=*/ true);
1157 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1158 /*convertInt=*/ true,
1159 /*convertFloat=*/!IsCompAssign);
1162 /// \brief Diagnose attempts to convert between __float128 and long double if
1163 /// there is no support for such conversion. Helper function of
1164 /// UsualArithmeticConversions().
1165 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1167 /* No issue converting if at least one of the types is not a floating point
1168 type or the two types have the same rank.
1170 if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1171 S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1174 assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1175 "The remaining types must be floating point types.");
1177 auto *LHSComplex = LHSType->getAs<ComplexType>();
1178 auto *RHSComplex = RHSType->getAs<ComplexType>();
1180 QualType LHSElemType = LHSComplex ?
1181 LHSComplex->getElementType() : LHSType;
1182 QualType RHSElemType = RHSComplex ?
1183 RHSComplex->getElementType() : RHSType;
1185 // No issue if the two types have the same representation
1186 if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1187 &S.Context.getFloatTypeSemantics(RHSElemType))
1190 bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1191 RHSElemType == S.Context.LongDoubleTy);
1192 Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1193 RHSElemType == S.Context.Float128Ty);
1195 /* We've handled the situation where __float128 and long double have the same
1196 representation. The only other allowable conversion is if long double is
1199 return Float128AndLongDouble &&
1200 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1201 &llvm::APFloat::IEEEdouble());
1204 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1207 /// These helper callbacks are placed in an anonymous namespace to
1208 /// permit their use as function template parameters.
1209 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1210 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1213 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1214 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1215 CK_IntegralComplexCast);
1219 /// \brief Handle integer arithmetic conversions. Helper function of
1220 /// UsualArithmeticConversions()
1221 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1222 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1223 ExprResult &RHS, QualType LHSType,
1224 QualType RHSType, bool IsCompAssign) {
1225 // The rules for this case are in C99 6.3.1.8
1226 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1227 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1228 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1229 if (LHSSigned == RHSSigned) {
1230 // Same signedness; use the higher-ranked type
1232 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1234 } else if (!IsCompAssign)
1235 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1237 } else if (order != (LHSSigned ? 1 : -1)) {
1238 // The unsigned type has greater than or equal rank to the
1239 // signed type, so use the unsigned type
1241 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1243 } else if (!IsCompAssign)
1244 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1246 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1247 // The two types are different widths; if we are here, that
1248 // means the signed type is larger than the unsigned type, so
1249 // use the signed type.
1251 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1253 } else if (!IsCompAssign)
1254 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1257 // The signed type is higher-ranked than the unsigned type,
1258 // but isn't actually any bigger (like unsigned int and long
1259 // on most 32-bit systems). Use the unsigned type corresponding
1260 // to the signed type.
1262 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1263 RHS = (*doRHSCast)(S, RHS.get(), result);
1265 LHS = (*doLHSCast)(S, LHS.get(), result);
1270 /// \brief Handle conversions with GCC complex int extension. Helper function
1271 /// of UsualArithmeticConversions()
1272 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1273 ExprResult &RHS, QualType LHSType,
1275 bool IsCompAssign) {
1276 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1277 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1279 if (LHSComplexInt && RHSComplexInt) {
1280 QualType LHSEltType = LHSComplexInt->getElementType();
1281 QualType RHSEltType = RHSComplexInt->getElementType();
1282 QualType ScalarType =
1283 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1284 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1286 return S.Context.getComplexType(ScalarType);
1289 if (LHSComplexInt) {
1290 QualType LHSEltType = LHSComplexInt->getElementType();
1291 QualType ScalarType =
1292 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1293 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1294 QualType ComplexType = S.Context.getComplexType(ScalarType);
1295 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1296 CK_IntegralRealToComplex);
1301 assert(RHSComplexInt);
1303 QualType RHSEltType = RHSComplexInt->getElementType();
1304 QualType ScalarType =
1305 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1306 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1307 QualType ComplexType = S.Context.getComplexType(ScalarType);
1310 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1311 CK_IntegralRealToComplex);
1315 /// UsualArithmeticConversions - Performs various conversions that are common to
1316 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1317 /// routine returns the first non-arithmetic type found. The client is
1318 /// responsible for emitting appropriate error diagnostics.
1319 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1320 bool IsCompAssign) {
1321 if (!IsCompAssign) {
1322 LHS = UsualUnaryConversions(LHS.get());
1323 if (LHS.isInvalid())
1327 RHS = UsualUnaryConversions(RHS.get());
1328 if (RHS.isInvalid())
1331 // For conversion purposes, we ignore any qualifiers.
1332 // For example, "const float" and "float" are equivalent.
1334 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1336 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1338 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1339 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1340 LHSType = AtomicLHS->getValueType();
1342 // If both types are identical, no conversion is needed.
1343 if (LHSType == RHSType)
1346 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1347 // The caller can deal with this (e.g. pointer + int).
1348 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1351 // Apply unary and bitfield promotions to the LHS's type.
1352 QualType LHSUnpromotedType = LHSType;
1353 if (LHSType->isPromotableIntegerType())
1354 LHSType = Context.getPromotedIntegerType(LHSType);
1355 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1356 if (!LHSBitfieldPromoteTy.isNull())
1357 LHSType = LHSBitfieldPromoteTy;
1358 if (LHSType != LHSUnpromotedType && !IsCompAssign)
1359 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1361 // If both types are identical, no conversion is needed.
1362 if (LHSType == RHSType)
1365 // At this point, we have two different arithmetic types.
1367 // Diagnose attempts to convert between __float128 and long double where
1368 // such conversions currently can't be handled.
1369 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1372 // Handle complex types first (C99 6.3.1.8p1).
1373 if (LHSType->isComplexType() || RHSType->isComplexType())
1374 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1377 // Now handle "real" floating types (i.e. float, double, long double).
1378 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1379 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1382 // Handle GCC complex int extension.
1383 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1384 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1387 // Finally, we have two differing integer types.
1388 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1389 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1393 //===----------------------------------------------------------------------===//
1394 // Semantic Analysis for various Expression Types
1395 //===----------------------------------------------------------------------===//
1399 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1400 SourceLocation DefaultLoc,
1401 SourceLocation RParenLoc,
1402 Expr *ControllingExpr,
1403 ArrayRef<ParsedType> ArgTypes,
1404 ArrayRef<Expr *> ArgExprs) {
1405 unsigned NumAssocs = ArgTypes.size();
1406 assert(NumAssocs == ArgExprs.size());
1408 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1409 for (unsigned i = 0; i < NumAssocs; ++i) {
1411 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1416 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1418 llvm::makeArrayRef(Types, NumAssocs),
1425 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1426 SourceLocation DefaultLoc,
1427 SourceLocation RParenLoc,
1428 Expr *ControllingExpr,
1429 ArrayRef<TypeSourceInfo *> Types,
1430 ArrayRef<Expr *> Exprs) {
1431 unsigned NumAssocs = Types.size();
1432 assert(NumAssocs == Exprs.size());
1434 // Decay and strip qualifiers for the controlling expression type, and handle
1435 // placeholder type replacement. See committee discussion from WG14 DR423.
1437 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1438 ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1441 ControllingExpr = R.get();
1444 // The controlling expression is an unevaluated operand, so side effects are
1445 // likely unintended.
1446 if (ActiveTemplateInstantiations.empty() &&
1447 ControllingExpr->HasSideEffects(Context, false))
1448 Diag(ControllingExpr->getExprLoc(),
1449 diag::warn_side_effects_unevaluated_context);
1451 bool TypeErrorFound = false,
1452 IsResultDependent = ControllingExpr->isTypeDependent(),
1453 ContainsUnexpandedParameterPack
1454 = ControllingExpr->containsUnexpandedParameterPack();
1456 for (unsigned i = 0; i < NumAssocs; ++i) {
1457 if (Exprs[i]->containsUnexpandedParameterPack())
1458 ContainsUnexpandedParameterPack = true;
1461 if (Types[i]->getType()->containsUnexpandedParameterPack())
1462 ContainsUnexpandedParameterPack = true;
1464 if (Types[i]->getType()->isDependentType()) {
1465 IsResultDependent = true;
1467 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1468 // complete object type other than a variably modified type."
1470 if (Types[i]->getType()->isIncompleteType())
1471 D = diag::err_assoc_type_incomplete;
1472 else if (!Types[i]->getType()->isObjectType())
1473 D = diag::err_assoc_type_nonobject;
1474 else if (Types[i]->getType()->isVariablyModifiedType())
1475 D = diag::err_assoc_type_variably_modified;
1478 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1479 << Types[i]->getTypeLoc().getSourceRange()
1480 << Types[i]->getType();
1481 TypeErrorFound = true;
1484 // C11 6.5.1.1p2 "No two generic associations in the same generic
1485 // selection shall specify compatible types."
1486 for (unsigned j = i+1; j < NumAssocs; ++j)
1487 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1488 Context.typesAreCompatible(Types[i]->getType(),
1489 Types[j]->getType())) {
1490 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1491 diag::err_assoc_compatible_types)
1492 << Types[j]->getTypeLoc().getSourceRange()
1493 << Types[j]->getType()
1494 << Types[i]->getType();
1495 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1496 diag::note_compat_assoc)
1497 << Types[i]->getTypeLoc().getSourceRange()
1498 << Types[i]->getType();
1499 TypeErrorFound = true;
1507 // If we determined that the generic selection is result-dependent, don't
1508 // try to compute the result expression.
1509 if (IsResultDependent)
1510 return new (Context) GenericSelectionExpr(
1511 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1512 ContainsUnexpandedParameterPack);
1514 SmallVector<unsigned, 1> CompatIndices;
1515 unsigned DefaultIndex = -1U;
1516 for (unsigned i = 0; i < NumAssocs; ++i) {
1519 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1520 Types[i]->getType()))
1521 CompatIndices.push_back(i);
1524 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1525 // type compatible with at most one of the types named in its generic
1526 // association list."
1527 if (CompatIndices.size() > 1) {
1528 // We strip parens here because the controlling expression is typically
1529 // parenthesized in macro definitions.
1530 ControllingExpr = ControllingExpr->IgnoreParens();
1531 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1532 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1533 << (unsigned) CompatIndices.size();
1534 for (unsigned I : CompatIndices) {
1535 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1536 diag::note_compat_assoc)
1537 << Types[I]->getTypeLoc().getSourceRange()
1538 << Types[I]->getType();
1543 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1544 // its controlling expression shall have type compatible with exactly one of
1545 // the types named in its generic association list."
1546 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1547 // We strip parens here because the controlling expression is typically
1548 // parenthesized in macro definitions.
1549 ControllingExpr = ControllingExpr->IgnoreParens();
1550 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1551 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1555 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1556 // type name that is compatible with the type of the controlling expression,
1557 // then the result expression of the generic selection is the expression
1558 // in that generic association. Otherwise, the result expression of the
1559 // generic selection is the expression in the default generic association."
1560 unsigned ResultIndex =
1561 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1563 return new (Context) GenericSelectionExpr(
1564 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1565 ContainsUnexpandedParameterPack, ResultIndex);
1568 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1569 /// location of the token and the offset of the ud-suffix within it.
1570 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1572 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1576 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1577 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1578 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1579 IdentifierInfo *UDSuffix,
1580 SourceLocation UDSuffixLoc,
1581 ArrayRef<Expr*> Args,
1582 SourceLocation LitEndLoc) {
1583 assert(Args.size() <= 2 && "too many arguments for literal operator");
1586 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1587 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1588 if (ArgTy[ArgIdx]->isArrayType())
1589 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1592 DeclarationName OpName =
1593 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1594 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1595 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1597 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1598 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1599 /*AllowRaw*/false, /*AllowTemplate*/false,
1600 /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1603 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1606 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1607 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1608 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1609 /// multiple tokens. However, the common case is that StringToks points to one
1613 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1614 assert(!StringToks.empty() && "Must have at least one string!");
1616 StringLiteralParser Literal(StringToks, PP);
1617 if (Literal.hadError)
1620 SmallVector<SourceLocation, 4> StringTokLocs;
1621 for (const Token &Tok : StringToks)
1622 StringTokLocs.push_back(Tok.getLocation());
1624 QualType CharTy = Context.CharTy;
1625 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1626 if (Literal.isWide()) {
1627 CharTy = Context.getWideCharType();
1628 Kind = StringLiteral::Wide;
1629 } else if (Literal.isUTF8()) {
1630 Kind = StringLiteral::UTF8;
1631 } else if (Literal.isUTF16()) {
1632 CharTy = Context.Char16Ty;
1633 Kind = StringLiteral::UTF16;
1634 } else if (Literal.isUTF32()) {
1635 CharTy = Context.Char32Ty;
1636 Kind = StringLiteral::UTF32;
1637 } else if (Literal.isPascal()) {
1638 CharTy = Context.UnsignedCharTy;
1641 QualType CharTyConst = CharTy;
1642 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1643 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1644 CharTyConst.addConst();
1646 // Get an array type for the string, according to C99 6.4.5. This includes
1647 // the nul terminator character as well as the string length for pascal
1649 QualType StrTy = Context.getConstantArrayType(CharTyConst,
1650 llvm::APInt(32, Literal.GetNumStringChars()+1),
1651 ArrayType::Normal, 0);
1653 // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1654 if (getLangOpts().OpenCL) {
1655 StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1658 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1659 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1660 Kind, Literal.Pascal, StrTy,
1662 StringTokLocs.size());
1663 if (Literal.getUDSuffix().empty())
1666 // We're building a user-defined literal.
1667 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1668 SourceLocation UDSuffixLoc =
1669 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1670 Literal.getUDSuffixOffset());
1672 // Make sure we're allowed user-defined literals here.
1674 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1676 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1677 // operator "" X (str, len)
1678 QualType SizeType = Context.getSizeType();
1680 DeclarationName OpName =
1681 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1682 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1683 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1685 QualType ArgTy[] = {
1686 Context.getArrayDecayedType(StrTy), SizeType
1689 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1690 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1691 /*AllowRaw*/false, /*AllowTemplate*/false,
1692 /*AllowStringTemplate*/true)) {
1695 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1696 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1698 Expr *Args[] = { Lit, LenArg };
1700 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1703 case LOLR_StringTemplate: {
1704 TemplateArgumentListInfo ExplicitArgs;
1706 unsigned CharBits = Context.getIntWidth(CharTy);
1707 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1708 llvm::APSInt Value(CharBits, CharIsUnsigned);
1710 TemplateArgument TypeArg(CharTy);
1711 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1712 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1714 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1715 Value = Lit->getCodeUnit(I);
1716 TemplateArgument Arg(Context, Value, CharTy);
1717 TemplateArgumentLocInfo ArgInfo;
1718 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1720 return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1725 llvm_unreachable("unexpected literal operator lookup result");
1729 llvm_unreachable("unexpected literal operator lookup result");
1733 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1735 const CXXScopeSpec *SS) {
1736 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1737 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1740 /// BuildDeclRefExpr - Build an expression that references a
1741 /// declaration that does not require a closure capture.
1743 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1744 const DeclarationNameInfo &NameInfo,
1745 const CXXScopeSpec *SS, NamedDecl *FoundD,
1746 const TemplateArgumentListInfo *TemplateArgs) {
1747 bool RefersToCapturedVariable =
1749 NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1752 if (isa<VarTemplateSpecializationDecl>(D)) {
1753 VarTemplateSpecializationDecl *VarSpec =
1754 cast<VarTemplateSpecializationDecl>(D);
1756 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1757 : NestedNameSpecifierLoc(),
1758 VarSpec->getTemplateKeywordLoc(), D,
1759 RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1760 FoundD, TemplateArgs);
1762 assert(!TemplateArgs && "No template arguments for non-variable"
1763 " template specialization references");
1764 E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1765 : NestedNameSpecifierLoc(),
1766 SourceLocation(), D, RefersToCapturedVariable,
1767 NameInfo, Ty, VK, FoundD);
1770 MarkDeclRefReferenced(E);
1772 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1773 Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1774 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1775 recordUseOfEvaluatedWeak(E);
1777 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1778 UnusedPrivateFields.remove(FD);
1779 // Just in case we're building an illegal pointer-to-member.
1780 if (FD->isBitField())
1781 E->setObjectKind(OK_BitField);
1784 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1785 // designates a bit-field.
1786 if (auto *BD = dyn_cast<BindingDecl>(D))
1787 if (auto *BE = BD->getBinding())
1788 E->setObjectKind(BE->getObjectKind());
1793 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1794 /// possibly a list of template arguments.
1796 /// If this produces template arguments, it is permitted to call
1797 /// DecomposeTemplateName.
1799 /// This actually loses a lot of source location information for
1800 /// non-standard name kinds; we should consider preserving that in
1803 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1804 TemplateArgumentListInfo &Buffer,
1805 DeclarationNameInfo &NameInfo,
1806 const TemplateArgumentListInfo *&TemplateArgs) {
1807 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1808 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1809 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1811 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1812 Id.TemplateId->NumArgs);
1813 translateTemplateArguments(TemplateArgsPtr, Buffer);
1815 TemplateName TName = Id.TemplateId->Template.get();
1816 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1817 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1818 TemplateArgs = &Buffer;
1820 NameInfo = GetNameFromUnqualifiedId(Id);
1821 TemplateArgs = nullptr;
1825 static void emitEmptyLookupTypoDiagnostic(
1826 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1827 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1828 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1830 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1832 // Emit a special diagnostic for failed member lookups.
1833 // FIXME: computing the declaration context might fail here (?)
1835 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1838 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1842 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1843 bool DroppedSpecifier =
1844 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1845 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1846 ? diag::note_implicit_param_decl
1847 : diag::note_previous_decl;
1849 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1850 SemaRef.PDiag(NoteID));
1852 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1853 << Typo << Ctx << DroppedSpecifier
1855 SemaRef.PDiag(NoteID));
1858 /// Diagnose an empty lookup.
1860 /// \return false if new lookup candidates were found
1862 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1863 std::unique_ptr<CorrectionCandidateCallback> CCC,
1864 TemplateArgumentListInfo *ExplicitTemplateArgs,
1865 ArrayRef<Expr *> Args, TypoExpr **Out) {
1866 DeclarationName Name = R.getLookupName();
1868 unsigned diagnostic = diag::err_undeclared_var_use;
1869 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1870 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1871 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1872 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1873 diagnostic = diag::err_undeclared_use;
1874 diagnostic_suggest = diag::err_undeclared_use_suggest;
1877 // If the original lookup was an unqualified lookup, fake an
1878 // unqualified lookup. This is useful when (for example) the
1879 // original lookup would not have found something because it was a
1881 DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1883 if (isa<CXXRecordDecl>(DC)) {
1884 LookupQualifiedName(R, DC);
1887 // Don't give errors about ambiguities in this lookup.
1888 R.suppressDiagnostics();
1890 // During a default argument instantiation the CurContext points
1891 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1892 // function parameter list, hence add an explicit check.
1893 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1894 ActiveTemplateInstantiations.back().Kind ==
1895 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1896 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1897 bool isInstance = CurMethod &&
1898 CurMethod->isInstance() &&
1899 DC == CurMethod->getParent() && !isDefaultArgument;
1901 // Give a code modification hint to insert 'this->'.
1902 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1903 // Actually quite difficult!
1904 if (getLangOpts().MSVCCompat)
1905 diagnostic = diag::ext_found_via_dependent_bases_lookup;
1907 Diag(R.getNameLoc(), diagnostic) << Name
1908 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1909 CheckCXXThisCapture(R.getNameLoc());
1911 Diag(R.getNameLoc(), diagnostic) << Name;
1914 // Do we really want to note all of these?
1915 for (NamedDecl *D : R)
1916 Diag(D->getLocation(), diag::note_dependent_var_use);
1918 // Return true if we are inside a default argument instantiation
1919 // and the found name refers to an instance member function, otherwise
1920 // the function calling DiagnoseEmptyLookup will try to create an
1921 // implicit member call and this is wrong for default argument.
1922 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1923 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1927 // Tell the callee to try to recover.
1934 // In Microsoft mode, if we are performing lookup from within a friend
1935 // function definition declared at class scope then we must set
1936 // DC to the lexical parent to be able to search into the parent
1938 if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1939 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1940 DC->getLexicalParent()->isRecord())
1941 DC = DC->getLexicalParent();
1943 DC = DC->getParent();
1946 // We didn't find anything, so try to correct for a typo.
1947 TypoCorrection Corrected;
1949 SourceLocation TypoLoc = R.getNameLoc();
1950 assert(!ExplicitTemplateArgs &&
1951 "Diagnosing an empty lookup with explicit template args!");
1952 *Out = CorrectTypoDelayed(
1953 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1954 [=](const TypoCorrection &TC) {
1955 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1956 diagnostic, diagnostic_suggest);
1958 nullptr, CTK_ErrorRecovery);
1961 } else if (S && (Corrected =
1962 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1963 &SS, std::move(CCC), CTK_ErrorRecovery))) {
1964 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1965 bool DroppedSpecifier =
1966 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1967 R.setLookupName(Corrected.getCorrection());
1969 bool AcceptableWithRecovery = false;
1970 bool AcceptableWithoutRecovery = false;
1971 NamedDecl *ND = Corrected.getFoundDecl();
1973 if (Corrected.isOverloaded()) {
1974 OverloadCandidateSet OCS(R.getNameLoc(),
1975 OverloadCandidateSet::CSK_Normal);
1976 OverloadCandidateSet::iterator Best;
1977 for (NamedDecl *CD : Corrected) {
1978 if (FunctionTemplateDecl *FTD =
1979 dyn_cast<FunctionTemplateDecl>(CD))
1980 AddTemplateOverloadCandidate(
1981 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1983 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1984 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1985 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1988 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1990 ND = Best->FoundDecl;
1991 Corrected.setCorrectionDecl(ND);
1994 // FIXME: Arbitrarily pick the first declaration for the note.
1995 Corrected.setCorrectionDecl(ND);
2000 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2001 CXXRecordDecl *Record = nullptr;
2002 if (Corrected.getCorrectionSpecifier()) {
2003 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2004 Record = Ty->getAsCXXRecordDecl();
2007 Record = cast<CXXRecordDecl>(
2008 ND->getDeclContext()->getRedeclContext());
2009 R.setNamingClass(Record);
2012 auto *UnderlyingND = ND->getUnderlyingDecl();
2013 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2014 isa<FunctionTemplateDecl>(UnderlyingND);
2015 // FIXME: If we ended up with a typo for a type name or
2016 // Objective-C class name, we're in trouble because the parser
2017 // is in the wrong place to recover. Suggest the typo
2018 // correction, but don't make it a fix-it since we're not going
2019 // to recover well anyway.
2020 AcceptableWithoutRecovery =
2021 isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2023 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2024 // because we aren't able to recover.
2025 AcceptableWithoutRecovery = true;
2028 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2029 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2030 ? diag::note_implicit_param_decl
2031 : diag::note_previous_decl;
2033 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2034 PDiag(NoteID), AcceptableWithRecovery);
2036 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2037 << Name << computeDeclContext(SS, false)
2038 << DroppedSpecifier << SS.getRange(),
2039 PDiag(NoteID), AcceptableWithRecovery);
2041 // Tell the callee whether to try to recover.
2042 return !AcceptableWithRecovery;
2047 // Emit a special diagnostic for failed member lookups.
2048 // FIXME: computing the declaration context might fail here (?)
2049 if (!SS.isEmpty()) {
2050 Diag(R.getNameLoc(), diag::err_no_member)
2051 << Name << computeDeclContext(SS, false)
2056 // Give up, we can't recover.
2057 Diag(R.getNameLoc(), diagnostic) << Name;
2061 /// In Microsoft mode, if we are inside a template class whose parent class has
2062 /// dependent base classes, and we can't resolve an unqualified identifier, then
2063 /// assume the identifier is a member of a dependent base class. We can only
2064 /// recover successfully in static methods, instance methods, and other contexts
2065 /// where 'this' is available. This doesn't precisely match MSVC's
2066 /// instantiation model, but it's close enough.
2068 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2069 DeclarationNameInfo &NameInfo,
2070 SourceLocation TemplateKWLoc,
2071 const TemplateArgumentListInfo *TemplateArgs) {
2072 // Only try to recover from lookup into dependent bases in static methods or
2073 // contexts where 'this' is available.
2074 QualType ThisType = S.getCurrentThisType();
2075 const CXXRecordDecl *RD = nullptr;
2076 if (!ThisType.isNull())
2077 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2078 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2079 RD = MD->getParent();
2080 if (!RD || !RD->hasAnyDependentBases())
2083 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2084 // is available, suggest inserting 'this->' as a fixit.
2085 SourceLocation Loc = NameInfo.getLoc();
2086 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2087 DB << NameInfo.getName() << RD;
2089 if (!ThisType.isNull()) {
2090 DB << FixItHint::CreateInsertion(Loc, "this->");
2091 return CXXDependentScopeMemberExpr::Create(
2092 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2093 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2094 /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2097 // Synthesize a fake NNS that points to the derived class. This will
2098 // perform name lookup during template instantiation.
2101 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2102 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2103 return DependentScopeDeclRefExpr::Create(
2104 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2109 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2110 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2111 bool HasTrailingLParen, bool IsAddressOfOperand,
2112 std::unique_ptr<CorrectionCandidateCallback> CCC,
2113 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2114 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2115 "cannot be direct & operand and have a trailing lparen");
2119 TemplateArgumentListInfo TemplateArgsBuffer;
2121 // Decompose the UnqualifiedId into the following data.
2122 DeclarationNameInfo NameInfo;
2123 const TemplateArgumentListInfo *TemplateArgs;
2124 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2126 DeclarationName Name = NameInfo.getName();
2127 IdentifierInfo *II = Name.getAsIdentifierInfo();
2128 SourceLocation NameLoc = NameInfo.getLoc();
2130 // C++ [temp.dep.expr]p3:
2131 // An id-expression is type-dependent if it contains:
2132 // -- an identifier that was declared with a dependent type,
2133 // (note: handled after lookup)
2134 // -- a template-id that is dependent,
2135 // (note: handled in BuildTemplateIdExpr)
2136 // -- a conversion-function-id that specifies a dependent type,
2137 // -- a nested-name-specifier that contains a class-name that
2138 // names a dependent type.
2139 // Determine whether this is a member of an unknown specialization;
2140 // we need to handle these differently.
2141 bool DependentID = false;
2142 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2143 Name.getCXXNameType()->isDependentType()) {
2145 } else if (SS.isSet()) {
2146 if (DeclContext *DC = computeDeclContext(SS, false)) {
2147 if (RequireCompleteDeclContext(SS, DC))
2155 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2156 IsAddressOfOperand, TemplateArgs);
2158 // Perform the required lookup.
2159 LookupResult R(*this, NameInfo,
2160 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2161 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2163 // Lookup the template name again to correctly establish the context in
2164 // which it was found. This is really unfortunate as we already did the
2165 // lookup to determine that it was a template name in the first place. If
2166 // this becomes a performance hit, we can work harder to preserve those
2167 // results until we get here but it's likely not worth it.
2168 bool MemberOfUnknownSpecialization;
2169 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2170 MemberOfUnknownSpecialization);
2172 if (MemberOfUnknownSpecialization ||
2173 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2174 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2175 IsAddressOfOperand, TemplateArgs);
2177 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2178 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2180 // If the result might be in a dependent base class, this is a dependent
2182 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2183 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2184 IsAddressOfOperand, TemplateArgs);
2186 // If this reference is in an Objective-C method, then we need to do
2187 // some special Objective-C lookup, too.
2188 if (IvarLookupFollowUp) {
2189 ExprResult E(LookupInObjCMethod(R, S, II, true));
2193 if (Expr *Ex = E.getAs<Expr>())
2198 if (R.isAmbiguous())
2201 // This could be an implicitly declared function reference (legal in C90,
2202 // extension in C99, forbidden in C++).
2203 if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2204 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2205 if (D) R.addDecl(D);
2208 // Determine whether this name might be a candidate for
2209 // argument-dependent lookup.
2210 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2212 if (R.empty() && !ADL) {
2213 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2214 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2215 TemplateKWLoc, TemplateArgs))
2219 // Don't diagnose an empty lookup for inline assembly.
2220 if (IsInlineAsmIdentifier)
2223 // If this name wasn't predeclared and if this is not a function
2224 // call, diagnose the problem.
2225 TypoExpr *TE = nullptr;
2226 auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2227 II, SS.isValid() ? SS.getScopeRep() : nullptr);
2228 DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2229 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2230 "Typo correction callback misconfigured");
2232 // Make sure the callback knows what the typo being diagnosed is.
2233 CCC->setTypoName(II);
2235 CCC->setTypoNNS(SS.getScopeRep());
2237 if (DiagnoseEmptyLookup(S, SS, R,
2238 CCC ? std::move(CCC) : std::move(DefaultValidator),
2239 nullptr, None, &TE)) {
2240 if (TE && KeywordReplacement) {
2241 auto &State = getTypoExprState(TE);
2242 auto BestTC = State.Consumer->getNextCorrection();
2243 if (BestTC.isKeyword()) {
2244 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2245 if (State.DiagHandler)
2246 State.DiagHandler(BestTC);
2247 KeywordReplacement->startToken();
2248 KeywordReplacement->setKind(II->getTokenID());
2249 KeywordReplacement->setIdentifierInfo(II);
2250 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2251 // Clean up the state associated with the TypoExpr, since it has
2252 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2253 clearDelayedTypo(TE);
2254 // Signal that a correction to a keyword was performed by returning a
2255 // valid-but-null ExprResult.
2256 return (Expr*)nullptr;
2258 State.Consumer->resetCorrectionStream();
2260 return TE ? TE : ExprError();
2263 assert(!R.empty() &&
2264 "DiagnoseEmptyLookup returned false but added no results");
2266 // If we found an Objective-C instance variable, let
2267 // LookupInObjCMethod build the appropriate expression to
2268 // reference the ivar.
2269 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2271 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2272 // In a hopelessly buggy code, Objective-C instance variable
2273 // lookup fails and no expression will be built to reference it.
2274 if (!E.isInvalid() && !E.get())
2280 // This is guaranteed from this point on.
2281 assert(!R.empty() || ADL);
2283 // Check whether this might be a C++ implicit instance member access.
2284 // C++ [class.mfct.non-static]p3:
2285 // When an id-expression that is not part of a class member access
2286 // syntax and not used to form a pointer to member is used in the
2287 // body of a non-static member function of class X, if name lookup
2288 // resolves the name in the id-expression to a non-static non-type
2289 // member of some class C, the id-expression is transformed into a
2290 // class member access expression using (*this) as the
2291 // postfix-expression to the left of the . operator.
2293 // But we don't actually need to do this for '&' operands if R
2294 // resolved to a function or overloaded function set, because the
2295 // expression is ill-formed if it actually works out to be a
2296 // non-static member function:
2298 // C++ [expr.ref]p4:
2299 // Otherwise, if E1.E2 refers to a non-static member function. . .
2300 // [t]he expression can be used only as the left-hand operand of a
2301 // member function call.
2303 // There are other safeguards against such uses, but it's important
2304 // to get this right here so that we don't end up making a
2305 // spuriously dependent expression if we're inside a dependent
2307 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2308 bool MightBeImplicitMember;
2309 if (!IsAddressOfOperand)
2310 MightBeImplicitMember = true;
2311 else if (!SS.isEmpty())
2312 MightBeImplicitMember = false;
2313 else if (R.isOverloadedResult())
2314 MightBeImplicitMember = false;
2315 else if (R.isUnresolvableResult())
2316 MightBeImplicitMember = true;
2318 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2319 isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2320 isa<MSPropertyDecl>(R.getFoundDecl());
2322 if (MightBeImplicitMember)
2323 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2324 R, TemplateArgs, S);
2327 if (TemplateArgs || TemplateKWLoc.isValid()) {
2329 // In C++1y, if this is a variable template id, then check it
2330 // in BuildTemplateIdExpr().
2331 // The single lookup result must be a variable template declaration.
2332 if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2333 Id.TemplateId->Kind == TNK_Var_template) {
2334 assert(R.getAsSingle<VarTemplateDecl>() &&
2335 "There should only be one declaration found.");
2338 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2341 return BuildDeclarationNameExpr(SS, R, ADL);
2344 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2345 /// declaration name, generally during template instantiation.
2346 /// There's a large number of things which don't need to be done along
2348 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2349 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2350 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2351 DeclContext *DC = computeDeclContext(SS, false);
2353 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2354 NameInfo, /*TemplateArgs=*/nullptr);
2356 if (RequireCompleteDeclContext(SS, DC))
2359 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2360 LookupQualifiedName(R, DC);
2362 if (R.isAmbiguous())
2365 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2366 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2367 NameInfo, /*TemplateArgs=*/nullptr);
2370 Diag(NameInfo.getLoc(), diag::err_no_member)
2371 << NameInfo.getName() << DC << SS.getRange();
2375 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2376 // Diagnose a missing typename if this resolved unambiguously to a type in
2377 // a dependent context. If we can recover with a type, downgrade this to
2378 // a warning in Microsoft compatibility mode.
2379 unsigned DiagID = diag::err_typename_missing;
2380 if (RecoveryTSI && getLangOpts().MSVCCompat)
2381 DiagID = diag::ext_typename_missing;
2382 SourceLocation Loc = SS.getBeginLoc();
2383 auto D = Diag(Loc, DiagID);
2384 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2385 << SourceRange(Loc, NameInfo.getEndLoc());
2387 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2392 // Only issue the fixit if we're prepared to recover.
2393 D << FixItHint::CreateInsertion(Loc, "typename ");
2395 // Recover by pretending this was an elaborated type.
2396 QualType Ty = Context.getTypeDeclType(TD);
2398 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2400 QualType ET = getElaboratedType(ETK_None, SS, Ty);
2401 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2402 QTL.setElaboratedKeywordLoc(SourceLocation());
2403 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2405 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2410 // Defend against this resolving to an implicit member access. We usually
2411 // won't get here if this might be a legitimate a class member (we end up in
2412 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2413 // a pointer-to-member or in an unevaluated context in C++11.
2414 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2415 return BuildPossibleImplicitMemberExpr(SS,
2416 /*TemplateKWLoc=*/SourceLocation(),
2417 R, /*TemplateArgs=*/nullptr, S);
2419 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2422 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2423 /// detected that we're currently inside an ObjC method. Perform some
2424 /// additional lookup.
2426 /// Ideally, most of this would be done by lookup, but there's
2427 /// actually quite a lot of extra work involved.
2429 /// Returns a null sentinel to indicate trivial success.
2431 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2432 IdentifierInfo *II, bool AllowBuiltinCreation) {
2433 SourceLocation Loc = Lookup.getNameLoc();
2434 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2436 // Check for error condition which is already reported.
2440 // There are two cases to handle here. 1) scoped lookup could have failed,
2441 // in which case we should look for an ivar. 2) scoped lookup could have
2442 // found a decl, but that decl is outside the current instance method (i.e.
2443 // a global variable). In these two cases, we do a lookup for an ivar with
2444 // this name, if the lookup sucedes, we replace it our current decl.
2446 // If we're in a class method, we don't normally want to look for
2447 // ivars. But if we don't find anything else, and there's an
2448 // ivar, that's an error.
2449 bool IsClassMethod = CurMethod->isClassMethod();
2453 LookForIvars = true;
2454 else if (IsClassMethod)
2455 LookForIvars = false;
2457 LookForIvars = (Lookup.isSingleResult() &&
2458 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2459 ObjCInterfaceDecl *IFace = nullptr;
2461 IFace = CurMethod->getClassInterface();
2462 ObjCInterfaceDecl *ClassDeclared;
2463 ObjCIvarDecl *IV = nullptr;
2464 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2465 // Diagnose using an ivar in a class method.
2467 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2468 << IV->getDeclName());
2470 // If we're referencing an invalid decl, just return this as a silent
2471 // error node. The error diagnostic was already emitted on the decl.
2472 if (IV->isInvalidDecl())
2475 // Check if referencing a field with __attribute__((deprecated)).
2476 if (DiagnoseUseOfDecl(IV, Loc))
2479 // Diagnose the use of an ivar outside of the declaring class.
2480 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2481 !declaresSameEntity(ClassDeclared, IFace) &&
2482 !getLangOpts().DebuggerSupport)
2483 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2485 // FIXME: This should use a new expr for a direct reference, don't
2486 // turn this into Self->ivar, just return a BareIVarExpr or something.
2487 IdentifierInfo &II = Context.Idents.get("self");
2488 UnqualifiedId SelfName;
2489 SelfName.setIdentifier(&II, SourceLocation());
2490 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2491 CXXScopeSpec SelfScopeSpec;
2492 SourceLocation TemplateKWLoc;
2493 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2494 SelfName, false, false);
2495 if (SelfExpr.isInvalid())
2498 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2499 if (SelfExpr.isInvalid())
2502 MarkAnyDeclReferenced(Loc, IV, true);
2504 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2505 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2506 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2507 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2509 ObjCIvarRefExpr *Result = new (Context)
2510 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2511 IV->getLocation(), SelfExpr.get(), true, true);
2513 if (getLangOpts().ObjCAutoRefCount) {
2514 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2515 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2516 recordUseOfEvaluatedWeak(Result);
2518 if (CurContext->isClosure())
2519 Diag(Loc, diag::warn_implicitly_retains_self)
2520 << FixItHint::CreateInsertion(Loc, "self->");
2525 } else if (CurMethod->isInstanceMethod()) {
2526 // We should warn if a local variable hides an ivar.
2527 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2528 ObjCInterfaceDecl *ClassDeclared;
2529 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2530 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2531 declaresSameEntity(IFace, ClassDeclared))
2532 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2535 } else if (Lookup.isSingleResult() &&
2536 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2537 // If accessing a stand-alone ivar in a class method, this is an error.
2538 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2539 return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2540 << IV->getDeclName());
2543 if (Lookup.empty() && II && AllowBuiltinCreation) {
2544 // FIXME. Consolidate this with similar code in LookupName.
2545 if (unsigned BuiltinID = II->getBuiltinID()) {
2546 if (!(getLangOpts().CPlusPlus &&
2547 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2548 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2549 S, Lookup.isForRedeclaration(),
2550 Lookup.getNameLoc());
2551 if (D) Lookup.addDecl(D);
2555 // Sentinel value saying that we didn't do anything special.
2556 return ExprResult((Expr *)nullptr);
2559 /// \brief Cast a base object to a member's actual type.
2561 /// Logically this happens in three phases:
2563 /// * First we cast from the base type to the naming class.
2564 /// The naming class is the class into which we were looking
2565 /// when we found the member; it's the qualifier type if a
2566 /// qualifier was provided, and otherwise it's the base type.
2568 /// * Next we cast from the naming class to the declaring class.
2569 /// If the member we found was brought into a class's scope by
2570 /// a using declaration, this is that class; otherwise it's
2571 /// the class declaring the member.
2573 /// * Finally we cast from the declaring class to the "true"
2574 /// declaring class of the member. This conversion does not
2575 /// obey access control.
2577 Sema::PerformObjectMemberConversion(Expr *From,
2578 NestedNameSpecifier *Qualifier,
2579 NamedDecl *FoundDecl,
2580 NamedDecl *Member) {
2581 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2585 QualType DestRecordType;
2587 QualType FromRecordType;
2588 QualType FromType = From->getType();
2589 bool PointerConversions = false;
2590 if (isa<FieldDecl>(Member)) {
2591 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2593 if (FromType->getAs<PointerType>()) {
2594 DestType = Context.getPointerType(DestRecordType);
2595 FromRecordType = FromType->getPointeeType();
2596 PointerConversions = true;
2598 DestType = DestRecordType;
2599 FromRecordType = FromType;
2601 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2602 if (Method->isStatic())
2605 DestType = Method->getThisType(Context);
2606 DestRecordType = DestType->getPointeeType();
2608 if (FromType->getAs<PointerType>()) {
2609 FromRecordType = FromType->getPointeeType();
2610 PointerConversions = true;
2612 FromRecordType = FromType;
2613 DestType = DestRecordType;
2616 // No conversion necessary.
2620 if (DestType->isDependentType() || FromType->isDependentType())
2623 // If the unqualified types are the same, no conversion is necessary.
2624 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2627 SourceRange FromRange = From->getSourceRange();
2628 SourceLocation FromLoc = FromRange.getBegin();
2630 ExprValueKind VK = From->getValueKind();
2632 // C++ [class.member.lookup]p8:
2633 // [...] Ambiguities can often be resolved by qualifying a name with its
2636 // If the member was a qualified name and the qualified referred to a
2637 // specific base subobject type, we'll cast to that intermediate type
2638 // first and then to the object in which the member is declared. That allows
2639 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2641 // class Base { public: int x; };
2642 // class Derived1 : public Base { };
2643 // class Derived2 : public Base { };
2644 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2646 // void VeryDerived::f() {
2647 // x = 17; // error: ambiguous base subobjects
2648 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2650 if (Qualifier && Qualifier->getAsType()) {
2651 QualType QType = QualType(Qualifier->getAsType(), 0);
2652 assert(QType->isRecordType() && "lookup done with non-record type");
2654 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2656 // In C++98, the qualifier type doesn't actually have to be a base
2657 // type of the object type, in which case we just ignore it.
2658 // Otherwise build the appropriate casts.
2659 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2660 CXXCastPath BasePath;
2661 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2662 FromLoc, FromRange, &BasePath))
2665 if (PointerConversions)
2666 QType = Context.getPointerType(QType);
2667 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2668 VK, &BasePath).get();
2671 FromRecordType = QRecordType;
2673 // If the qualifier type was the same as the destination type,
2675 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2680 bool IgnoreAccess = false;
2682 // If we actually found the member through a using declaration, cast
2683 // down to the using declaration's type.
2685 // Pointer equality is fine here because only one declaration of a
2686 // class ever has member declarations.
2687 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2688 assert(isa<UsingShadowDecl>(FoundDecl));
2689 QualType URecordType = Context.getTypeDeclType(
2690 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2692 // We only need to do this if the naming-class to declaring-class
2693 // conversion is non-trivial.
2694 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2695 assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2696 CXXCastPath BasePath;
2697 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2698 FromLoc, FromRange, &BasePath))
2701 QualType UType = URecordType;
2702 if (PointerConversions)
2703 UType = Context.getPointerType(UType);
2704 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2705 VK, &BasePath).get();
2707 FromRecordType = URecordType;
2710 // We don't do access control for the conversion from the
2711 // declaring class to the true declaring class.
2712 IgnoreAccess = true;
2715 CXXCastPath BasePath;
2716 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2717 FromLoc, FromRange, &BasePath,
2721 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2725 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2726 const LookupResult &R,
2727 bool HasTrailingLParen) {
2728 // Only when used directly as the postfix-expression of a call.
2729 if (!HasTrailingLParen)
2732 // Never if a scope specifier was provided.
2736 // Only in C++ or ObjC++.
2737 if (!getLangOpts().CPlusPlus)
2740 // Turn off ADL when we find certain kinds of declarations during
2742 for (NamedDecl *D : R) {
2743 // C++0x [basic.lookup.argdep]p3:
2744 // -- a declaration of a class member
2745 // Since using decls preserve this property, we check this on the
2747 if (D->isCXXClassMember())
2750 // C++0x [basic.lookup.argdep]p3:
2751 // -- a block-scope function declaration that is not a
2752 // using-declaration
2753 // NOTE: we also trigger this for function templates (in fact, we
2754 // don't check the decl type at all, since all other decl types
2755 // turn off ADL anyway).
2756 if (isa<UsingShadowDecl>(D))
2757 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2758 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2761 // C++0x [basic.lookup.argdep]p3:
2762 // -- a declaration that is neither a function or a function
2764 // And also for builtin functions.
2765 if (isa<FunctionDecl>(D)) {
2766 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2768 // But also builtin functions.
2769 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2771 } else if (!isa<FunctionTemplateDecl>(D))
2779 /// Diagnoses obvious problems with the use of the given declaration
2780 /// as an expression. This is only actually called for lookups that
2781 /// were not overloaded, and it doesn't promise that the declaration
2782 /// will in fact be used.
2783 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2784 if (D->isInvalidDecl())
2787 if (isa<TypedefNameDecl>(D)) {
2788 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2792 if (isa<ObjCInterfaceDecl>(D)) {
2793 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2797 if (isa<NamespaceDecl>(D)) {
2798 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2805 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2806 LookupResult &R, bool NeedsADL,
2807 bool AcceptInvalidDecl) {
2808 // If this is a single, fully-resolved result and we don't need ADL,
2809 // just build an ordinary singleton decl ref.
2810 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2811 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2812 R.getRepresentativeDecl(), nullptr,
2815 // We only need to check the declaration if there's exactly one
2816 // result, because in the overloaded case the results can only be
2817 // functions and function templates.
2818 if (R.isSingleResult() &&
2819 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2822 // Otherwise, just build an unresolved lookup expression. Suppress
2823 // any lookup-related diagnostics; we'll hash these out later, when
2824 // we've picked a target.
2825 R.suppressDiagnostics();
2827 UnresolvedLookupExpr *ULE
2828 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2829 SS.getWithLocInContext(Context),
2830 R.getLookupNameInfo(),
2831 NeedsADL, R.isOverloadedResult(),
2832 R.begin(), R.end());
2838 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2839 ValueDecl *var, DeclContext *DC);
2841 /// \brief Complete semantic analysis for a reference to the given declaration.
2842 ExprResult Sema::BuildDeclarationNameExpr(
2843 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2844 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2845 bool AcceptInvalidDecl) {
2846 assert(D && "Cannot refer to a NULL declaration");
2847 assert(!isa<FunctionTemplateDecl>(D) &&
2848 "Cannot refer unambiguously to a function template");
2850 SourceLocation Loc = NameInfo.getLoc();
2851 if (CheckDeclInExpr(*this, Loc, D))
2854 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2855 // Specifically diagnose references to class templates that are missing
2856 // a template argument list.
2857 Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2858 << Template << SS.getRange();
2859 Diag(Template->getLocation(), diag::note_template_decl_here);
2863 // Make sure that we're referring to a value.
2864 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2866 Diag(Loc, diag::err_ref_non_value)
2867 << D << SS.getRange();
2868 Diag(D->getLocation(), diag::note_declared_at);
2872 // Check whether this declaration can be used. Note that we suppress
2873 // this check when we're going to perform argument-dependent lookup
2874 // on this function name, because this might not be the function
2875 // that overload resolution actually selects.
2876 if (DiagnoseUseOfDecl(VD, Loc))
2879 // Only create DeclRefExpr's for valid Decl's.
2880 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2883 // Handle members of anonymous structs and unions. If we got here,
2884 // and the reference is to a class member indirect field, then this
2885 // must be the subject of a pointer-to-member expression.
2886 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2887 if (!indirectField->isCXXClassMember())
2888 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2892 QualType type = VD->getType();
2893 if (auto *FPT = type->getAs<FunctionProtoType>()) {
2894 // C++ [except.spec]p17:
2895 // An exception-specification is considered to be needed when:
2896 // - in an expression, the function is the unique lookup result or
2897 // the selected member of a set of overloaded functions.
2898 ResolveExceptionSpec(Loc, FPT);
2899 type = VD->getType();
2901 ExprValueKind valueKind = VK_RValue;
2903 switch (D->getKind()) {
2904 // Ignore all the non-ValueDecl kinds.
2905 #define ABSTRACT_DECL(kind)
2906 #define VALUE(type, base)
2907 #define DECL(type, base) \
2909 #include "clang/AST/DeclNodes.inc"
2910 llvm_unreachable("invalid value decl kind");
2912 // These shouldn't make it here.
2913 case Decl::ObjCAtDefsField:
2914 case Decl::ObjCIvar:
2915 llvm_unreachable("forming non-member reference to ivar?");
2917 // Enum constants are always r-values and never references.
2918 // Unresolved using declarations are dependent.
2919 case Decl::EnumConstant:
2920 case Decl::UnresolvedUsingValue:
2921 case Decl::OMPDeclareReduction:
2922 valueKind = VK_RValue;
2925 // Fields and indirect fields that got here must be for
2926 // pointer-to-member expressions; we just call them l-values for
2927 // internal consistency, because this subexpression doesn't really
2928 // exist in the high-level semantics.
2930 case Decl::IndirectField:
2931 assert(getLangOpts().CPlusPlus &&
2932 "building reference to field in C?");
2934 // These can't have reference type in well-formed programs, but
2935 // for internal consistency we do this anyway.
2936 type = type.getNonReferenceType();
2937 valueKind = VK_LValue;
2940 // Non-type template parameters are either l-values or r-values
2941 // depending on the type.
2942 case Decl::NonTypeTemplateParm: {
2943 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2944 type = reftype->getPointeeType();
2945 valueKind = VK_LValue; // even if the parameter is an r-value reference
2949 // For non-references, we need to strip qualifiers just in case
2950 // the template parameter was declared as 'const int' or whatever.
2951 valueKind = VK_RValue;
2952 type = type.getUnqualifiedType();
2957 case Decl::VarTemplateSpecialization:
2958 case Decl::VarTemplatePartialSpecialization:
2959 case Decl::Decomposition:
2960 case Decl::OMPCapturedExpr:
2961 // In C, "extern void blah;" is valid and is an r-value.
2962 if (!getLangOpts().CPlusPlus &&
2963 !type.hasQualifiers() &&
2964 type->isVoidType()) {
2965 valueKind = VK_RValue;
2970 case Decl::ImplicitParam:
2971 case Decl::ParmVar: {
2972 // These are always l-values.
2973 valueKind = VK_LValue;
2974 type = type.getNonReferenceType();
2976 // FIXME: Does the addition of const really only apply in
2977 // potentially-evaluated contexts? Since the variable isn't actually
2978 // captured in an unevaluated context, it seems that the answer is no.
2979 if (!isUnevaluatedContext()) {
2980 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2981 if (!CapturedType.isNull())
2982 type = CapturedType;
2988 case Decl::Binding: {
2989 // These are always lvalues.
2990 valueKind = VK_LValue;
2991 type = type.getNonReferenceType();
2992 // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2993 // decides how that's supposed to work.
2994 auto *BD = cast<BindingDecl>(VD);
2995 if (BD->getDeclContext()->isFunctionOrMethod() &&
2996 BD->getDeclContext() != CurContext)
2997 diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3001 case Decl::Function: {
3002 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3003 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3004 type = Context.BuiltinFnTy;
3005 valueKind = VK_RValue;
3010 const FunctionType *fty = type->castAs<FunctionType>();
3012 // If we're referring to a function with an __unknown_anytype
3013 // result type, make the entire expression __unknown_anytype.
3014 if (fty->getReturnType() == Context.UnknownAnyTy) {
3015 type = Context.UnknownAnyTy;
3016 valueKind = VK_RValue;
3020 // Functions are l-values in C++.
3021 if (getLangOpts().CPlusPlus) {
3022 valueKind = VK_LValue;
3026 // C99 DR 316 says that, if a function type comes from a
3027 // function definition (without a prototype), that type is only
3028 // used for checking compatibility. Therefore, when referencing
3029 // the function, we pretend that we don't have the full function
3031 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3032 isa<FunctionProtoType>(fty))
3033 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3036 // Functions are r-values in C.
3037 valueKind = VK_RValue;
3041 case Decl::MSProperty:
3042 valueKind = VK_LValue;
3045 case Decl::CXXMethod:
3046 // If we're referring to a method with an __unknown_anytype
3047 // result type, make the entire expression __unknown_anytype.
3048 // This should only be possible with a type written directly.
3049 if (const FunctionProtoType *proto
3050 = dyn_cast<FunctionProtoType>(VD->getType()))
3051 if (proto->getReturnType() == Context.UnknownAnyTy) {
3052 type = Context.UnknownAnyTy;
3053 valueKind = VK_RValue;
3057 // C++ methods are l-values if static, r-values if non-static.
3058 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3059 valueKind = VK_LValue;
3064 case Decl::CXXConversion:
3065 case Decl::CXXDestructor:
3066 case Decl::CXXConstructor:
3067 valueKind = VK_RValue;
3071 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3076 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3077 SmallString<32> &Target) {
3078 Target.resize(CharByteWidth * (Source.size() + 1));
3079 char *ResultPtr = &Target[0];
3080 const llvm::UTF8 *ErrorPtr;
3082 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3085 Target.resize(ResultPtr - &Target[0]);
3088 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3089 PredefinedExpr::IdentType IT) {
3090 // Pick the current block, lambda, captured statement or function.
3091 Decl *currentDecl = nullptr;
3092 if (const BlockScopeInfo *BSI = getCurBlock())
3093 currentDecl = BSI->TheDecl;
3094 else if (const LambdaScopeInfo *LSI = getCurLambda())
3095 currentDecl = LSI->CallOperator;
3096 else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3097 currentDecl = CSI->TheCapturedDecl;
3099 currentDecl = getCurFunctionOrMethodDecl();
3102 Diag(Loc, diag::ext_predef_outside_function);
3103 currentDecl = Context.getTranslationUnitDecl();
3107 StringLiteral *SL = nullptr;
3108 if (cast<DeclContext>(currentDecl)->isDependentContext())
3109 ResTy = Context.DependentTy;
3111 // Pre-defined identifiers are of type char[x], where x is the length of
3113 auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3114 unsigned Length = Str.length();
3116 llvm::APInt LengthI(32, Length + 1);
3117 if (IT == PredefinedExpr::LFunction) {
3118 ResTy = Context.WideCharTy.withConst();
3119 SmallString<32> RawChars;
3120 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3122 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3123 /*IndexTypeQuals*/ 0);
3124 SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3125 /*Pascal*/ false, ResTy, Loc);
3127 ResTy = Context.CharTy.withConst();
3128 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3129 /*IndexTypeQuals*/ 0);
3130 SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3131 /*Pascal*/ false, ResTy, Loc);
3135 return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3138 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3139 PredefinedExpr::IdentType IT;
3142 default: llvm_unreachable("Unknown simple primary expr!");
3143 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3144 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3145 case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3146 case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3147 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3148 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3151 return BuildPredefinedExpr(Loc, IT);
3154 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3155 SmallString<16> CharBuffer;
3156 bool Invalid = false;
3157 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3161 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3163 if (Literal.hadError())
3167 if (Literal.isWide())
3168 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3169 else if (Literal.isUTF16())
3170 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3171 else if (Literal.isUTF32())
3172 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3173 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3174 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3176 Ty = Context.CharTy; // 'x' -> char in C++
3178 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3179 if (Literal.isWide())
3180 Kind = CharacterLiteral::Wide;
3181 else if (Literal.isUTF16())
3182 Kind = CharacterLiteral::UTF16;
3183 else if (Literal.isUTF32())
3184 Kind = CharacterLiteral::UTF32;
3185 else if (Literal.isUTF8())
3186 Kind = CharacterLiteral::UTF8;
3188 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3191 if (Literal.getUDSuffix().empty())
3194 // We're building a user-defined literal.
3195 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3196 SourceLocation UDSuffixLoc =
3197 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3199 // Make sure we're allowed user-defined literals here.
3201 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3203 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3204 // operator "" X (ch)
3205 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3206 Lit, Tok.getLocation());
3209 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3210 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3211 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3212 Context.IntTy, Loc);
3215 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3216 QualType Ty, SourceLocation Loc) {
3217 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3219 using llvm::APFloat;
3220 APFloat Val(Format);
3222 APFloat::opStatus result = Literal.GetFloatValue(Val);
3224 // Overflow is always an error, but underflow is only an error if
3225 // we underflowed to zero (APFloat reports denormals as underflow).
3226 if ((result & APFloat::opOverflow) ||
3227 ((result & APFloat::opUnderflow) && Val.isZero())) {
3228 unsigned diagnostic;
3229 SmallString<20> buffer;
3230 if (result & APFloat::opOverflow) {
3231 diagnostic = diag::warn_float_overflow;
3232 APFloat::getLargest(Format).toString(buffer);
3234 diagnostic = diag::warn_float_underflow;
3235 APFloat::getSmallest(Format).toString(buffer);
3238 S.Diag(Loc, diagnostic)
3240 << StringRef(buffer.data(), buffer.size());
3243 bool isExact = (result == APFloat::opOK);
3244 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3247 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3248 assert(E && "Invalid expression");
3250 if (E->isValueDependent())
3253 QualType QT = E->getType();
3254 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3255 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3259 llvm::APSInt ValueAPS;
3260 ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3265 bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3266 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3267 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3268 << ValueAPS.toString(10) << ValueIsPositive;
3275 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3276 // Fast path for a single digit (which is quite common). A single digit
3277 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3278 if (Tok.getLength() == 1) {
3279 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3280 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3283 SmallString<128> SpellingBuffer;
3284 // NumericLiteralParser wants to overread by one character. Add padding to
3285 // the buffer in case the token is copied to the buffer. If getSpelling()
3286 // returns a StringRef to the memory buffer, it should have a null char at
3287 // the EOF, so it is also safe.
3288 SpellingBuffer.resize(Tok.getLength() + 1);
3290 // Get the spelling of the token, which eliminates trigraphs, etc.
3291 bool Invalid = false;
3292 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3296 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3297 if (Literal.hadError)
3300 if (Literal.hasUDSuffix()) {
3301 // We're building a user-defined literal.
3302 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3303 SourceLocation UDSuffixLoc =
3304 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3306 // Make sure we're allowed user-defined literals here.
3308 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3311 if (Literal.isFloatingLiteral()) {
3312 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3313 // long double, the literal is treated as a call of the form
3314 // operator "" X (f L)
3315 CookedTy = Context.LongDoubleTy;
3317 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3318 // unsigned long long, the literal is treated as a call of the form
3319 // operator "" X (n ULL)
3320 CookedTy = Context.UnsignedLongLongTy;
3323 DeclarationName OpName =
3324 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3325 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3326 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3328 SourceLocation TokLoc = Tok.getLocation();
3330 // Perform literal operator lookup to determine if we're building a raw
3331 // literal or a cooked one.
3332 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3333 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3334 /*AllowRaw*/true, /*AllowTemplate*/true,
3335 /*AllowStringTemplate*/false)) {
3341 if (Literal.isFloatingLiteral()) {
3342 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3344 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3345 if (Literal.GetIntegerValue(ResultVal))
3346 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3347 << /* Unsigned */ 1;
3348 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3351 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3355 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3356 // literal is treated as a call of the form
3357 // operator "" X ("n")
3358 unsigned Length = Literal.getUDSuffixOffset();
3359 QualType StrTy = Context.getConstantArrayType(
3360 Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3361 ArrayType::Normal, 0);
3362 Expr *Lit = StringLiteral::Create(
3363 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3364 /*Pascal*/false, StrTy, &TokLoc, 1);
3365 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3368 case LOLR_Template: {
3369 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3370 // template), L is treated as a call fo the form
3371 // operator "" X <'c1', 'c2', ... 'ck'>()
3372 // where n is the source character sequence c1 c2 ... ck.
3373 TemplateArgumentListInfo ExplicitArgs;
3374 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3375 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3376 llvm::APSInt Value(CharBits, CharIsUnsigned);
3377 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3378 Value = TokSpelling[I];
3379 TemplateArgument Arg(Context, Value, Context.CharTy);
3380 TemplateArgumentLocInfo ArgInfo;
3381 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3383 return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3386 case LOLR_StringTemplate:
3387 llvm_unreachable("unexpected literal operator lookup result");
3393 if (Literal.isFloatingLiteral()) {
3395 if (Literal.isHalf){
3396 if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3397 Ty = Context.HalfTy;
3399 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3402 } else if (Literal.isFloat)
3403 Ty = Context.FloatTy;
3404 else if (Literal.isLong)
3405 Ty = Context.LongDoubleTy;
3406 else if (Literal.isFloat128)
3407 Ty = Context.Float128Ty;
3409 Ty = Context.DoubleTy;
3411 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3413 if (Ty == Context.DoubleTy) {
3414 if (getLangOpts().SinglePrecisionConstants) {
3415 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3416 if (BTy->getKind() != BuiltinType::Float) {
3417 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3419 } else if (getLangOpts().OpenCL &&
3420 !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3421 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3422 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3423 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3426 } else if (!Literal.isIntegerLiteral()) {
3431 // 'long long' is a C99 or C++11 feature.
3432 if (!getLangOpts().C99 && Literal.isLongLong) {
3433 if (getLangOpts().CPlusPlus)
3434 Diag(Tok.getLocation(),
3435 getLangOpts().CPlusPlus11 ?
3436 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3438 Diag(Tok.getLocation(), diag::ext_c99_longlong);
3441 // Get the value in the widest-possible width.
3442 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3443 llvm::APInt ResultVal(MaxWidth, 0);
3445 if (Literal.GetIntegerValue(ResultVal)) {
3446 // If this value didn't fit into uintmax_t, error and force to ull.
3447 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3448 << /* Unsigned */ 1;
3449 Ty = Context.UnsignedLongLongTy;
3450 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3451 "long long is not intmax_t?");
3453 // If this value fits into a ULL, try to figure out what else it fits into
3454 // according to the rules of C99 6.4.4.1p5.
3456 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3457 // be an unsigned int.
3458 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3460 // Check from smallest to largest, picking the smallest type we can.
3463 // Microsoft specific integer suffixes are explicitly sized.
3464 if (Literal.MicrosoftInteger) {
3465 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3467 Ty = Context.CharTy;
3469 Width = Literal.MicrosoftInteger;
3470 Ty = Context.getIntTypeForBitwidth(Width,
3471 /*Signed=*/!Literal.isUnsigned);
3475 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3476 // Are int/unsigned possibilities?
3477 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3479 // Does it fit in a unsigned int?
3480 if (ResultVal.isIntN(IntSize)) {
3481 // Does it fit in a signed int?
3482 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3484 else if (AllowUnsigned)
3485 Ty = Context.UnsignedIntTy;
3490 // Are long/unsigned long possibilities?
3491 if (Ty.isNull() && !Literal.isLongLong) {
3492 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3494 // Does it fit in a unsigned long?
3495 if (ResultVal.isIntN(LongSize)) {
3496 // Does it fit in a signed long?
3497 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3498 Ty = Context.LongTy;
3499 else if (AllowUnsigned)
3500 Ty = Context.UnsignedLongTy;
3501 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3503 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3504 const unsigned LongLongSize =
3505 Context.getTargetInfo().getLongLongWidth();
3506 Diag(Tok.getLocation(),
3507 getLangOpts().CPlusPlus
3509 ? diag::warn_old_implicitly_unsigned_long_cxx
3510 : /*C++98 UB*/ diag::
3511 ext_old_implicitly_unsigned_long_cxx
3512 : diag::warn_old_implicitly_unsigned_long)
3513 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3514 : /*will be ill-formed*/ 1);
3515 Ty = Context.UnsignedLongTy;
3521 // Check long long if needed.
3523 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3525 // Does it fit in a unsigned long long?
3526 if (ResultVal.isIntN(LongLongSize)) {
3527 // Does it fit in a signed long long?
3528 // To be compatible with MSVC, hex integer literals ending with the
3529 // LL or i64 suffix are always signed in Microsoft mode.
3530 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3531 (getLangOpts().MSVCCompat && Literal.isLongLong)))
3532 Ty = Context.LongLongTy;
3533 else if (AllowUnsigned)
3534 Ty = Context.UnsignedLongLongTy;
3535 Width = LongLongSize;
3539 // If we still couldn't decide a type, we probably have something that
3540 // does not fit in a signed long long, but has no U suffix.
3542 Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3543 Ty = Context.UnsignedLongLongTy;
3544 Width = Context.getTargetInfo().getLongLongWidth();
3547 if (ResultVal.getBitWidth() != Width)
3548 ResultVal = ResultVal.trunc(Width);
3550 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3553 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3554 if (Literal.isImaginary)
3555 Res = new (Context) ImaginaryLiteral(Res,
3556 Context.getComplexType(Res->getType()));
3561 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3562 assert(E && "ActOnParenExpr() missing expr");
3563 return new (Context) ParenExpr(L, R, E);
3566 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3568 SourceRange ArgRange) {
3569 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3570 // scalar or vector data type argument..."
3571 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3572 // type (C99 6.2.5p18) or void.
3573 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3574 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3579 assert((T->isVoidType() || !T->isIncompleteType()) &&
3580 "Scalar types should always be complete");
3584 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3586 SourceRange ArgRange,
3587 UnaryExprOrTypeTrait TraitKind) {
3588 // Invalid types must be hard errors for SFINAE in C++.
3589 if (S.LangOpts.CPlusPlus)
3593 if (T->isFunctionType() &&
3594 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3595 // sizeof(function)/alignof(function) is allowed as an extension.
3596 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3597 << TraitKind << ArgRange;
3601 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3602 // this is an error (OpenCL v1.1 s6.3.k)
3603 if (T->isVoidType()) {
3604 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3605 : diag::ext_sizeof_alignof_void_type;
3606 S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3613 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3615 SourceRange ArgRange,
3616 UnaryExprOrTypeTrait TraitKind) {
3617 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3618 // runtime doesn't allow it.
3619 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3620 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3621 << T << (TraitKind == UETT_SizeOf)
3629 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3630 /// pointer type is equal to T) and emit a warning if it is.
3631 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3633 // Don't warn if the operation changed the type.
3634 if (T != E->getType())
3637 // Now look for array decays.
3638 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3639 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3642 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3644 << ICE->getSubExpr()->getType();
3647 /// \brief Check the constraints on expression operands to unary type expression
3648 /// and type traits.
3650 /// Completes any types necessary and validates the constraints on the operand
3651 /// expression. The logic mostly mirrors the type-based overload, but may modify
3652 /// the expression as it completes the type for that expression through template
3653 /// instantiation, etc.
3654 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3655 UnaryExprOrTypeTrait ExprKind) {
3656 QualType ExprTy = E->getType();
3657 assert(!ExprTy->isReferenceType());
3659 if (ExprKind == UETT_VecStep)
3660 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3661 E->getSourceRange());
3663 // Whitelist some types as extensions
3664 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3665 E->getSourceRange(), ExprKind))
3668 // 'alignof' applied to an expression only requires the base element type of
3669 // the expression to be complete. 'sizeof' requires the expression's type to
3670 // be complete (and will attempt to complete it if it's an array of unknown
3672 if (ExprKind == UETT_AlignOf) {
3673 if (RequireCompleteType(E->getExprLoc(),
3674 Context.getBaseElementType(E->getType()),
3675 diag::err_sizeof_alignof_incomplete_type, ExprKind,
3676 E->getSourceRange()))
3679 if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3680 ExprKind, E->getSourceRange()))
3684 // Completing the expression's type may have changed it.
3685 ExprTy = E->getType();
3686 assert(!ExprTy->isReferenceType());
3688 if (ExprTy->isFunctionType()) {
3689 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3690 << ExprKind << E->getSourceRange();
3694 // The operand for sizeof and alignof is in an unevaluated expression context,
3695 // so side effects could result in unintended consequences.
3696 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3697 ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3698 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3700 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3701 E->getSourceRange(), ExprKind))
3704 if (ExprKind == UETT_SizeOf) {
3705 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3706 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3707 QualType OType = PVD->getOriginalType();
3708 QualType Type = PVD->getType();
3709 if (Type->isPointerType() && OType->isArrayType()) {
3710 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3712 Diag(PVD->getLocation(), diag::note_declared_at);
3717 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3718 // decays into a pointer and returns an unintended result. This is most
3719 // likely a typo for "sizeof(array) op x".
3720 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3721 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3723 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3731 /// \brief Check the constraints on operands to unary expression and type
3734 /// This will complete any types necessary, and validate the various constraints
3735 /// on those operands.
3737 /// The UsualUnaryConversions() function is *not* called by this routine.
3738 /// C99 6.3.2.1p[2-4] all state:
3739 /// Except when it is the operand of the sizeof operator ...
3741 /// C++ [expr.sizeof]p4
3742 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3743 /// standard conversions are not applied to the operand of sizeof.
3745 /// This policy is followed for all of the unary trait expressions.
3746 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3747 SourceLocation OpLoc,
3748 SourceRange ExprRange,
3749 UnaryExprOrTypeTrait ExprKind) {
3750 if (ExprType->isDependentType())
3753 // C++ [expr.sizeof]p2:
3754 // When applied to a reference or a reference type, the result
3755 // is the size of the referenced type.
3756 // C++11 [expr.alignof]p3:
3757 // When alignof is applied to a reference type, the result
3758 // shall be the alignment of the referenced type.
3759 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3760 ExprType = Ref->getPointeeType();
3762 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3763 // When alignof or _Alignof is applied to an array type, the result
3764 // is the alignment of the element type.
3765 if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3766 ExprType = Context.getBaseElementType(ExprType);
3768 if (ExprKind == UETT_VecStep)
3769 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3771 // Whitelist some types as extensions
3772 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3776 if (RequireCompleteType(OpLoc, ExprType,
3777 diag::err_sizeof_alignof_incomplete_type,
3778 ExprKind, ExprRange))
3781 if (ExprType->isFunctionType()) {
3782 Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3783 << ExprKind << ExprRange;
3787 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3794 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3795 E = E->IgnoreParens();
3797 // Cannot know anything else if the expression is dependent.
3798 if (E->isTypeDependent())
3801 if (E->getObjectKind() == OK_BitField) {
3802 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3803 << 1 << E->getSourceRange();
3807 ValueDecl *D = nullptr;
3808 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3810 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3811 D = ME->getMemberDecl();
3814 // If it's a field, require the containing struct to have a
3815 // complete definition so that we can compute the layout.
3817 // This can happen in C++11 onwards, either by naming the member
3818 // in a way that is not transformed into a member access expression
3819 // (in an unevaluated operand, for instance), or by naming the member
3820 // in a trailing-return-type.
3822 // For the record, since __alignof__ on expressions is a GCC
3823 // extension, GCC seems to permit this but always gives the
3824 // nonsensical answer 0.
3826 // We don't really need the layout here --- we could instead just
3827 // directly check for all the appropriate alignment-lowing
3828 // attributes --- but that would require duplicating a lot of
3829 // logic that just isn't worth duplicating for such a marginal
3831 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3832 // Fast path this check, since we at least know the record has a
3833 // definition if we can find a member of it.
3834 if (!FD->getParent()->isCompleteDefinition()) {
3835 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3836 << E->getSourceRange();
3840 // Otherwise, if it's a field, and the field doesn't have
3841 // reference type, then it must have a complete type (or be a
3842 // flexible array member, which we explicitly want to
3843 // white-list anyway), which makes the following checks trivial.
3844 if (!FD->getType()->isReferenceType())
3848 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3851 bool Sema::CheckVecStepExpr(Expr *E) {
3852 E = E->IgnoreParens();
3854 // Cannot know anything else if the expression is dependent.
3855 if (E->isTypeDependent())
3858 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3861 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3862 CapturingScopeInfo *CSI) {
3863 assert(T->isVariablyModifiedType());
3864 assert(CSI != nullptr);
3866 // We're going to walk down into the type and look for VLA expressions.
3868 const Type *Ty = T.getTypePtr();
3869 switch (Ty->getTypeClass()) {
3870 #define TYPE(Class, Base)
3871 #define ABSTRACT_TYPE(Class, Base)
3872 #define NON_CANONICAL_TYPE(Class, Base)
3873 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3874 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3875 #include "clang/AST/TypeNodes.def"
3878 // These types are never variably-modified.
3882 case Type::ExtVector:
3885 case Type::Elaborated:
3886 case Type::TemplateSpecialization:
3887 case Type::ObjCObject:
3888 case Type::ObjCInterface:
3889 case Type::ObjCObjectPointer:
3890 case Type::ObjCTypeParam:
3892 llvm_unreachable("type class is never variably-modified!");
3893 case Type::Adjusted:
3894 T = cast<AdjustedType>(Ty)->getOriginalType();
3897 T = cast<DecayedType>(Ty)->getPointeeType();
3900 T = cast<PointerType>(Ty)->getPointeeType();
3902 case Type::BlockPointer:
3903 T = cast<BlockPointerType>(Ty)->getPointeeType();
3905 case Type::LValueReference:
3906 case Type::RValueReference:
3907 T = cast<ReferenceType>(Ty)->getPointeeType();
3909 case Type::MemberPointer:
3910 T = cast<MemberPointerType>(Ty)->getPointeeType();
3912 case Type::ConstantArray:
3913 case Type::IncompleteArray:
3914 // Losing element qualification here is fine.
3915 T = cast<ArrayType>(Ty)->getElementType();
3917 case Type::VariableArray: {
3918 // Losing element qualification here is fine.
3919 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3921 // Unknown size indication requires no size computation.
3922 // Otherwise, evaluate and record it.
3923 if (auto Size = VAT->getSizeExpr()) {
3924 if (!CSI->isVLATypeCaptured(VAT)) {
3925 RecordDecl *CapRecord = nullptr;
3926 if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3927 CapRecord = LSI->Lambda;
3928 } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3929 CapRecord = CRSI->TheRecordDecl;
3932 auto ExprLoc = Size->getExprLoc();
3933 auto SizeType = Context.getSizeType();
3934 // Build the non-static data member.
3936 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3937 /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3938 /*BW*/ nullptr, /*Mutable*/ false,
3939 /*InitStyle*/ ICIS_NoInit);
3940 Field->setImplicit(true);
3941 Field->setAccess(AS_private);
3942 Field->setCapturedVLAType(VAT);
3943 CapRecord->addDecl(Field);
3945 CSI->addVLATypeCapture(ExprLoc, SizeType);
3949 T = VAT->getElementType();
3952 case Type::FunctionProto:
3953 case Type::FunctionNoProto:
3954 T = cast<FunctionType>(Ty)->getReturnType();
3958 case Type::UnaryTransform:
3959 case Type::Attributed:
3960 case Type::SubstTemplateTypeParm:
3961 case Type::PackExpansion:
3962 // Keep walking after single level desugaring.
3963 T = T.getSingleStepDesugaredType(Context);
3966 T = cast<TypedefType>(Ty)->desugar();
3968 case Type::Decltype:
3969 T = cast<DecltypeType>(Ty)->desugar();
3972 T = cast<AutoType>(Ty)->getDeducedType();
3974 case Type::TypeOfExpr:
3975 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3978 T = cast<AtomicType>(Ty)->getValueType();
3981 } while (!T.isNull() && T->isVariablyModifiedType());
3984 /// \brief Build a sizeof or alignof expression given a type operand.
3986 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3987 SourceLocation OpLoc,
3988 UnaryExprOrTypeTrait ExprKind,
3993 QualType T = TInfo->getType();
3995 if (!T->isDependentType() &&
3996 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3999 if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4000 if (auto *TT = T->getAs<TypedefType>()) {
4001 for (auto I = FunctionScopes.rbegin(),
4002 E = std::prev(FunctionScopes.rend());
4004 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4007 DeclContext *DC = nullptr;
4008 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4009 DC = LSI->CallOperator;
4010 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4011 DC = CRSI->TheCapturedDecl;
4012 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4015 if (DC->containsDecl(TT->getDecl()))
4017 captureVariablyModifiedType(Context, T, CSI);
4023 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4024 return new (Context) UnaryExprOrTypeTraitExpr(
4025 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4028 /// \brief Build a sizeof or alignof expression given an expression
4031 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4032 UnaryExprOrTypeTrait ExprKind) {
4033 ExprResult PE = CheckPlaceholderExpr(E);
4039 // Verify that the operand is valid.
4040 bool isInvalid = false;
4041 if (E->isTypeDependent()) {
4042 // Delay type-checking for type-dependent expressions.
4043 } else if (ExprKind == UETT_AlignOf) {
4044 isInvalid = CheckAlignOfExpr(*this, E);
4045 } else if (ExprKind == UETT_VecStep) {
4046 isInvalid = CheckVecStepExpr(E);
4047 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4048 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4050 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4051 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4054 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4060 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4061 PE = TransformToPotentiallyEvaluated(E);
4062 if (PE.isInvalid()) return ExprError();
4066 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4067 return new (Context) UnaryExprOrTypeTraitExpr(
4068 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4071 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4072 /// expr and the same for @c alignof and @c __alignof
4073 /// Note that the ArgRange is invalid if isType is false.
4075 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4076 UnaryExprOrTypeTrait ExprKind, bool IsType,
4077 void *TyOrEx, SourceRange ArgRange) {
4078 // If error parsing type, ignore.
4079 if (!TyOrEx) return ExprError();
4082 TypeSourceInfo *TInfo;
4083 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4084 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4087 Expr *ArgEx = (Expr *)TyOrEx;
4088 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4092 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4094 if (V.get()->isTypeDependent())
4095 return S.Context.DependentTy;
4097 // _Real and _Imag are only l-values for normal l-values.
4098 if (V.get()->getObjectKind() != OK_Ordinary) {
4099 V = S.DefaultLvalueConversion(V.get());
4104 // These operators return the element type of a complex type.
4105 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4106 return CT->getElementType();
4108 // Otherwise they pass through real integer and floating point types here.
4109 if (V.get()->getType()->isArithmeticType())
4110 return V.get()->getType();
4112 // Test for placeholders.
4113 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4114 if (PR.isInvalid()) return QualType();
4115 if (PR.get() != V.get()) {
4117 return CheckRealImagOperand(S, V, Loc, IsReal);
4120 // Reject anything else.
4121 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4122 << (IsReal ? "__real" : "__imag");
4129 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4130 tok::TokenKind Kind, Expr *Input) {
4131 UnaryOperatorKind Opc;
4133 default: llvm_unreachable("Unknown unary op!");
4134 case tok::plusplus: Opc = UO_PostInc; break;
4135 case tok::minusminus: Opc = UO_PostDec; break;
4138 // Since this might is a postfix expression, get rid of ParenListExprs.
4139 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4140 if (Result.isInvalid()) return ExprError();
4141 Input = Result.get();
4143 return BuildUnaryOp(S, OpLoc, Opc, Input);
4146 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4148 /// \return true on error
4149 static bool checkArithmeticOnObjCPointer(Sema &S,
4150 SourceLocation opLoc,
4152 assert(op->getType()->isObjCObjectPointerType());
4153 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4154 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4157 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4158 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4159 << op->getSourceRange();
4163 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4164 auto *BaseNoParens = Base->IgnoreParens();
4165 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4166 return MSProp->getPropertyDecl()->getType()->isArrayType();
4167 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4171 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4172 Expr *idx, SourceLocation rbLoc) {
4173 if (base && !base->getType().isNull() &&
4174 base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4175 return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4176 /*Length=*/nullptr, rbLoc);
4178 // Since this might be a postfix expression, get rid of ParenListExprs.
4179 if (isa<ParenListExpr>(base)) {
4180 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4181 if (result.isInvalid()) return ExprError();
4182 base = result.get();
4185 // Handle any non-overload placeholder types in the base and index
4186 // expressions. We can't handle overloads here because the other
4187 // operand might be an overloadable type, in which case the overload
4188 // resolution for the operator overload should get the first crack
4190 bool IsMSPropertySubscript = false;
4191 if (base->getType()->isNonOverloadPlaceholderType()) {
4192 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4193 if (!IsMSPropertySubscript) {
4194 ExprResult result = CheckPlaceholderExpr(base);
4195 if (result.isInvalid())
4197 base = result.get();
4200 if (idx->getType()->isNonOverloadPlaceholderType()) {
4201 ExprResult result = CheckPlaceholderExpr(idx);
4202 if (result.isInvalid()) return ExprError();
4206 // Build an unanalyzed expression if either operand is type-dependent.
4207 if (getLangOpts().CPlusPlus &&
4208 (base->isTypeDependent() || idx->isTypeDependent())) {
4209 return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4210 VK_LValue, OK_Ordinary, rbLoc);
4213 // MSDN, property (C++)
4214 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4215 // This attribute can also be used in the declaration of an empty array in a
4216 // class or structure definition. For example:
4217 // __declspec(property(get=GetX, put=PutX)) int x[];
4218 // The above statement indicates that x[] can be used with one or more array
4219 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4220 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4221 if (IsMSPropertySubscript) {
4222 // Build MS property subscript expression if base is MS property reference
4223 // or MS property subscript.
4224 return new (Context) MSPropertySubscriptExpr(
4225 base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4228 // Use C++ overloaded-operator rules if either operand has record
4229 // type. The spec says to do this if either type is *overloadable*,
4230 // but enum types can't declare subscript operators or conversion
4231 // operators, so there's nothing interesting for overload resolution
4232 // to do if there aren't any record types involved.
4234 // ObjC pointers have their own subscripting logic that is not tied
4235 // to overload resolution and so should not take this path.
4236 if (getLangOpts().CPlusPlus &&
4237 (base->getType()->isRecordType() ||
4238 (!base->getType()->isObjCObjectPointerType() &&
4239 idx->getType()->isRecordType()))) {
4240 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4243 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4246 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4248 SourceLocation ColonLoc, Expr *Length,
4249 SourceLocation RBLoc) {
4250 if (Base->getType()->isPlaceholderType() &&
4251 !Base->getType()->isSpecificPlaceholderType(
4252 BuiltinType::OMPArraySection)) {
4253 ExprResult Result = CheckPlaceholderExpr(Base);
4254 if (Result.isInvalid())
4256 Base = Result.get();
4258 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4259 ExprResult Result = CheckPlaceholderExpr(LowerBound);
4260 if (Result.isInvalid())
4262 Result = DefaultLvalueConversion(Result.get());
4263 if (Result.isInvalid())
4265 LowerBound = Result.get();
4267 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4268 ExprResult Result = CheckPlaceholderExpr(Length);
4269 if (Result.isInvalid())
4271 Result = DefaultLvalueConversion(Result.get());
4272 if (Result.isInvalid())
4274 Length = Result.get();
4277 // Build an unanalyzed expression if either operand is type-dependent.
4278 if (Base->isTypeDependent() ||
4280 (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4281 (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4282 return new (Context)
4283 OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4284 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4287 // Perform default conversions.
4288 QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4290 if (OriginalTy->isAnyPointerType()) {
4291 ResultTy = OriginalTy->getPointeeType();
4292 } else if (OriginalTy->isArrayType()) {
4293 ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4296 Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4297 << Base->getSourceRange());
4301 auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4303 if (Res.isInvalid())
4304 return ExprError(Diag(LowerBound->getExprLoc(),
4305 diag::err_omp_typecheck_section_not_integer)
4306 << 0 << LowerBound->getSourceRange());
4307 LowerBound = Res.get();
4309 if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4310 LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4311 Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4312 << 0 << LowerBound->getSourceRange();
4316 PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4317 if (Res.isInvalid())
4318 return ExprError(Diag(Length->getExprLoc(),
4319 diag::err_omp_typecheck_section_not_integer)
4320 << 1 << Length->getSourceRange());
4323 if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4324 Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4325 Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4326 << 1 << Length->getSourceRange();
4329 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4330 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4331 // type. Note that functions are not objects, and that (in C99 parlance)
4332 // incomplete types are not object types.
4333 if (ResultTy->isFunctionType()) {
4334 Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4335 << ResultTy << Base->getSourceRange();
4339 if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4340 diag::err_omp_section_incomplete_type, Base))
4343 if (LowerBound && !OriginalTy->isAnyPointerType()) {
4344 llvm::APSInt LowerBoundValue;
4345 if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4346 // OpenMP 4.5, [2.4 Array Sections]
4347 // The array section must be a subset of the original array.
4348 if (LowerBoundValue.isNegative()) {
4349 Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4350 << LowerBound->getSourceRange();
4357 llvm::APSInt LengthValue;
4358 if (Length->EvaluateAsInt(LengthValue, Context)) {
4359 // OpenMP 4.5, [2.4 Array Sections]
4360 // The length must evaluate to non-negative integers.
4361 if (LengthValue.isNegative()) {
4362 Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4363 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4364 << Length->getSourceRange();
4368 } else if (ColonLoc.isValid() &&
4369 (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4370 !OriginalTy->isVariableArrayType()))) {
4371 // OpenMP 4.5, [2.4 Array Sections]
4372 // When the size of the array dimension is not known, the length must be
4373 // specified explicitly.
4374 Diag(ColonLoc, diag::err_omp_section_length_undefined)
4375 << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4379 if (!Base->getType()->isSpecificPlaceholderType(
4380 BuiltinType::OMPArraySection)) {
4381 ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4382 if (Result.isInvalid())
4384 Base = Result.get();
4386 return new (Context)
4387 OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4388 VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4392 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4393 Expr *Idx, SourceLocation RLoc) {
4394 Expr *LHSExp = Base;
4397 ExprValueKind VK = VK_LValue;
4398 ExprObjectKind OK = OK_Ordinary;
4400 // Per C++ core issue 1213, the result is an xvalue if either operand is
4401 // a non-lvalue array, and an lvalue otherwise.
4402 if (getLangOpts().CPlusPlus11 &&
4403 ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4404 (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4407 // Perform default conversions.
4408 if (!LHSExp->getType()->getAs<VectorType>()) {
4409 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4410 if (Result.isInvalid())
4412 LHSExp = Result.get();
4414 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4415 if (Result.isInvalid())
4417 RHSExp = Result.get();
4419 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4421 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4422 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4423 // in the subscript position. As a result, we need to derive the array base
4424 // and index from the expression types.
4425 Expr *BaseExpr, *IndexExpr;
4426 QualType ResultType;
4427 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4430 ResultType = Context.DependentTy;
4431 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4434 ResultType = PTy->getPointeeType();
4435 } else if (const ObjCObjectPointerType *PTy =
4436 LHSTy->getAs<ObjCObjectPointerType>()) {
4440 // Use custom logic if this should be the pseudo-object subscript
4442 if (!LangOpts.isSubscriptPointerArithmetic())
4443 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4446 ResultType = PTy->getPointeeType();
4447 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4448 // Handle the uncommon case of "123[Ptr]".
4451 ResultType = PTy->getPointeeType();
4452 } else if (const ObjCObjectPointerType *PTy =
4453 RHSTy->getAs<ObjCObjectPointerType>()) {
4454 // Handle the uncommon case of "123[Ptr]".
4457 ResultType = PTy->getPointeeType();
4458 if (!LangOpts.isSubscriptPointerArithmetic()) {
4459 Diag(LLoc, diag::err_subscript_nonfragile_interface)
4460 << ResultType << BaseExpr->getSourceRange();
4463 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4464 BaseExpr = LHSExp; // vectors: V[123]
4466 VK = LHSExp->getValueKind();
4467 if (VK != VK_RValue)
4468 OK = OK_VectorComponent;
4470 // FIXME: need to deal with const...
4471 ResultType = VTy->getElementType();
4472 } else if (LHSTy->isArrayType()) {
4473 // If we see an array that wasn't promoted by
4474 // DefaultFunctionArrayLvalueConversion, it must be an array that
4475 // wasn't promoted because of the C90 rule that doesn't
4476 // allow promoting non-lvalue arrays. Warn, then
4477 // force the promotion here.
4478 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4479 LHSExp->getSourceRange();
4480 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4481 CK_ArrayToPointerDecay).get();
4482 LHSTy = LHSExp->getType();
4486 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4487 } else if (RHSTy->isArrayType()) {
4488 // Same as previous, except for 123[f().a] case
4489 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4490 RHSExp->getSourceRange();
4491 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4492 CK_ArrayToPointerDecay).get();
4493 RHSTy = RHSExp->getType();
4497 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4499 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4500 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4503 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4504 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4505 << IndexExpr->getSourceRange());
4507 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4508 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4509 && !IndexExpr->isTypeDependent())
4510 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4512 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4513 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4514 // type. Note that Functions are not objects, and that (in C99 parlance)
4515 // incomplete types are not object types.
4516 if (ResultType->isFunctionType()) {
4517 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4518 << ResultType << BaseExpr->getSourceRange();
4522 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4523 // GNU extension: subscripting on pointer to void
4524 Diag(LLoc, diag::ext_gnu_subscript_void_type)
4525 << BaseExpr->getSourceRange();
4527 // C forbids expressions of unqualified void type from being l-values.
4528 // See IsCForbiddenLValueType.
4529 if (!ResultType.hasQualifiers()) VK = VK_RValue;
4530 } else if (!ResultType->isDependentType() &&
4531 RequireCompleteType(LLoc, ResultType,
4532 diag::err_subscript_incomplete_type, BaseExpr))
4535 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4536 !ResultType.isCForbiddenLValueType());
4538 return new (Context)
4539 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4542 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4543 ParmVarDecl *Param) {
4544 if (Param->hasUnparsedDefaultArg()) {
4546 diag::err_use_of_default_argument_to_function_declared_later) <<
4547 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4548 Diag(UnparsedDefaultArgLocs[Param],
4549 diag::note_default_argument_declared_here);
4553 if (Param->hasUninstantiatedDefaultArg()) {
4554 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4556 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4559 // Instantiate the expression.
4560 MultiLevelTemplateArgumentList MutiLevelArgList
4561 = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4563 InstantiatingTemplate Inst(*this, CallLoc, Param,
4564 MutiLevelArgList.getInnermost());
4565 if (Inst.isInvalid())
4567 if (Inst.isAlreadyInstantiating()) {
4568 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4569 Param->setInvalidDecl();
4575 // C++ [dcl.fct.default]p5:
4576 // The names in the [default argument] expression are bound, and
4577 // the semantic constraints are checked, at the point where the
4578 // default argument expression appears.
4579 ContextRAII SavedContext(*this, FD);
4580 LocalInstantiationScope Local(*this);
4581 Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4582 /*DirectInit*/false);
4584 if (Result.isInvalid())
4587 // Check the expression as an initializer for the parameter.
4588 InitializedEntity Entity
4589 = InitializedEntity::InitializeParameter(Context, Param);
4590 InitializationKind Kind
4591 = InitializationKind::CreateCopy(Param->getLocation(),
4592 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4593 Expr *ResultE = Result.getAs<Expr>();
4595 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4596 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4597 if (Result.isInvalid())
4600 Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4601 Param->getOuterLocStart());
4602 if (Result.isInvalid())
4605 // Remember the instantiated default argument.
4606 Param->setDefaultArg(Result.getAs<Expr>());
4607 if (ASTMutationListener *L = getASTMutationListener()) {
4608 L->DefaultArgumentInstantiated(Param);
4612 // If the default argument expression is not set yet, we are building it now.
4613 if (!Param->hasInit()) {
4614 Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4615 Param->setInvalidDecl();
4619 // If the default expression creates temporaries, we need to
4620 // push them to the current stack of expression temporaries so they'll
4621 // be properly destroyed.
4622 // FIXME: We should really be rebuilding the default argument with new
4623 // bound temporaries; see the comment in PR5810.
4624 // We don't need to do that with block decls, though, because
4625 // blocks in default argument expression can never capture anything.
4626 if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4627 // Set the "needs cleanups" bit regardless of whether there are
4628 // any explicit objects.
4629 Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4631 // Append all the objects to the cleanup list. Right now, this
4632 // should always be a no-op, because blocks in default argument
4633 // expressions should never be able to capture anything.
4634 assert(!Init->getNumObjects() &&
4635 "default argument expression has capturing blocks?");
4638 // We already type-checked the argument, so we know it works.
4639 // Just mark all of the declarations in this potentially-evaluated expression
4640 // as being "referenced".
4641 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4642 /*SkipLocalVariables=*/true);
4646 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4647 FunctionDecl *FD, ParmVarDecl *Param) {
4648 if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4650 return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4653 Sema::VariadicCallType
4654 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4656 if (Proto && Proto->isVariadic()) {
4657 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4658 return VariadicConstructor;
4659 else if (Fn && Fn->getType()->isBlockPointerType())
4660 return VariadicBlock;
4662 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4663 if (Method->isInstance())
4664 return VariadicMethod;
4665 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4666 return VariadicMethod;
4667 return VariadicFunction;
4669 return VariadicDoesNotApply;
4673 class FunctionCallCCC : public FunctionCallFilterCCC {
4675 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4676 unsigned NumArgs, MemberExpr *ME)
4677 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4678 FunctionName(FuncName) {}
4680 bool ValidateCandidate(const TypoCorrection &candidate) override {
4681 if (!candidate.getCorrectionSpecifier() ||
4682 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4686 return FunctionCallFilterCCC::ValidateCandidate(candidate);
4690 const IdentifierInfo *const FunctionName;
4694 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4695 FunctionDecl *FDecl,
4696 ArrayRef<Expr *> Args) {
4697 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4698 DeclarationName FuncName = FDecl->getDeclName();
4699 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4701 if (TypoCorrection Corrected = S.CorrectTypo(
4702 DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4703 S.getScopeForContext(S.CurContext), nullptr,
4704 llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4706 Sema::CTK_ErrorRecovery)) {
4707 if (NamedDecl *ND = Corrected.getFoundDecl()) {
4708 if (Corrected.isOverloaded()) {
4709 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4710 OverloadCandidateSet::iterator Best;
4711 for (NamedDecl *CD : Corrected) {
4712 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4713 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4716 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4718 ND = Best->FoundDecl;
4719 Corrected.setCorrectionDecl(ND);
4725 ND = ND->getUnderlyingDecl();
4726 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4730 return TypoCorrection();
4733 /// ConvertArgumentsForCall - Converts the arguments specified in
4734 /// Args/NumArgs to the parameter types of the function FDecl with
4735 /// function prototype Proto. Call is the call expression itself, and
4736 /// Fn is the function expression. For a C++ member function, this
4737 /// routine does not attempt to convert the object argument. Returns
4738 /// true if the call is ill-formed.
4740 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4741 FunctionDecl *FDecl,
4742 const FunctionProtoType *Proto,
4743 ArrayRef<Expr *> Args,
4744 SourceLocation RParenLoc,
4745 bool IsExecConfig) {
4746 // Bail out early if calling a builtin with custom typechecking.
4748 if (unsigned ID = FDecl->getBuiltinID())
4749 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4752 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4753 // assignment, to the types of the corresponding parameter, ...
4754 unsigned NumParams = Proto->getNumParams();
4755 bool Invalid = false;
4756 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4757 unsigned FnKind = Fn->getType()->isBlockPointerType()
4759 : (IsExecConfig ? 3 /* kernel function (exec config) */
4760 : 0 /* function */);
4762 // If too few arguments are available (and we don't have default
4763 // arguments for the remaining parameters), don't make the call.
4764 if (Args.size() < NumParams) {
4765 if (Args.size() < MinArgs) {
4767 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4769 MinArgs == NumParams && !Proto->isVariadic()
4770 ? diag::err_typecheck_call_too_few_args_suggest
4771 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4772 diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4773 << static_cast<unsigned>(Args.size())
4774 << TC.getCorrectionRange());
4775 } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4777 MinArgs == NumParams && !Proto->isVariadic()
4778 ? diag::err_typecheck_call_too_few_args_one
4779 : diag::err_typecheck_call_too_few_args_at_least_one)
4780 << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4782 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4783 ? diag::err_typecheck_call_too_few_args
4784 : diag::err_typecheck_call_too_few_args_at_least)
4785 << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4786 << Fn->getSourceRange();
4788 // Emit the location of the prototype.
4789 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4790 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4795 Call->setNumArgs(Context, NumParams);
4798 // If too many are passed and not variadic, error on the extras and drop
4800 if (Args.size() > NumParams) {
4801 if (!Proto->isVariadic()) {
4803 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4805 MinArgs == NumParams && !Proto->isVariadic()
4806 ? diag::err_typecheck_call_too_many_args_suggest
4807 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4808 diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4809 << static_cast<unsigned>(Args.size())
4810 << TC.getCorrectionRange());
4811 } else if (NumParams == 1 && FDecl &&
4812 FDecl->getParamDecl(0)->getDeclName())
4813 Diag(Args[NumParams]->getLocStart(),
4814 MinArgs == NumParams
4815 ? diag::err_typecheck_call_too_many_args_one
4816 : diag::err_typecheck_call_too_many_args_at_most_one)
4817 << FnKind << FDecl->getParamDecl(0)
4818 << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4819 << SourceRange(Args[NumParams]->getLocStart(),
4820 Args.back()->getLocEnd());
4822 Diag(Args[NumParams]->getLocStart(),
4823 MinArgs == NumParams
4824 ? diag::err_typecheck_call_too_many_args
4825 : diag::err_typecheck_call_too_many_args_at_most)
4826 << FnKind << NumParams << static_cast<unsigned>(Args.size())
4827 << Fn->getSourceRange()
4828 << SourceRange(Args[NumParams]->getLocStart(),
4829 Args.back()->getLocEnd());
4831 // Emit the location of the prototype.
4832 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4833 Diag(FDecl->getLocStart(), diag::note_callee_decl)
4836 // This deletes the extra arguments.
4837 Call->setNumArgs(Context, NumParams);
4841 SmallVector<Expr *, 8> AllArgs;
4842 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4844 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4845 Proto, 0, Args, AllArgs, CallType);
4848 unsigned TotalNumArgs = AllArgs.size();
4849 for (unsigned i = 0; i < TotalNumArgs; ++i)
4850 Call->setArg(i, AllArgs[i]);
4855 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4856 const FunctionProtoType *Proto,
4857 unsigned FirstParam, ArrayRef<Expr *> Args,
4858 SmallVectorImpl<Expr *> &AllArgs,
4859 VariadicCallType CallType, bool AllowExplicit,
4860 bool IsListInitialization) {
4861 unsigned NumParams = Proto->getNumParams();
4862 bool Invalid = false;
4864 // Continue to check argument types (even if we have too few/many args).
4865 for (unsigned i = FirstParam; i < NumParams; i++) {
4866 QualType ProtoArgType = Proto->getParamType(i);
4869 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4870 if (ArgIx < Args.size()) {
4871 Arg = Args[ArgIx++];
4873 if (RequireCompleteType(Arg->getLocStart(),
4875 diag::err_call_incomplete_argument, Arg))
4878 // Strip the unbridged-cast placeholder expression off, if applicable.
4879 bool CFAudited = false;
4880 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4881 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4882 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4883 Arg = stripARCUnbridgedCast(Arg);
4884 else if (getLangOpts().ObjCAutoRefCount &&
4885 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4886 (!Param || !Param->hasAttr<CFConsumedAttr>()))
4889 InitializedEntity Entity =
4890 Param ? InitializedEntity::InitializeParameter(Context, Param,
4892 : InitializedEntity::InitializeParameter(
4893 Context, ProtoArgType, Proto->isParamConsumed(i));
4895 // Remember that parameter belongs to a CF audited API.
4897 Entity.setParameterCFAudited();
4899 ExprResult ArgE = PerformCopyInitialization(
4900 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4901 if (ArgE.isInvalid())
4904 Arg = ArgE.getAs<Expr>();
4906 assert(Param && "can't use default arguments without a known callee");
4908 ExprResult ArgExpr =
4909 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4910 if (ArgExpr.isInvalid())
4913 Arg = ArgExpr.getAs<Expr>();
4916 // Check for array bounds violations for each argument to the call. This
4917 // check only triggers warnings when the argument isn't a more complex Expr
4918 // with its own checking, such as a BinaryOperator.
4919 CheckArrayAccess(Arg);
4921 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4922 CheckStaticArrayArgument(CallLoc, Param, Arg);
4924 AllArgs.push_back(Arg);
4927 // If this is a variadic call, handle args passed through "...".
4928 if (CallType != VariadicDoesNotApply) {
4929 // Assume that extern "C" functions with variadic arguments that
4930 // return __unknown_anytype aren't *really* variadic.
4931 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4932 FDecl->isExternC()) {
4933 for (Expr *A : Args.slice(ArgIx)) {
4934 QualType paramType; // ignored
4935 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4936 Invalid |= arg.isInvalid();
4937 AllArgs.push_back(arg.get());
4940 // Otherwise do argument promotion, (C99 6.5.2.2p7).
4942 for (Expr *A : Args.slice(ArgIx)) {
4943 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4944 Invalid |= Arg.isInvalid();
4945 AllArgs.push_back(Arg.get());
4949 // Check for array bounds violations.
4950 for (Expr *A : Args.slice(ArgIx))
4951 CheckArrayAccess(A);
4956 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4957 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4958 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4959 TL = DTL.getOriginalLoc();
4960 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4961 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4962 << ATL.getLocalSourceRange();
4965 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4966 /// array parameter, check that it is non-null, and that if it is formed by
4967 /// array-to-pointer decay, the underlying array is sufficiently large.
4969 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4970 /// array type derivation, then for each call to the function, the value of the
4971 /// corresponding actual argument shall provide access to the first element of
4972 /// an array with at least as many elements as specified by the size expression.
4974 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4976 const Expr *ArgExpr) {
4977 // Static array parameters are not supported in C++.
4978 if (!Param || getLangOpts().CPlusPlus)
4981 QualType OrigTy = Param->getOriginalType();
4983 const ArrayType *AT = Context.getAsArrayType(OrigTy);
4984 if (!AT || AT->getSizeModifier() != ArrayType::Static)
4987 if (ArgExpr->isNullPointerConstant(Context,
4988 Expr::NPC_NeverValueDependent)) {
4989 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4990 DiagnoseCalleeStaticArrayParam(*this, Param);
4994 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4998 const ConstantArrayType *ArgCAT =
4999 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
5003 if (ArgCAT->getSize().ult(CAT->getSize())) {
5004 Diag(CallLoc, diag::warn_static_array_too_small)
5005 << ArgExpr->getSourceRange()
5006 << (unsigned) ArgCAT->getSize().getZExtValue()
5007 << (unsigned) CAT->getSize().getZExtValue();
5008 DiagnoseCalleeStaticArrayParam(*this, Param);
5012 /// Given a function expression of unknown-any type, try to rebuild it
5013 /// to have a function type.
5014 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5016 /// Is the given type a placeholder that we need to lower out
5017 /// immediately during argument processing?
5018 static bool isPlaceholderToRemoveAsArg(QualType type) {
5019 // Placeholders are never sugared.
5020 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5021 if (!placeholder) return false;
5023 switch (placeholder->getKind()) {
5024 // Ignore all the non-placeholder types.
5025 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5026 case BuiltinType::Id:
5027 #include "clang/Basic/OpenCLImageTypes.def"
5028 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5029 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5030 #include "clang/AST/BuiltinTypes.def"
5033 // We cannot lower out overload sets; they might validly be resolved
5034 // by the call machinery.
5035 case BuiltinType::Overload:
5038 // Unbridged casts in ARC can be handled in some call positions and
5039 // should be left in place.
5040 case BuiltinType::ARCUnbridgedCast:
5043 // Pseudo-objects should be converted as soon as possible.
5044 case BuiltinType::PseudoObject:
5047 // The debugger mode could theoretically but currently does not try
5048 // to resolve unknown-typed arguments based on known parameter types.
5049 case BuiltinType::UnknownAny:
5052 // These are always invalid as call arguments and should be reported.
5053 case BuiltinType::BoundMember:
5054 case BuiltinType::BuiltinFn:
5055 case BuiltinType::OMPArraySection:
5059 llvm_unreachable("bad builtin type kind");
5062 /// Check an argument list for placeholders that we won't try to
5064 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5065 // Apply this processing to all the arguments at once instead of
5066 // dying at the first failure.
5067 bool hasInvalid = false;
5068 for (size_t i = 0, e = args.size(); i != e; i++) {
5069 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5070 ExprResult result = S.CheckPlaceholderExpr(args[i]);
5071 if (result.isInvalid()) hasInvalid = true;
5072 else args[i] = result.get();
5073 } else if (hasInvalid) {
5074 (void)S.CorrectDelayedTyposInExpr(args[i]);
5080 /// If a builtin function has a pointer argument with no explicit address
5081 /// space, then it should be able to accept a pointer to any address
5082 /// space as input. In order to do this, we need to replace the
5083 /// standard builtin declaration with one that uses the same address space
5086 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5087 /// it does not contain any pointer arguments without
5088 /// an address space qualifer. Otherwise the rewritten
5089 /// FunctionDecl is returned.
5090 /// TODO: Handle pointer return types.
5091 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5092 const FunctionDecl *FDecl,
5093 MultiExprArg ArgExprs) {
5095 QualType DeclType = FDecl->getType();
5096 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5098 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5099 !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5102 bool NeedsNewDecl = false;
5104 SmallVector<QualType, 8> OverloadParams;
5106 for (QualType ParamType : FT->param_types()) {
5108 // Convert array arguments to pointer to simplify type lookup.
5110 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5111 if (ArgRes.isInvalid())
5113 Expr *Arg = ArgRes.get();
5114 QualType ArgType = Arg->getType();
5115 if (!ParamType->isPointerType() ||
5116 ParamType.getQualifiers().hasAddressSpace() ||
5117 !ArgType->isPointerType() ||
5118 !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5119 OverloadParams.push_back(ParamType);
5123 NeedsNewDecl = true;
5124 unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5126 QualType PointeeType = ParamType->getPointeeType();
5127 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5128 OverloadParams.push_back(Context.getPointerType(PointeeType));
5134 FunctionProtoType::ExtProtoInfo EPI;
5135 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5136 OverloadParams, EPI);
5137 DeclContext *Parent = Context.getTranslationUnitDecl();
5138 FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5139 FDecl->getLocation(),
5140 FDecl->getLocation(),
5141 FDecl->getIdentifier(),
5145 /*hasPrototype=*/true);
5146 SmallVector<ParmVarDecl*, 16> Params;
5147 FT = cast<FunctionProtoType>(OverloadTy);
5148 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5149 QualType ParamType = FT->getParamType(i);
5151 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5152 SourceLocation(), nullptr, ParamType,
5153 /*TInfo=*/nullptr, SC_None, nullptr);
5154 Parm->setScopeInfo(0, i);
5155 Params.push_back(Parm);
5157 OverloadDecl->setParams(Params);
5158 return OverloadDecl;
5161 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5162 FunctionDecl *Callee,
5163 MultiExprArg ArgExprs) {
5164 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5165 // similar attributes) really don't like it when functions are called with an
5166 // invalid number of args.
5167 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5168 /*PartialOverloading=*/false) &&
5169 !Callee->isVariadic())
5171 if (Callee->getMinRequiredArguments() > ArgExprs.size())
5174 if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5175 S.Diag(Fn->getLocStart(),
5176 isa<CXXMethodDecl>(Callee)
5177 ? diag::err_ovl_no_viable_member_function_in_call
5178 : diag::err_ovl_no_viable_function_in_call)
5179 << Callee << Callee->getSourceRange();
5180 S.Diag(Callee->getLocation(),
5181 diag::note_ovl_candidate_disabled_by_function_cond_attr)
5182 << Attr->getCond()->getSourceRange() << Attr->getMessage();
5187 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5188 /// This provides the location of the left/right parens and a list of comma
5190 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5191 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5192 Expr *ExecConfig, bool IsExecConfig) {
5193 // Since this might be a postfix expression, get rid of ParenListExprs.
5194 ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5195 if (Result.isInvalid()) return ExprError();
5198 if (checkArgsForPlaceholders(*this, ArgExprs))
5201 if (getLangOpts().CPlusPlus) {
5202 // If this is a pseudo-destructor expression, build the call immediately.
5203 if (isa<CXXPseudoDestructorExpr>(Fn)) {
5204 if (!ArgExprs.empty()) {
5205 // Pseudo-destructor calls should not have any arguments.
5206 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5207 << FixItHint::CreateRemoval(
5208 SourceRange(ArgExprs.front()->getLocStart(),
5209 ArgExprs.back()->getLocEnd()));
5212 return new (Context)
5213 CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5215 if (Fn->getType() == Context.PseudoObjectTy) {
5216 ExprResult result = CheckPlaceholderExpr(Fn);
5217 if (result.isInvalid()) return ExprError();
5221 // Determine whether this is a dependent call inside a C++ template,
5222 // in which case we won't do any semantic analysis now.
5223 bool Dependent = false;
5224 if (Fn->isTypeDependent())
5226 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5231 return new (Context) CUDAKernelCallExpr(
5232 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5233 Context.DependentTy, VK_RValue, RParenLoc);
5235 return new (Context) CallExpr(
5236 Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5240 // Determine whether this is a call to an object (C++ [over.call.object]).
5241 if (Fn->getType()->isRecordType())
5242 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5245 if (Fn->getType() == Context.UnknownAnyTy) {
5246 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5247 if (result.isInvalid()) return ExprError();
5251 if (Fn->getType() == Context.BoundMemberTy) {
5252 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5257 // Check for overloaded calls. This can happen even in C due to extensions.
5258 if (Fn->getType() == Context.OverloadTy) {
5259 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5261 // We aren't supposed to apply this logic for if there'Scope an '&'
5263 if (!find.HasFormOfMemberPointer) {
5264 OverloadExpr *ovl = find.Expression;
5265 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5266 return BuildOverloadedCallExpr(
5267 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5268 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5269 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5274 // If we're directly calling a function, get the appropriate declaration.
5275 if (Fn->getType() == Context.UnknownAnyTy) {
5276 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5277 if (result.isInvalid()) return ExprError();
5281 Expr *NakedFn = Fn->IgnoreParens();
5283 bool CallingNDeclIndirectly = false;
5284 NamedDecl *NDecl = nullptr;
5285 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5286 if (UnOp->getOpcode() == UO_AddrOf) {
5287 CallingNDeclIndirectly = true;
5288 NakedFn = UnOp->getSubExpr()->IgnoreParens();
5292 if (isa<DeclRefExpr>(NakedFn)) {
5293 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5295 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5296 if (FDecl && FDecl->getBuiltinID()) {
5297 // Rewrite the function decl for this builtin by replacing parameters
5298 // with no explicit address space with the address space of the arguments
5301 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5303 Fn = DeclRefExpr::Create(
5304 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5305 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5308 } else if (isa<MemberExpr>(NakedFn))
5309 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5311 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5312 if (CallingNDeclIndirectly &&
5313 !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5317 if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5320 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5323 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5324 ExecConfig, IsExecConfig);
5327 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5329 /// __builtin_astype( value, dst type )
5331 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5332 SourceLocation BuiltinLoc,
5333 SourceLocation RParenLoc) {
5334 ExprValueKind VK = VK_RValue;
5335 ExprObjectKind OK = OK_Ordinary;
5336 QualType DstTy = GetTypeFromParser(ParsedDestTy);
5337 QualType SrcTy = E->getType();
5338 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5339 return ExprError(Diag(BuiltinLoc,
5340 diag::err_invalid_astype_of_different_size)
5343 << E->getSourceRange());
5344 return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5347 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5348 /// provided arguments.
5350 /// __builtin_convertvector( value, dst type )
5352 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5353 SourceLocation BuiltinLoc,
5354 SourceLocation RParenLoc) {
5355 TypeSourceInfo *TInfo;
5356 GetTypeFromParser(ParsedDestTy, &TInfo);
5357 return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5360 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5361 /// i.e. an expression not of \p OverloadTy. The expression should
5362 /// unary-convert to an expression of function-pointer or
5363 /// block-pointer type.
5365 /// \param NDecl the declaration being called, if available
5367 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5368 SourceLocation LParenLoc,
5369 ArrayRef<Expr *> Args,
5370 SourceLocation RParenLoc,
5371 Expr *Config, bool IsExecConfig) {
5372 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5373 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5375 // Functions with 'interrupt' attribute cannot be called directly.
5376 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5377 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5381 // Promote the function operand.
5382 // We special-case function promotion here because we only allow promoting
5383 // builtin functions to function pointers in the callee of a call.
5386 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5387 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5388 CK_BuiltinFnToFnPtr).get();
5390 Result = CallExprUnaryConversions(Fn);
5392 if (Result.isInvalid())
5396 // Make the call expr early, before semantic checks. This guarantees cleanup
5397 // of arguments and function on error.
5400 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5401 cast<CallExpr>(Config), Args,
5402 Context.BoolTy, VK_RValue,
5405 TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5406 VK_RValue, RParenLoc);
5408 if (!getLangOpts().CPlusPlus) {
5409 // C cannot always handle TypoExpr nodes in builtin calls and direct
5410 // function calls as their argument checking don't necessarily handle
5411 // dependent types properly, so make sure any TypoExprs have been
5413 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5414 if (!Result.isUsable()) return ExprError();
5415 TheCall = dyn_cast<CallExpr>(Result.get());
5416 if (!TheCall) return Result;
5417 Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5420 // Bail out early if calling a builtin with custom typechecking.
5421 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5422 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5425 const FunctionType *FuncT;
5426 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5427 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5428 // have type pointer to function".
5429 FuncT = PT->getPointeeType()->getAs<FunctionType>();
5431 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5432 << Fn->getType() << Fn->getSourceRange());
5433 } else if (const BlockPointerType *BPT =
5434 Fn->getType()->getAs<BlockPointerType>()) {
5435 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5437 // Handle calls to expressions of unknown-any type.
5438 if (Fn->getType() == Context.UnknownAnyTy) {
5439 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5440 if (rewrite.isInvalid()) return ExprError();
5442 TheCall->setCallee(Fn);
5446 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5447 << Fn->getType() << Fn->getSourceRange());
5450 if (getLangOpts().CUDA) {
5452 // CUDA: Kernel calls must be to global functions
5453 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5454 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5455 << FDecl->getName() << Fn->getSourceRange());
5457 // CUDA: Kernel function must have 'void' return type
5458 if (!FuncT->getReturnType()->isVoidType())
5459 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5460 << Fn->getType() << Fn->getSourceRange());
5462 // CUDA: Calls to global functions must be configured
5463 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5464 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5465 << FDecl->getName() << Fn->getSourceRange());
5469 // Check for a valid return type
5470 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5474 // We know the result type of the call, set it.
5475 TheCall->setType(FuncT->getCallResultType(Context));
5476 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5478 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5480 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5484 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5487 // Check if we have too few/too many template arguments, based
5488 // on our knowledge of the function definition.
5489 const FunctionDecl *Def = nullptr;
5490 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5491 Proto = Def->getType()->getAs<FunctionProtoType>();
5492 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5493 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5494 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5497 // If the function we're calling isn't a function prototype, but we have
5498 // a function prototype from a prior declaratiom, use that prototype.
5499 if (!FDecl->hasPrototype())
5500 Proto = FDecl->getType()->getAs<FunctionProtoType>();
5503 // Promote the arguments (C99 6.5.2.2p6).
5504 for (unsigned i = 0, e = Args.size(); i != e; i++) {
5505 Expr *Arg = Args[i];
5507 if (Proto && i < Proto->getNumParams()) {
5508 InitializedEntity Entity = InitializedEntity::InitializeParameter(
5509 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5511 PerformCopyInitialization(Entity, SourceLocation(), Arg);
5512 if (ArgE.isInvalid())
5515 Arg = ArgE.getAs<Expr>();
5518 ExprResult ArgE = DefaultArgumentPromotion(Arg);
5520 if (ArgE.isInvalid())
5523 Arg = ArgE.getAs<Expr>();
5526 if (RequireCompleteType(Arg->getLocStart(),
5528 diag::err_call_incomplete_argument, Arg))
5531 TheCall->setArg(i, Arg);
5535 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5536 if (!Method->isStatic())
5537 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5538 << Fn->getSourceRange());
5540 // Check for sentinels
5542 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5544 // Do special checking on direct calls to functions.
5546 if (CheckFunctionCall(FDecl, TheCall, Proto))
5550 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5552 if (CheckPointerCall(NDecl, TheCall, Proto))
5555 if (CheckOtherCall(TheCall, Proto))
5559 return MaybeBindToTemporary(TheCall);
5563 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5564 SourceLocation RParenLoc, Expr *InitExpr) {
5565 assert(Ty && "ActOnCompoundLiteral(): missing type");
5566 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5568 TypeSourceInfo *TInfo;
5569 QualType literalType = GetTypeFromParser(Ty, &TInfo);
5571 TInfo = Context.getTrivialTypeSourceInfo(literalType);
5573 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5577 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5578 SourceLocation RParenLoc, Expr *LiteralExpr) {
5579 QualType literalType = TInfo->getType();
5581 if (literalType->isArrayType()) {
5582 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5583 diag::err_illegal_decl_array_incomplete_type,
5584 SourceRange(LParenLoc,
5585 LiteralExpr->getSourceRange().getEnd())))
5587 if (literalType->isVariableArrayType())
5588 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5589 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5590 } else if (!literalType->isDependentType() &&
5591 RequireCompleteType(LParenLoc, literalType,
5592 diag::err_typecheck_decl_incomplete_type,
5593 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5596 InitializedEntity Entity
5597 = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5598 InitializationKind Kind
5599 = InitializationKind::CreateCStyleCast(LParenLoc,
5600 SourceRange(LParenLoc, RParenLoc),
5602 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5603 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5605 if (Result.isInvalid())
5607 LiteralExpr = Result.get();
5609 bool isFileScope = !CurContext->isFunctionOrMethod();
5611 !LiteralExpr->isTypeDependent() &&
5612 !LiteralExpr->isValueDependent() &&
5613 !literalType->isDependentType()) { // 6.5.2.5p3
5614 if (CheckForConstantInitializer(LiteralExpr, literalType))
5618 // In C, compound literals are l-values for some reason.
5619 // For GCC compatibility, in C++, file-scope array compound literals with
5620 // constant initializers are also l-values, and compound literals are
5621 // otherwise prvalues.
5623 // (GCC also treats C++ list-initialized file-scope array prvalues with
5624 // constant initializers as l-values, but that's non-conforming, so we don't
5625 // follow it there.)
5627 // FIXME: It would be better to handle the lvalue cases as materializing and
5628 // lifetime-extending a temporary object, but our materialized temporaries
5629 // representation only supports lifetime extension from a variable, not "out
5631 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5632 // is bound to the result of applying array-to-pointer decay to the compound
5634 // FIXME: GCC supports compound literals of reference type, which should
5635 // obviously have a value kind derived from the kind of reference involved.
5637 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5641 return MaybeBindToTemporary(
5642 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5643 VK, LiteralExpr, isFileScope));
5647 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5648 SourceLocation RBraceLoc) {
5649 // Immediately handle non-overload placeholders. Overloads can be
5650 // resolved contextually, but everything else here can't.
5651 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5652 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5653 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5655 // Ignore failures; dropping the entire initializer list because
5656 // of one failure would be terrible for indexing/etc.
5657 if (result.isInvalid()) continue;
5659 InitArgList[I] = result.get();
5663 // Semantic analysis for initializers is done by ActOnDeclarator() and
5664 // CheckInitializer() - it requires knowledge of the object being intialized.
5666 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5668 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5672 /// Do an explicit extend of the given block pointer if we're in ARC.
5673 void Sema::maybeExtendBlockObject(ExprResult &E) {
5674 assert(E.get()->getType()->isBlockPointerType());
5675 assert(E.get()->isRValue());
5677 // Only do this in an r-value context.
5678 if (!getLangOpts().ObjCAutoRefCount) return;
5680 E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5681 CK_ARCExtendBlockObject, E.get(),
5682 /*base path*/ nullptr, VK_RValue);
5683 Cleanup.setExprNeedsCleanups(true);
5686 /// Prepare a conversion of the given expression to an ObjC object
5688 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5689 QualType type = E.get()->getType();
5690 if (type->isObjCObjectPointerType()) {
5692 } else if (type->isBlockPointerType()) {
5693 maybeExtendBlockObject(E);
5694 return CK_BlockPointerToObjCPointerCast;
5696 assert(type->isPointerType());
5697 return CK_CPointerToObjCPointerCast;
5701 /// Prepares for a scalar cast, performing all the necessary stages
5702 /// except the final cast and returning the kind required.
5703 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5704 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5705 // Also, callers should have filtered out the invalid cases with
5706 // pointers. Everything else should be possible.
5708 QualType SrcTy = Src.get()->getType();
5709 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5712 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5713 case Type::STK_MemberPointer:
5714 llvm_unreachable("member pointer type in C");
5716 case Type::STK_CPointer:
5717 case Type::STK_BlockPointer:
5718 case Type::STK_ObjCObjectPointer:
5719 switch (DestTy->getScalarTypeKind()) {
5720 case Type::STK_CPointer: {
5721 unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5722 unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5723 if (SrcAS != DestAS)
5724 return CK_AddressSpaceConversion;
5727 case Type::STK_BlockPointer:
5728 return (SrcKind == Type::STK_BlockPointer
5729 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5730 case Type::STK_ObjCObjectPointer:
5731 if (SrcKind == Type::STK_ObjCObjectPointer)
5733 if (SrcKind == Type::STK_CPointer)
5734 return CK_CPointerToObjCPointerCast;
5735 maybeExtendBlockObject(Src);
5736 return CK_BlockPointerToObjCPointerCast;
5737 case Type::STK_Bool:
5738 return CK_PointerToBoolean;
5739 case Type::STK_Integral:
5740 return CK_PointerToIntegral;
5741 case Type::STK_Floating:
5742 case Type::STK_FloatingComplex:
5743 case Type::STK_IntegralComplex:
5744 case Type::STK_MemberPointer:
5745 llvm_unreachable("illegal cast from pointer");
5747 llvm_unreachable("Should have returned before this");
5749 case Type::STK_Bool: // casting from bool is like casting from an integer
5750 case Type::STK_Integral:
5751 switch (DestTy->getScalarTypeKind()) {
5752 case Type::STK_CPointer:
5753 case Type::STK_ObjCObjectPointer:
5754 case Type::STK_BlockPointer:
5755 if (Src.get()->isNullPointerConstant(Context,
5756 Expr::NPC_ValueDependentIsNull))
5757 return CK_NullToPointer;
5758 return CK_IntegralToPointer;
5759 case Type::STK_Bool:
5760 return CK_IntegralToBoolean;
5761 case Type::STK_Integral:
5762 return CK_IntegralCast;
5763 case Type::STK_Floating:
5764 return CK_IntegralToFloating;
5765 case Type::STK_IntegralComplex:
5766 Src = ImpCastExprToType(Src.get(),
5767 DestTy->castAs<ComplexType>()->getElementType(),
5769 return CK_IntegralRealToComplex;
5770 case Type::STK_FloatingComplex:
5771 Src = ImpCastExprToType(Src.get(),
5772 DestTy->castAs<ComplexType>()->getElementType(),
5773 CK_IntegralToFloating);
5774 return CK_FloatingRealToComplex;
5775 case Type::STK_MemberPointer:
5776 llvm_unreachable("member pointer type in C");
5778 llvm_unreachable("Should have returned before this");
5780 case Type::STK_Floating:
5781 switch (DestTy->getScalarTypeKind()) {
5782 case Type::STK_Floating:
5783 return CK_FloatingCast;
5784 case Type::STK_Bool:
5785 return CK_FloatingToBoolean;
5786 case Type::STK_Integral:
5787 return CK_FloatingToIntegral;
5788 case Type::STK_FloatingComplex:
5789 Src = ImpCastExprToType(Src.get(),
5790 DestTy->castAs<ComplexType>()->getElementType(),
5792 return CK_FloatingRealToComplex;
5793 case Type::STK_IntegralComplex:
5794 Src = ImpCastExprToType(Src.get(),
5795 DestTy->castAs<ComplexType>()->getElementType(),
5796 CK_FloatingToIntegral);
5797 return CK_IntegralRealToComplex;
5798 case Type::STK_CPointer:
5799 case Type::STK_ObjCObjectPointer:
5800 case Type::STK_BlockPointer:
5801 llvm_unreachable("valid float->pointer cast?");
5802 case Type::STK_MemberPointer:
5803 llvm_unreachable("member pointer type in C");
5805 llvm_unreachable("Should have returned before this");
5807 case Type::STK_FloatingComplex:
5808 switch (DestTy->getScalarTypeKind()) {
5809 case Type::STK_FloatingComplex:
5810 return CK_FloatingComplexCast;
5811 case Type::STK_IntegralComplex:
5812 return CK_FloatingComplexToIntegralComplex;
5813 case Type::STK_Floating: {
5814 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5815 if (Context.hasSameType(ET, DestTy))
5816 return CK_FloatingComplexToReal;
5817 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5818 return CK_FloatingCast;
5820 case Type::STK_Bool:
5821 return CK_FloatingComplexToBoolean;
5822 case Type::STK_Integral:
5823 Src = ImpCastExprToType(Src.get(),
5824 SrcTy->castAs<ComplexType>()->getElementType(),
5825 CK_FloatingComplexToReal);
5826 return CK_FloatingToIntegral;
5827 case Type::STK_CPointer:
5828 case Type::STK_ObjCObjectPointer:
5829 case Type::STK_BlockPointer:
5830 llvm_unreachable("valid complex float->pointer cast?");
5831 case Type::STK_MemberPointer:
5832 llvm_unreachable("member pointer type in C");
5834 llvm_unreachable("Should have returned before this");
5836 case Type::STK_IntegralComplex:
5837 switch (DestTy->getScalarTypeKind()) {
5838 case Type::STK_FloatingComplex:
5839 return CK_IntegralComplexToFloatingComplex;
5840 case Type::STK_IntegralComplex:
5841 return CK_IntegralComplexCast;
5842 case Type::STK_Integral: {
5843 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5844 if (Context.hasSameType(ET, DestTy))
5845 return CK_IntegralComplexToReal;
5846 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5847 return CK_IntegralCast;
5849 case Type::STK_Bool:
5850 return CK_IntegralComplexToBoolean;
5851 case Type::STK_Floating:
5852 Src = ImpCastExprToType(Src.get(),
5853 SrcTy->castAs<ComplexType>()->getElementType(),
5854 CK_IntegralComplexToReal);
5855 return CK_IntegralToFloating;
5856 case Type::STK_CPointer:
5857 case Type::STK_ObjCObjectPointer:
5858 case Type::STK_BlockPointer:
5859 llvm_unreachable("valid complex int->pointer cast?");
5860 case Type::STK_MemberPointer:
5861 llvm_unreachable("member pointer type in C");
5863 llvm_unreachable("Should have returned before this");
5866 llvm_unreachable("Unhandled scalar cast");
5869 static bool breakDownVectorType(QualType type, uint64_t &len,
5870 QualType &eltType) {
5871 // Vectors are simple.
5872 if (const VectorType *vecType = type->getAs<VectorType>()) {
5873 len = vecType->getNumElements();
5874 eltType = vecType->getElementType();
5875 assert(eltType->isScalarType());
5879 // We allow lax conversion to and from non-vector types, but only if
5880 // they're real types (i.e. non-complex, non-pointer scalar types).
5881 if (!type->isRealType()) return false;
5888 /// Are the two types lax-compatible vector types? That is, given
5889 /// that one of them is a vector, do they have equal storage sizes,
5890 /// where the storage size is the number of elements times the element
5893 /// This will also return false if either of the types is neither a
5894 /// vector nor a real type.
5895 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5896 assert(destTy->isVectorType() || srcTy->isVectorType());
5898 // Disallow lax conversions between scalars and ExtVectors (these
5899 // conversions are allowed for other vector types because common headers
5900 // depend on them). Most scalar OP ExtVector cases are handled by the
5901 // splat path anyway, which does what we want (convert, not bitcast).
5902 // What this rules out for ExtVectors is crazy things like char4*float.
5903 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5904 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5906 uint64_t srcLen, destLen;
5907 QualType srcEltTy, destEltTy;
5908 if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5909 if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5911 // ASTContext::getTypeSize will return the size rounded up to a
5912 // power of 2, so instead of using that, we need to use the raw
5913 // element size multiplied by the element count.
5914 uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5915 uint64_t destEltSize = Context.getTypeSize(destEltTy);
5917 return (srcLen * srcEltSize == destLen * destEltSize);
5920 /// Is this a legal conversion between two types, one of which is
5921 /// known to be a vector type?
5922 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5923 assert(destTy->isVectorType() || srcTy->isVectorType());
5925 if (!Context.getLangOpts().LaxVectorConversions)
5927 return areLaxCompatibleVectorTypes(srcTy, destTy);
5930 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5932 assert(VectorTy->isVectorType() && "Not a vector type!");
5934 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5935 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5936 return Diag(R.getBegin(),
5937 Ty->isVectorType() ?
5938 diag::err_invalid_conversion_between_vectors :
5939 diag::err_invalid_conversion_between_vector_and_integer)
5940 << VectorTy << Ty << R;
5942 return Diag(R.getBegin(),
5943 diag::err_invalid_conversion_between_vector_and_scalar)
5944 << VectorTy << Ty << R;
5950 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5951 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5953 if (DestElemTy == SplattedExpr->getType())
5954 return SplattedExpr;
5956 assert(DestElemTy->isFloatingType() ||
5957 DestElemTy->isIntegralOrEnumerationType());
5960 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5961 // OpenCL requires that we convert `true` boolean expressions to -1, but
5962 // only when splatting vectors.
5963 if (DestElemTy->isFloatingType()) {
5964 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5965 // in two steps: boolean to signed integral, then to floating.
5966 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5967 CK_BooleanToSignedIntegral);
5968 SplattedExpr = CastExprRes.get();
5969 CK = CK_IntegralToFloating;
5971 CK = CK_BooleanToSignedIntegral;
5974 ExprResult CastExprRes = SplattedExpr;
5975 CK = PrepareScalarCast(CastExprRes, DestElemTy);
5976 if (CastExprRes.isInvalid())
5978 SplattedExpr = CastExprRes.get();
5980 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5983 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5984 Expr *CastExpr, CastKind &Kind) {
5985 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5987 QualType SrcTy = CastExpr->getType();
5989 // If SrcTy is a VectorType, the total size must match to explicitly cast to
5990 // an ExtVectorType.
5991 // In OpenCL, casts between vectors of different types are not allowed.
5992 // (See OpenCL 6.2).
5993 if (SrcTy->isVectorType()) {
5994 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5995 || (getLangOpts().OpenCL &&
5996 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5997 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5998 << DestTy << SrcTy << R;
6005 // All non-pointer scalars can be cast to ExtVector type. The appropriate
6006 // conversion will take place first from scalar to elt type, and then
6007 // splat from elt type to vector.
6008 if (SrcTy->isPointerType())
6009 return Diag(R.getBegin(),
6010 diag::err_invalid_conversion_between_vector_and_scalar)
6011 << DestTy << SrcTy << R;
6013 Kind = CK_VectorSplat;
6014 return prepareVectorSplat(DestTy, CastExpr);
6018 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6019 Declarator &D, ParsedType &Ty,
6020 SourceLocation RParenLoc, Expr *CastExpr) {
6021 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6022 "ActOnCastExpr(): missing type or expr");
6024 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6025 if (D.isInvalidType())
6028 if (getLangOpts().CPlusPlus) {
6029 // Check that there are no default arguments (C++ only).
6030 CheckExtraCXXDefaultArguments(D);
6032 // Make sure any TypoExprs have been dealt with.
6033 ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6034 if (!Res.isUsable())
6036 CastExpr = Res.get();
6039 checkUnusedDeclAttributes(D);
6041 QualType castType = castTInfo->getType();
6042 Ty = CreateParsedType(castType, castTInfo);
6044 bool isVectorLiteral = false;
6046 // Check for an altivec or OpenCL literal,
6047 // i.e. all the elements are integer constants.
6048 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6049 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6050 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6051 && castType->isVectorType() && (PE || PLE)) {
6052 if (PLE && PLE->getNumExprs() == 0) {
6053 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6056 if (PE || PLE->getNumExprs() == 1) {
6057 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6058 if (!E->getType()->isVectorType())
6059 isVectorLiteral = true;
6062 isVectorLiteral = true;
6065 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6066 // then handle it as such.
6067 if (isVectorLiteral)
6068 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6070 // If the Expr being casted is a ParenListExpr, handle it specially.
6071 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6072 // sequence of BinOp comma operators.
6073 if (isa<ParenListExpr>(CastExpr)) {
6074 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6075 if (Result.isInvalid()) return ExprError();
6076 CastExpr = Result.get();
6079 if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6080 !getSourceManager().isInSystemMacro(LParenLoc))
6081 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6083 CheckTollFreeBridgeCast(castType, CastExpr);
6085 CheckObjCBridgeRelatedCast(castType, CastExpr);
6087 DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6089 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6092 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6093 SourceLocation RParenLoc, Expr *E,
6094 TypeSourceInfo *TInfo) {
6095 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6096 "Expected paren or paren list expression");
6101 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6102 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6103 LiteralLParenLoc = PE->getLParenLoc();
6104 LiteralRParenLoc = PE->getRParenLoc();
6105 exprs = PE->getExprs();
6106 numExprs = PE->getNumExprs();
6107 } else { // isa<ParenExpr> by assertion at function entrance
6108 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6109 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6110 subExpr = cast<ParenExpr>(E)->getSubExpr();
6115 QualType Ty = TInfo->getType();
6116 assert(Ty->isVectorType() && "Expected vector type");
6118 SmallVector<Expr *, 8> initExprs;
6119 const VectorType *VTy = Ty->getAs<VectorType>();
6120 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6122 // '(...)' form of vector initialization in AltiVec: the number of
6123 // initializers must be one or must match the size of the vector.
6124 // If a single value is specified in the initializer then it will be
6125 // replicated to all the components of the vector
6126 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6127 // The number of initializers must be one or must match the size of the
6128 // vector. If a single value is specified in the initializer then it will
6129 // be replicated to all the components of the vector
6130 if (numExprs == 1) {
6131 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6132 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6133 if (Literal.isInvalid())
6135 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6136 PrepareScalarCast(Literal, ElemTy));
6137 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6139 else if (numExprs < numElems) {
6140 Diag(E->getExprLoc(),
6141 diag::err_incorrect_number_of_vector_initializers);
6145 initExprs.append(exprs, exprs + numExprs);
6148 // For OpenCL, when the number of initializers is a single value,
6149 // it will be replicated to all components of the vector.
6150 if (getLangOpts().OpenCL &&
6151 VTy->getVectorKind() == VectorType::GenericVector &&
6153 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6154 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6155 if (Literal.isInvalid())
6157 Literal = ImpCastExprToType(Literal.get(), ElemTy,
6158 PrepareScalarCast(Literal, ElemTy));
6159 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6162 initExprs.append(exprs, exprs + numExprs);
6164 // FIXME: This means that pretty-printing the final AST will produce curly
6165 // braces instead of the original commas.
6166 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6167 initExprs, LiteralRParenLoc);
6169 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6172 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6173 /// the ParenListExpr into a sequence of comma binary operators.
6175 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6176 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6180 ExprResult Result(E->getExpr(0));
6182 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6183 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6186 if (Result.isInvalid()) return ExprError();
6188 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6191 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6194 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6198 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6199 /// constant and the other is not a pointer. Returns true if a diagnostic is
6201 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6202 SourceLocation QuestionLoc) {
6203 Expr *NullExpr = LHSExpr;
6204 Expr *NonPointerExpr = RHSExpr;
6205 Expr::NullPointerConstantKind NullKind =
6206 NullExpr->isNullPointerConstant(Context,
6207 Expr::NPC_ValueDependentIsNotNull);
6209 if (NullKind == Expr::NPCK_NotNull) {
6211 NonPointerExpr = LHSExpr;
6213 NullExpr->isNullPointerConstant(Context,
6214 Expr::NPC_ValueDependentIsNotNull);
6217 if (NullKind == Expr::NPCK_NotNull)
6220 if (NullKind == Expr::NPCK_ZeroExpression)
6223 if (NullKind == Expr::NPCK_ZeroLiteral) {
6224 // In this case, check to make sure that we got here from a "NULL"
6225 // string in the source code.
6226 NullExpr = NullExpr->IgnoreParenImpCasts();
6227 SourceLocation loc = NullExpr->getExprLoc();
6228 if (!findMacroSpelling(loc, "NULL"))
6232 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6233 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6234 << NonPointerExpr->getType() << DiagType
6235 << NonPointerExpr->getSourceRange();
6239 /// \brief Return false if the condition expression is valid, true otherwise.
6240 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6241 QualType CondTy = Cond->getType();
6243 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6244 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6245 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6246 << CondTy << Cond->getSourceRange();
6251 if (CondTy->isScalarType()) return false;
6253 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6254 << CondTy << Cond->getSourceRange();
6258 /// \brief Handle when one or both operands are void type.
6259 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6261 Expr *LHSExpr = LHS.get();
6262 Expr *RHSExpr = RHS.get();
6264 if (!LHSExpr->getType()->isVoidType())
6265 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6266 << RHSExpr->getSourceRange();
6267 if (!RHSExpr->getType()->isVoidType())
6268 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6269 << LHSExpr->getSourceRange();
6270 LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6271 RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6272 return S.Context.VoidTy;
6275 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6277 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6278 QualType PointerTy) {
6279 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6280 !NullExpr.get()->isNullPointerConstant(S.Context,
6281 Expr::NPC_ValueDependentIsNull))
6284 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6288 /// \brief Checks compatibility between two pointers and return the resulting
6290 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6292 SourceLocation Loc) {
6293 QualType LHSTy = LHS.get()->getType();
6294 QualType RHSTy = RHS.get()->getType();
6296 if (S.Context.hasSameType(LHSTy, RHSTy)) {
6297 // Two identical pointers types are always compatible.
6301 QualType lhptee, rhptee;
6303 // Get the pointee types.
6304 bool IsBlockPointer = false;
6305 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6306 lhptee = LHSBTy->getPointeeType();
6307 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6308 IsBlockPointer = true;
6310 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6311 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6314 // C99 6.5.15p6: If both operands are pointers to compatible types or to
6315 // differently qualified versions of compatible types, the result type is
6316 // a pointer to an appropriately qualified version of the composite
6319 // Only CVR-qualifiers exist in the standard, and the differently-qualified
6320 // clause doesn't make sense for our extensions. E.g. address space 2 should
6321 // be incompatible with address space 3: they may live on different devices or
6323 Qualifiers lhQual = lhptee.getQualifiers();
6324 Qualifiers rhQual = rhptee.getQualifiers();
6326 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6327 lhQual.removeCVRQualifiers();
6328 rhQual.removeCVRQualifiers();
6330 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6331 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6334 // 1. If LHS and RHS types match exactly and:
6335 // (a) AS match => use standard C rules, no bitcast or addrspacecast
6336 // (b) AS overlap => generate addrspacecast
6337 // (c) AS don't overlap => give an error
6338 // 2. if LHS and RHS types don't match:
6339 // (a) AS match => use standard C rules, generate bitcast
6340 // (b) AS overlap => generate addrspacecast instead of bitcast
6341 // (c) AS don't overlap => give an error
6343 // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6344 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6346 // OpenCL cases 1c, 2a, 2b, and 2c.
6347 if (CompositeTy.isNull()) {
6348 // In this situation, we assume void* type. No especially good
6349 // reason, but this is what gcc does, and we do have to pick
6350 // to get a consistent AST.
6351 QualType incompatTy;
6352 if (S.getLangOpts().OpenCL) {
6353 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6354 // spaces is disallowed.
6355 unsigned ResultAddrSpace;
6356 if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6358 ResultAddrSpace = lhQual.getAddressSpace();
6359 } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6361 ResultAddrSpace = rhQual.getAddressSpace();
6365 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6366 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6367 << RHS.get()->getSourceRange();
6371 // Continue handling cases 2a and 2b.
6372 incompatTy = S.Context.getPointerType(
6373 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6374 LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6375 (lhQual.getAddressSpace() != ResultAddrSpace)
6376 ? CK_AddressSpaceConversion /* 2b */
6377 : CK_BitCast /* 2a */);
6378 RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6379 (rhQual.getAddressSpace() != ResultAddrSpace)
6380 ? CK_AddressSpaceConversion /* 2b */
6381 : CK_BitCast /* 2a */);
6383 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6384 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6385 << RHS.get()->getSourceRange();
6386 incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6387 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6388 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6393 // The pointer types are compatible.
6394 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6395 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6397 ResultTy = S.Context.getBlockPointerType(ResultTy);
6399 // Cases 1a and 1b for OpenCL.
6400 auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6401 LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6402 ? CK_BitCast /* 1a */
6403 : CK_AddressSpaceConversion /* 1b */;
6404 RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6405 ? CK_BitCast /* 1a */
6406 : CK_AddressSpaceConversion /* 1b */;
6407 ResultTy = S.Context.getPointerType(ResultTy);
6410 // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6411 // if the target type does not change.
6412 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6413 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6417 /// \brief Return the resulting type when the operands are both block pointers.
6418 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6421 SourceLocation Loc) {
6422 QualType LHSTy = LHS.get()->getType();
6423 QualType RHSTy = RHS.get()->getType();
6425 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6426 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6427 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6428 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6429 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6432 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6433 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6434 << RHS.get()->getSourceRange();
6438 // We have 2 block pointer types.
6439 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6442 /// \brief Return the resulting type when the operands are both pointers.
6444 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6446 SourceLocation Loc) {
6447 // get the pointer types
6448 QualType LHSTy = LHS.get()->getType();
6449 QualType RHSTy = RHS.get()->getType();
6451 // get the "pointed to" types
6452 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6453 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6455 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6456 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6457 // Figure out necessary qualifiers (C99 6.5.15p6)
6458 QualType destPointee
6459 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6460 QualType destType = S.Context.getPointerType(destPointee);
6461 // Add qualifiers if necessary.
6462 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6463 // Promote to void*.
6464 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6467 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6468 QualType destPointee
6469 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6470 QualType destType = S.Context.getPointerType(destPointee);
6471 // Add qualifiers if necessary.
6472 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6473 // Promote to void*.
6474 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6478 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6481 /// \brief Return false if the first expression is not an integer and the second
6482 /// expression is not a pointer, true otherwise.
6483 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6484 Expr* PointerExpr, SourceLocation Loc,
6485 bool IsIntFirstExpr) {
6486 if (!PointerExpr->getType()->isPointerType() ||
6487 !Int.get()->getType()->isIntegerType())
6490 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6491 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6493 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6494 << Expr1->getType() << Expr2->getType()
6495 << Expr1->getSourceRange() << Expr2->getSourceRange();
6496 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6497 CK_IntegralToPointer);
6501 /// \brief Simple conversion between integer and floating point types.
6503 /// Used when handling the OpenCL conditional operator where the
6504 /// condition is a vector while the other operands are scalar.
6506 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6507 /// types are either integer or floating type. Between the two
6508 /// operands, the type with the higher rank is defined as the "result
6509 /// type". The other operand needs to be promoted to the same type. No
6510 /// other type promotion is allowed. We cannot use
6511 /// UsualArithmeticConversions() for this purpose, since it always
6512 /// promotes promotable types.
6513 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6515 SourceLocation QuestionLoc) {
6516 LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6517 if (LHS.isInvalid())
6519 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6520 if (RHS.isInvalid())
6523 // For conversion purposes, we ignore any qualifiers.
6524 // For example, "const float" and "float" are equivalent.
6526 S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6528 S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6530 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6531 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6532 << LHSType << LHS.get()->getSourceRange();
6536 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6537 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6538 << RHSType << RHS.get()->getSourceRange();
6542 // If both types are identical, no conversion is needed.
6543 if (LHSType == RHSType)
6546 // Now handle "real" floating types (i.e. float, double, long double).
6547 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6548 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6549 /*IsCompAssign = */ false);
6551 // Finally, we have two differing integer types.
6552 return handleIntegerConversion<doIntegralCast, doIntegralCast>
6553 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6556 /// \brief Convert scalar operands to a vector that matches the
6557 /// condition in length.
6559 /// Used when handling the OpenCL conditional operator where the
6560 /// condition is a vector while the other operands are scalar.
6562 /// We first compute the "result type" for the scalar operands
6563 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6564 /// into a vector of that type where the length matches the condition
6565 /// vector type. s6.11.6 requires that the element types of the result
6566 /// and the condition must have the same number of bits.
6568 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6569 QualType CondTy, SourceLocation QuestionLoc) {
6570 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6571 if (ResTy.isNull()) return QualType();
6573 const VectorType *CV = CondTy->getAs<VectorType>();
6576 // Determine the vector result type
6577 unsigned NumElements = CV->getNumElements();
6578 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6580 // Ensure that all types have the same number of bits
6581 if (S.Context.getTypeSize(CV->getElementType())
6582 != S.Context.getTypeSize(ResTy)) {
6583 // Since VectorTy is created internally, it does not pretty print
6584 // with an OpenCL name. Instead, we just print a description.
6585 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6586 SmallString<64> Str;
6587 llvm::raw_svector_ostream OS(Str);
6588 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6589 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6590 << CondTy << OS.str();
6594 // Convert operands to the vector result type
6595 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6596 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6601 /// \brief Return false if this is a valid OpenCL condition vector
6602 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6603 SourceLocation QuestionLoc) {
6604 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6606 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6608 QualType EleTy = CondTy->getElementType();
6609 if (EleTy->isIntegerType()) return false;
6611 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6612 << Cond->getType() << Cond->getSourceRange();
6616 /// \brief Return false if the vector condition type and the vector
6617 /// result type are compatible.
6619 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6620 /// number of elements, and their element types have the same number
6622 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6623 SourceLocation QuestionLoc) {
6624 const VectorType *CV = CondTy->getAs<VectorType>();
6625 const VectorType *RV = VecResTy->getAs<VectorType>();
6628 if (CV->getNumElements() != RV->getNumElements()) {
6629 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6630 << CondTy << VecResTy;
6634 QualType CVE = CV->getElementType();
6635 QualType RVE = RV->getElementType();
6637 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6638 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6639 << CondTy << VecResTy;
6646 /// \brief Return the resulting type for the conditional operator in
6647 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
6648 /// s6.3.i) when the condition is a vector type.
6650 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6651 ExprResult &LHS, ExprResult &RHS,
6652 SourceLocation QuestionLoc) {
6653 Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6654 if (Cond.isInvalid())
6656 QualType CondTy = Cond.get()->getType();
6658 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6661 // If either operand is a vector then find the vector type of the
6662 // result as specified in OpenCL v1.1 s6.3.i.
6663 if (LHS.get()->getType()->isVectorType() ||
6664 RHS.get()->getType()->isVectorType()) {
6665 QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6666 /*isCompAssign*/false,
6667 /*AllowBothBool*/true,
6668 /*AllowBoolConversions*/false);
6669 if (VecResTy.isNull()) return QualType();
6670 // The result type must match the condition type as specified in
6671 // OpenCL v1.1 s6.11.6.
6672 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6677 // Both operands are scalar.
6678 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6681 /// \brief Return true if the Expr is block type
6682 static bool checkBlockType(Sema &S, const Expr *E) {
6683 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6684 QualType Ty = CE->getCallee()->getType();
6685 if (Ty->isBlockPointerType()) {
6686 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6693 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6694 /// In that case, LHS = cond.
6696 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6697 ExprResult &RHS, ExprValueKind &VK,
6699 SourceLocation QuestionLoc) {
6701 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6702 if (!LHSResult.isUsable()) return QualType();
6705 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6706 if (!RHSResult.isUsable()) return QualType();
6709 // C++ is sufficiently different to merit its own checker.
6710 if (getLangOpts().CPlusPlus)
6711 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6716 // The OpenCL operator with a vector condition is sufficiently
6717 // different to merit its own checker.
6718 if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6719 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6721 // First, check the condition.
6722 Cond = UsualUnaryConversions(Cond.get());
6723 if (Cond.isInvalid())
6725 if (checkCondition(*this, Cond.get(), QuestionLoc))
6728 // Now check the two expressions.
6729 if (LHS.get()->getType()->isVectorType() ||
6730 RHS.get()->getType()->isVectorType())
6731 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6732 /*AllowBothBool*/true,
6733 /*AllowBoolConversions*/false);
6735 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6736 if (LHS.isInvalid() || RHS.isInvalid())
6739 QualType LHSTy = LHS.get()->getType();
6740 QualType RHSTy = RHS.get()->getType();
6742 // Diagnose attempts to convert between __float128 and long double where
6743 // such conversions currently can't be handled.
6744 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6746 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6747 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6751 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6752 // selection operator (?:).
6753 if (getLangOpts().OpenCL &&
6754 (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6758 // If both operands have arithmetic type, do the usual arithmetic conversions
6759 // to find a common type: C99 6.5.15p3,5.
6760 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6761 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6762 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6767 // If both operands are the same structure or union type, the result is that
6769 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
6770 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6771 if (LHSRT->getDecl() == RHSRT->getDecl())
6772 // "If both the operands have structure or union type, the result has
6773 // that type." This implies that CV qualifiers are dropped.
6774 return LHSTy.getUnqualifiedType();
6775 // FIXME: Type of conditional expression must be complete in C mode.
6778 // C99 6.5.15p5: "If both operands have void type, the result has void type."
6779 // The following || allows only one side to be void (a GCC-ism).
6780 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6781 return checkConditionalVoidType(*this, LHS, RHS);
6784 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6785 // the type of the other operand."
6786 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6787 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6789 // All objective-c pointer type analysis is done here.
6790 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6792 if (LHS.isInvalid() || RHS.isInvalid())
6794 if (!compositeType.isNull())
6795 return compositeType;
6798 // Handle block pointer types.
6799 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6800 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6803 // Check constraints for C object pointers types (C99 6.5.15p3,6).
6804 if (LHSTy->isPointerType() && RHSTy->isPointerType())
6805 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6808 // GCC compatibility: soften pointer/integer mismatch. Note that
6809 // null pointers have been filtered out by this point.
6810 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6811 /*isIntFirstExpr=*/true))
6813 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6814 /*isIntFirstExpr=*/false))
6817 // Emit a better diagnostic if one of the expressions is a null pointer
6818 // constant and the other is not a pointer type. In this case, the user most
6819 // likely forgot to take the address of the other expression.
6820 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6823 // Otherwise, the operands are not compatible.
6824 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6825 << LHSTy << RHSTy << LHS.get()->getSourceRange()
6826 << RHS.get()->getSourceRange();
6830 /// FindCompositeObjCPointerType - Helper method to find composite type of
6831 /// two objective-c pointer types of the two input expressions.
6832 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6833 SourceLocation QuestionLoc) {
6834 QualType LHSTy = LHS.get()->getType();
6835 QualType RHSTy = RHS.get()->getType();
6837 // Handle things like Class and struct objc_class*. Here we case the result
6838 // to the pseudo-builtin, because that will be implicitly cast back to the
6839 // redefinition type if an attempt is made to access its fields.
6840 if (LHSTy->isObjCClassType() &&
6841 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6842 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6845 if (RHSTy->isObjCClassType() &&
6846 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6847 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6850 // And the same for struct objc_object* / id
6851 if (LHSTy->isObjCIdType() &&
6852 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6853 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6856 if (RHSTy->isObjCIdType() &&
6857 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6858 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6861 // And the same for struct objc_selector* / SEL
6862 if (Context.isObjCSelType(LHSTy) &&
6863 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6864 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6867 if (Context.isObjCSelType(RHSTy) &&
6868 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6869 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6872 // Check constraints for Objective-C object pointers types.
6873 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6875 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6876 // Two identical object pointer types are always compatible.
6879 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6880 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6881 QualType compositeType = LHSTy;
6883 // If both operands are interfaces and either operand can be
6884 // assigned to the other, use that type as the composite
6885 // type. This allows
6886 // xxx ? (A*) a : (B*) b
6887 // where B is a subclass of A.
6889 // Additionally, as for assignment, if either type is 'id'
6890 // allow silent coercion. Finally, if the types are
6891 // incompatible then make sure to use 'id' as the composite
6892 // type so the result is acceptable for sending messages to.
6894 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6895 // It could return the composite type.
6896 if (!(compositeType =
6897 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6898 // Nothing more to do.
6899 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6900 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6901 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6902 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6903 } else if ((LHSTy->isObjCQualifiedIdType() ||
6904 RHSTy->isObjCQualifiedIdType()) &&
6905 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6906 // Need to handle "id<xx>" explicitly.
6907 // GCC allows qualified id and any Objective-C type to devolve to
6908 // id. Currently localizing to here until clear this should be
6909 // part of ObjCQualifiedIdTypesAreCompatible.
6910 compositeType = Context.getObjCIdType();
6911 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6912 compositeType = Context.getObjCIdType();
6914 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6916 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6917 QualType incompatTy = Context.getObjCIdType();
6918 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6919 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6922 // The object pointer types are compatible.
6923 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6924 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6925 return compositeType;
6927 // Check Objective-C object pointer types and 'void *'
6928 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6929 if (getLangOpts().ObjCAutoRefCount) {
6930 // ARC forbids the implicit conversion of object pointers to 'void *',
6931 // so these types are not compatible.
6932 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6933 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6937 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6938 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6939 QualType destPointee
6940 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6941 QualType destType = Context.getPointerType(destPointee);
6942 // Add qualifiers if necessary.
6943 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6944 // Promote to void*.
6945 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6948 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6949 if (getLangOpts().ObjCAutoRefCount) {
6950 // ARC forbids the implicit conversion of object pointers to 'void *',
6951 // so these types are not compatible.
6952 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6953 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6957 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6958 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6959 QualType destPointee
6960 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6961 QualType destType = Context.getPointerType(destPointee);
6962 // Add qualifiers if necessary.
6963 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6964 // Promote to void*.
6965 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6971 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6972 /// ParenRange in parentheses.
6973 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6974 const PartialDiagnostic &Note,
6975 SourceRange ParenRange) {
6976 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6977 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6979 Self.Diag(Loc, Note)
6980 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6981 << FixItHint::CreateInsertion(EndLoc, ")");
6983 // We can't display the parentheses, so just show the bare note.
6984 Self.Diag(Loc, Note) << ParenRange;
6988 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6989 return BinaryOperator::isAdditiveOp(Opc) ||
6990 BinaryOperator::isMultiplicativeOp(Opc) ||
6991 BinaryOperator::isShiftOp(Opc);
6994 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6995 /// expression, either using a built-in or overloaded operator,
6996 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6998 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7000 // Don't strip parenthesis: we should not warn if E is in parenthesis.
7001 E = E->IgnoreImpCasts();
7002 E = E->IgnoreConversionOperator();
7003 E = E->IgnoreImpCasts();
7005 // Built-in binary operator.
7006 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7007 if (IsArithmeticOp(OP->getOpcode())) {
7008 *Opcode = OP->getOpcode();
7009 *RHSExprs = OP->getRHS();
7014 // Overloaded operator.
7015 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7016 if (Call->getNumArgs() != 2)
7019 // Make sure this is really a binary operator that is safe to pass into
7020 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7021 OverloadedOperatorKind OO = Call->getOperator();
7022 if (OO < OO_Plus || OO > OO_Arrow ||
7023 OO == OO_PlusPlus || OO == OO_MinusMinus)
7026 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7027 if (IsArithmeticOp(OpKind)) {
7029 *RHSExprs = Call->getArg(1);
7037 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7038 /// or is a logical expression such as (x==y) which has int type, but is
7039 /// commonly interpreted as boolean.
7040 static bool ExprLooksBoolean(Expr *E) {
7041 E = E->IgnoreParenImpCasts();
7043 if (E->getType()->isBooleanType())
7045 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7046 return OP->isComparisonOp() || OP->isLogicalOp();
7047 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7048 return OP->getOpcode() == UO_LNot;
7049 if (E->getType()->isPointerType())
7055 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7056 /// and binary operator are mixed in a way that suggests the programmer assumed
7057 /// the conditional operator has higher precedence, for example:
7058 /// "int x = a + someBinaryCondition ? 1 : 2".
7059 static void DiagnoseConditionalPrecedence(Sema &Self,
7060 SourceLocation OpLoc,
7064 BinaryOperatorKind CondOpcode;
7067 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7069 if (!ExprLooksBoolean(CondRHS))
7072 // The condition is an arithmetic binary expression, with a right-
7073 // hand side that looks boolean, so warn.
7075 Self.Diag(OpLoc, diag::warn_precedence_conditional)
7076 << Condition->getSourceRange()
7077 << BinaryOperator::getOpcodeStr(CondOpcode);
7079 SuggestParentheses(Self, OpLoc,
7080 Self.PDiag(diag::note_precedence_silence)
7081 << BinaryOperator::getOpcodeStr(CondOpcode),
7082 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7084 SuggestParentheses(Self, OpLoc,
7085 Self.PDiag(diag::note_precedence_conditional_first),
7086 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7089 /// Compute the nullability of a conditional expression.
7090 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7091 QualType LHSTy, QualType RHSTy,
7093 if (!ResTy->isAnyPointerType())
7096 auto GetNullability = [&Ctx](QualType Ty) {
7097 Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7100 return NullabilityKind::Unspecified;
7103 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7104 NullabilityKind MergedKind;
7106 // Compute nullability of a binary conditional expression.
7108 if (LHSKind == NullabilityKind::NonNull)
7109 MergedKind = NullabilityKind::NonNull;
7111 MergedKind = RHSKind;
7112 // Compute nullability of a normal conditional expression.
7114 if (LHSKind == NullabilityKind::Nullable ||
7115 RHSKind == NullabilityKind::Nullable)
7116 MergedKind = NullabilityKind::Nullable;
7117 else if (LHSKind == NullabilityKind::NonNull)
7118 MergedKind = RHSKind;
7119 else if (RHSKind == NullabilityKind::NonNull)
7120 MergedKind = LHSKind;
7122 MergedKind = NullabilityKind::Unspecified;
7125 // Return if ResTy already has the correct nullability.
7126 if (GetNullability(ResTy) == MergedKind)
7129 // Strip all nullability from ResTy.
7130 while (ResTy->getNullability(Ctx))
7131 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7133 // Create a new AttributedType with the new nullability kind.
7134 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7135 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7138 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
7139 /// in the case of a the GNU conditional expr extension.
7140 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7141 SourceLocation ColonLoc,
7142 Expr *CondExpr, Expr *LHSExpr,
7144 if (!getLangOpts().CPlusPlus) {
7145 // C cannot handle TypoExpr nodes in the condition because it
7146 // doesn't handle dependent types properly, so make sure any TypoExprs have
7147 // been dealt with before checking the operands.
7148 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7149 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7150 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7152 if (!CondResult.isUsable())
7156 if (!LHSResult.isUsable())
7160 if (!RHSResult.isUsable())
7163 CondExpr = CondResult.get();
7164 LHSExpr = LHSResult.get();
7165 RHSExpr = RHSResult.get();
7168 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7169 // was the condition.
7170 OpaqueValueExpr *opaqueValue = nullptr;
7171 Expr *commonExpr = nullptr;
7173 commonExpr = CondExpr;
7174 // Lower out placeholder types first. This is important so that we don't
7175 // try to capture a placeholder. This happens in few cases in C++; such
7176 // as Objective-C++'s dictionary subscripting syntax.
7177 if (commonExpr->hasPlaceholderType()) {
7178 ExprResult result = CheckPlaceholderExpr(commonExpr);
7179 if (!result.isUsable()) return ExprError();
7180 commonExpr = result.get();
7182 // We usually want to apply unary conversions *before* saving, except
7183 // in the special case of a C++ l-value conditional.
7184 if (!(getLangOpts().CPlusPlus
7185 && !commonExpr->isTypeDependent()
7186 && commonExpr->getValueKind() == RHSExpr->getValueKind()
7187 && commonExpr->isGLValue()
7188 && commonExpr->isOrdinaryOrBitFieldObject()
7189 && RHSExpr->isOrdinaryOrBitFieldObject()
7190 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7191 ExprResult commonRes = UsualUnaryConversions(commonExpr);
7192 if (commonRes.isInvalid())
7194 commonExpr = commonRes.get();
7197 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7198 commonExpr->getType(),
7199 commonExpr->getValueKind(),
7200 commonExpr->getObjectKind(),
7202 LHSExpr = CondExpr = opaqueValue;
7205 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7206 ExprValueKind VK = VK_RValue;
7207 ExprObjectKind OK = OK_Ordinary;
7208 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7209 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7210 VK, OK, QuestionLoc);
7211 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7215 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7218 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7220 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7224 return new (Context)
7225 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7226 RHS.get(), result, VK, OK);
7228 return new (Context) BinaryConditionalOperator(
7229 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7230 ColonLoc, result, VK, OK);
7233 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7234 // being closely modeled after the C99 spec:-). The odd characteristic of this
7235 // routine is it effectively iqnores the qualifiers on the top level pointee.
7236 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7237 // FIXME: add a couple examples in this comment.
7238 static Sema::AssignConvertType
7239 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7240 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7241 assert(RHSType.isCanonical() && "RHS not canonicalized!");
7243 // get the "pointed to" type (ignoring qualifiers at the top level)
7244 const Type *lhptee, *rhptee;
7245 Qualifiers lhq, rhq;
7246 std::tie(lhptee, lhq) =
7247 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7248 std::tie(rhptee, rhq) =
7249 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7251 Sema::AssignConvertType ConvTy = Sema::Compatible;
7253 // C99 6.5.16.1p1: This following citation is common to constraints
7254 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7255 // qualifiers of the type *pointed to* by the right;
7257 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7258 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7259 lhq.compatiblyIncludesObjCLifetime(rhq)) {
7260 // Ignore lifetime for further calculation.
7261 lhq.removeObjCLifetime();
7262 rhq.removeObjCLifetime();
7265 if (!lhq.compatiblyIncludes(rhq)) {
7266 // Treat address-space mismatches as fatal. TODO: address subspaces
7267 if (!lhq.isAddressSpaceSupersetOf(rhq))
7268 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7270 // It's okay to add or remove GC or lifetime qualifiers when converting to
7272 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7273 .compatiblyIncludes(
7274 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7275 && (lhptee->isVoidType() || rhptee->isVoidType()))
7278 // Treat lifetime mismatches as fatal.
7279 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7280 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7282 // For GCC/MS compatibility, other qualifier mismatches are treated
7283 // as still compatible in C.
7284 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7287 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7288 // incomplete type and the other is a pointer to a qualified or unqualified
7289 // version of void...
7290 if (lhptee->isVoidType()) {
7291 if (rhptee->isIncompleteOrObjectType())
7294 // As an extension, we allow cast to/from void* to function pointer.
7295 assert(rhptee->isFunctionType());
7296 return Sema::FunctionVoidPointer;
7299 if (rhptee->isVoidType()) {
7300 if (lhptee->isIncompleteOrObjectType())
7303 // As an extension, we allow cast to/from void* to function pointer.
7304 assert(lhptee->isFunctionType());
7305 return Sema::FunctionVoidPointer;
7308 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7309 // unqualified versions of compatible types, ...
7310 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7311 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7312 // Check if the pointee types are compatible ignoring the sign.
7313 // We explicitly check for char so that we catch "char" vs
7314 // "unsigned char" on systems where "char" is unsigned.
7315 if (lhptee->isCharType())
7316 ltrans = S.Context.UnsignedCharTy;
7317 else if (lhptee->hasSignedIntegerRepresentation())
7318 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7320 if (rhptee->isCharType())
7321 rtrans = S.Context.UnsignedCharTy;
7322 else if (rhptee->hasSignedIntegerRepresentation())
7323 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7325 if (ltrans == rtrans) {
7326 // Types are compatible ignoring the sign. Qualifier incompatibility
7327 // takes priority over sign incompatibility because the sign
7328 // warning can be disabled.
7329 if (ConvTy != Sema::Compatible)
7332 return Sema::IncompatiblePointerSign;
7335 // If we are a multi-level pointer, it's possible that our issue is simply
7336 // one of qualification - e.g. char ** -> const char ** is not allowed. If
7337 // the eventual target type is the same and the pointers have the same
7338 // level of indirection, this must be the issue.
7339 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7341 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7342 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7343 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7345 if (lhptee == rhptee)
7346 return Sema::IncompatibleNestedPointerQualifiers;
7349 // General pointer incompatibility takes priority over qualifiers.
7350 return Sema::IncompatiblePointer;
7352 if (!S.getLangOpts().CPlusPlus &&
7353 S.IsFunctionConversion(ltrans, rtrans, ltrans))
7354 return Sema::IncompatiblePointer;
7358 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7359 /// block pointer types are compatible or whether a block and normal pointer
7360 /// are compatible. It is more restrict than comparing two function pointer
7362 static Sema::AssignConvertType
7363 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7365 assert(LHSType.isCanonical() && "LHS not canonicalized!");
7366 assert(RHSType.isCanonical() && "RHS not canonicalized!");
7368 QualType lhptee, rhptee;
7370 // get the "pointed to" type (ignoring qualifiers at the top level)
7371 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7372 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7374 // In C++, the types have to match exactly.
7375 if (S.getLangOpts().CPlusPlus)
7376 return Sema::IncompatibleBlockPointer;
7378 Sema::AssignConvertType ConvTy = Sema::Compatible;
7380 // For blocks we enforce that qualifiers are identical.
7381 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7382 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7384 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7385 return Sema::IncompatibleBlockPointer;
7390 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7391 /// for assignment compatibility.
7392 static Sema::AssignConvertType
7393 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7395 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7396 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7398 if (LHSType->isObjCBuiltinType()) {
7399 // Class is not compatible with ObjC object pointers.
7400 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7401 !RHSType->isObjCQualifiedClassType())
7402 return Sema::IncompatiblePointer;
7403 return Sema::Compatible;
7405 if (RHSType->isObjCBuiltinType()) {
7406 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7407 !LHSType->isObjCQualifiedClassType())
7408 return Sema::IncompatiblePointer;
7409 return Sema::Compatible;
7411 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7412 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7414 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7415 // make an exception for id<P>
7416 !LHSType->isObjCQualifiedIdType())
7417 return Sema::CompatiblePointerDiscardsQualifiers;
7419 if (S.Context.typesAreCompatible(LHSType, RHSType))
7420 return Sema::Compatible;
7421 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7422 return Sema::IncompatibleObjCQualifiedId;
7423 return Sema::IncompatiblePointer;
7426 Sema::AssignConvertType
7427 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7428 QualType LHSType, QualType RHSType) {
7429 // Fake up an opaque expression. We don't actually care about what
7430 // cast operations are required, so if CheckAssignmentConstraints
7431 // adds casts to this they'll be wasted, but fortunately that doesn't
7432 // usually happen on valid code.
7433 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7434 ExprResult RHSPtr = &RHSExpr;
7435 CastKind K = CK_Invalid;
7437 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7440 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7441 /// has code to accommodate several GCC extensions when type checking
7442 /// pointers. Here are some objectionable examples that GCC considers warnings:
7446 /// struct foo *pfoo;
7448 /// pint = pshort; // warning: assignment from incompatible pointer type
7449 /// a = pint; // warning: assignment makes integer from pointer without a cast
7450 /// pint = a; // warning: assignment makes pointer from integer without a cast
7451 /// pint = pfoo; // warning: assignment from incompatible pointer type
7453 /// As a result, the code for dealing with pointers is more complex than the
7454 /// C99 spec dictates.
7456 /// Sets 'Kind' for any result kind except Incompatible.
7457 Sema::AssignConvertType
7458 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7459 CastKind &Kind, bool ConvertRHS) {
7460 QualType RHSType = RHS.get()->getType();
7461 QualType OrigLHSType = LHSType;
7463 // Get canonical types. We're not formatting these types, just comparing
7465 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7466 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7468 // Common case: no conversion required.
7469 if (LHSType == RHSType) {
7474 // If we have an atomic type, try a non-atomic assignment, then just add an
7475 // atomic qualification step.
7476 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7477 Sema::AssignConvertType result =
7478 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7479 if (result != Compatible)
7481 if (Kind != CK_NoOp && ConvertRHS)
7482 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7483 Kind = CK_NonAtomicToAtomic;
7487 // If the left-hand side is a reference type, then we are in a
7488 // (rare!) case where we've allowed the use of references in C,
7489 // e.g., as a parameter type in a built-in function. In this case,
7490 // just make sure that the type referenced is compatible with the
7491 // right-hand side type. The caller is responsible for adjusting
7492 // LHSType so that the resulting expression does not have reference
7494 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7495 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7496 Kind = CK_LValueBitCast;
7499 return Incompatible;
7502 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7503 // to the same ExtVector type.
7504 if (LHSType->isExtVectorType()) {
7505 if (RHSType->isExtVectorType())
7506 return Incompatible;
7507 if (RHSType->isArithmeticType()) {
7508 // CK_VectorSplat does T -> vector T, so first cast to the element type.
7510 RHS = prepareVectorSplat(LHSType, RHS.get());
7511 Kind = CK_VectorSplat;
7516 // Conversions to or from vector type.
7517 if (LHSType->isVectorType() || RHSType->isVectorType()) {
7518 if (LHSType->isVectorType() && RHSType->isVectorType()) {
7519 // Allow assignments of an AltiVec vector type to an equivalent GCC
7520 // vector type and vice versa
7521 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7526 // If we are allowing lax vector conversions, and LHS and RHS are both
7527 // vectors, the total size only needs to be the same. This is a bitcast;
7528 // no bits are changed but the result type is different.
7529 if (isLaxVectorConversion(RHSType, LHSType)) {
7531 return IncompatibleVectors;
7535 // When the RHS comes from another lax conversion (e.g. binops between
7536 // scalars and vectors) the result is canonicalized as a vector. When the
7537 // LHS is also a vector, the lax is allowed by the condition above. Handle
7538 // the case where LHS is a scalar.
7539 if (LHSType->isScalarType()) {
7540 const VectorType *VecType = RHSType->getAs<VectorType>();
7541 if (VecType && VecType->getNumElements() == 1 &&
7542 isLaxVectorConversion(RHSType, LHSType)) {
7543 ExprResult *VecExpr = &RHS;
7544 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7550 return Incompatible;
7553 // Diagnose attempts to convert between __float128 and long double where
7554 // such conversions currently can't be handled.
7555 if (unsupportedTypeConversion(*this, LHSType, RHSType))
7556 return Incompatible;
7558 // Arithmetic conversions.
7559 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7560 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7562 Kind = PrepareScalarCast(RHS, LHSType);
7566 // Conversions to normal pointers.
7567 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7569 if (isa<PointerType>(RHSType)) {
7570 unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7571 unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7572 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7573 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7577 if (RHSType->isIntegerType()) {
7578 Kind = CK_IntegralToPointer; // FIXME: null?
7579 return IntToPointer;
7582 // C pointers are not compatible with ObjC object pointers,
7583 // with two exceptions:
7584 if (isa<ObjCObjectPointerType>(RHSType)) {
7585 // - conversions to void*
7586 if (LHSPointer->getPointeeType()->isVoidType()) {
7591 // - conversions from 'Class' to the redefinition type
7592 if (RHSType->isObjCClassType() &&
7593 Context.hasSameType(LHSType,
7594 Context.getObjCClassRedefinitionType())) {
7600 return IncompatiblePointer;
7604 if (RHSType->getAs<BlockPointerType>()) {
7605 if (LHSPointer->getPointeeType()->isVoidType()) {
7611 return Incompatible;
7614 // Conversions to block pointers.
7615 if (isa<BlockPointerType>(LHSType)) {
7617 if (RHSType->isBlockPointerType()) {
7619 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7622 // int or null -> T^
7623 if (RHSType->isIntegerType()) {
7624 Kind = CK_IntegralToPointer; // FIXME: null
7625 return IntToBlockPointer;
7629 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7630 Kind = CK_AnyPointerToBlockPointerCast;
7635 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7636 if (RHSPT->getPointeeType()->isVoidType()) {
7637 Kind = CK_AnyPointerToBlockPointerCast;
7641 return Incompatible;
7644 // Conversions to Objective-C pointers.
7645 if (isa<ObjCObjectPointerType>(LHSType)) {
7647 if (RHSType->isObjCObjectPointerType()) {
7649 Sema::AssignConvertType result =
7650 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7651 if (getLangOpts().ObjCAutoRefCount &&
7652 result == Compatible &&
7653 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7654 result = IncompatibleObjCWeakRef;
7658 // int or null -> A*
7659 if (RHSType->isIntegerType()) {
7660 Kind = CK_IntegralToPointer; // FIXME: null
7661 return IntToPointer;
7664 // In general, C pointers are not compatible with ObjC object pointers,
7665 // with two exceptions:
7666 if (isa<PointerType>(RHSType)) {
7667 Kind = CK_CPointerToObjCPointerCast;
7669 // - conversions from 'void*'
7670 if (RHSType->isVoidPointerType()) {
7674 // - conversions to 'Class' from its redefinition type
7675 if (LHSType->isObjCClassType() &&
7676 Context.hasSameType(RHSType,
7677 Context.getObjCClassRedefinitionType())) {
7681 return IncompatiblePointer;
7684 // Only under strict condition T^ is compatible with an Objective-C pointer.
7685 if (RHSType->isBlockPointerType() &&
7686 LHSType->isBlockCompatibleObjCPointerType(Context)) {
7688 maybeExtendBlockObject(RHS);
7689 Kind = CK_BlockPointerToObjCPointerCast;
7693 return Incompatible;
7696 // Conversions from pointers that are not covered by the above.
7697 if (isa<PointerType>(RHSType)) {
7699 if (LHSType == Context.BoolTy) {
7700 Kind = CK_PointerToBoolean;
7705 if (LHSType->isIntegerType()) {
7706 Kind = CK_PointerToIntegral;
7707 return PointerToInt;
7710 return Incompatible;
7713 // Conversions from Objective-C pointers that are not covered by the above.
7714 if (isa<ObjCObjectPointerType>(RHSType)) {
7716 if (LHSType == Context.BoolTy) {
7717 Kind = CK_PointerToBoolean;
7722 if (LHSType->isIntegerType()) {
7723 Kind = CK_PointerToIntegral;
7724 return PointerToInt;
7727 return Incompatible;
7730 // struct A -> struct B
7731 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7732 if (Context.typesAreCompatible(LHSType, RHSType)) {
7738 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7739 Kind = CK_IntToOCLSampler;
7743 return Incompatible;
7746 /// \brief Constructs a transparent union from an expression that is
7747 /// used to initialize the transparent union.
7748 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7749 ExprResult &EResult, QualType UnionType,
7751 // Build an initializer list that designates the appropriate member
7752 // of the transparent union.
7753 Expr *E = EResult.get();
7754 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7755 E, SourceLocation());
7756 Initializer->setType(UnionType);
7757 Initializer->setInitializedFieldInUnion(Field);
7759 // Build a compound literal constructing a value of the transparent
7760 // union type from this initializer list.
7761 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7762 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7763 VK_RValue, Initializer, false);
7766 Sema::AssignConvertType
7767 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7769 QualType RHSType = RHS.get()->getType();
7771 // If the ArgType is a Union type, we want to handle a potential
7772 // transparent_union GCC extension.
7773 const RecordType *UT = ArgType->getAsUnionType();
7774 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7775 return Incompatible;
7777 // The field to initialize within the transparent union.
7778 RecordDecl *UD = UT->getDecl();
7779 FieldDecl *InitField = nullptr;
7780 // It's compatible if the expression matches any of the fields.
7781 for (auto *it : UD->fields()) {
7782 if (it->getType()->isPointerType()) {
7783 // If the transparent union contains a pointer type, we allow:
7785 // 2) null pointer constant
7786 if (RHSType->isPointerType())
7787 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7788 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7793 if (RHS.get()->isNullPointerConstant(Context,
7794 Expr::NPC_ValueDependentIsNull)) {
7795 RHS = ImpCastExprToType(RHS.get(), it->getType(),
7802 CastKind Kind = CK_Invalid;
7803 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7805 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7812 return Incompatible;
7814 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7818 Sema::AssignConvertType
7819 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7821 bool DiagnoseCFAudited,
7823 // We need to be able to tell the caller whether we diagnosed a problem, if
7824 // they ask us to issue diagnostics.
7825 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7827 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7828 // we can't avoid *all* modifications at the moment, so we need some somewhere
7829 // to put the updated value.
7830 ExprResult LocalRHS = CallerRHS;
7831 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7833 if (getLangOpts().CPlusPlus) {
7834 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7835 // C++ 5.17p3: If the left operand is not of class type, the
7836 // expression is implicitly converted (C++ 4) to the
7837 // cv-unqualified type of the left operand.
7838 QualType RHSType = RHS.get()->getType();
7840 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7843 ImplicitConversionSequence ICS =
7844 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7845 /*SuppressUserConversions=*/false,
7846 /*AllowExplicit=*/false,
7847 /*InOverloadResolution=*/false,
7849 /*AllowObjCWritebackConversion=*/false);
7850 if (ICS.isFailure())
7851 return Incompatible;
7852 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7855 if (RHS.isInvalid())
7856 return Incompatible;
7857 Sema::AssignConvertType result = Compatible;
7858 if (getLangOpts().ObjCAutoRefCount &&
7859 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7860 result = IncompatibleObjCWeakRef;
7864 // FIXME: Currently, we fall through and treat C++ classes like C
7866 // FIXME: We also fall through for atomics; not sure what should
7867 // happen there, though.
7868 } else if (RHS.get()->getType() == Context.OverloadTy) {
7869 // As a set of extensions to C, we support overloading on functions. These
7870 // functions need to be resolved here.
7872 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7873 RHS.get(), LHSType, /*Complain=*/false, DAP))
7874 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7876 return Incompatible;
7879 // C99 6.5.16.1p1: the left operand is a pointer and the right is
7880 // a null pointer constant.
7881 if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7882 LHSType->isBlockPointerType()) &&
7883 RHS.get()->isNullPointerConstant(Context,
7884 Expr::NPC_ValueDependentIsNull)) {
7885 if (Diagnose || ConvertRHS) {
7888 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7889 /*IgnoreBaseAccess=*/false, Diagnose);
7891 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7896 // This check seems unnatural, however it is necessary to ensure the proper
7897 // conversion of functions/arrays. If the conversion were done for all
7898 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7899 // expressions that suppress this implicit conversion (&, sizeof).
7901 // Suppress this for references: C++ 8.5.3p5.
7902 if (!LHSType->isReferenceType()) {
7903 // FIXME: We potentially allocate here even if ConvertRHS is false.
7904 RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7905 if (RHS.isInvalid())
7906 return Incompatible;
7909 Expr *PRE = RHS.get()->IgnoreParenCasts();
7910 if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7911 ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7912 if (PDecl && !PDecl->hasDefinition()) {
7913 Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7914 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7918 CastKind Kind = CK_Invalid;
7919 Sema::AssignConvertType result =
7920 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7922 // C99 6.5.16.1p2: The value of the right operand is converted to the
7923 // type of the assignment expression.
7924 // CheckAssignmentConstraints allows the left-hand side to be a reference,
7925 // so that we can use references in built-in functions even in C.
7926 // The getNonReferenceType() call makes sure that the resulting expression
7927 // does not have reference type.
7928 if (result != Incompatible && RHS.get()->getType() != LHSType) {
7929 QualType Ty = LHSType.getNonLValueExprType(Context);
7930 Expr *E = RHS.get();
7932 // Check for various Objective-C errors. If we are not reporting
7933 // diagnostics and just checking for errors, e.g., during overload
7934 // resolution, return Incompatible to indicate the failure.
7935 if (getLangOpts().ObjCAutoRefCount &&
7936 CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7937 Diagnose, DiagnoseCFAudited) != ACR_okay) {
7939 return Incompatible;
7941 if (getLangOpts().ObjC1 &&
7942 (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7943 E->getType(), E, Diagnose) ||
7944 ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7946 return Incompatible;
7947 // Replace the expression with a corrected version and continue so we
7948 // can find further errors.
7954 RHS = ImpCastExprToType(E, Ty, Kind);
7959 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7961 Diag(Loc, diag::err_typecheck_invalid_operands)
7962 << LHS.get()->getType() << RHS.get()->getType()
7963 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7967 /// Try to convert a value of non-vector type to a vector type by converting
7968 /// the type to the element type of the vector and then performing a splat.
7969 /// If the language is OpenCL, we only use conversions that promote scalar
7970 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7973 /// \param scalar - if non-null, actually perform the conversions
7974 /// \return true if the operation fails (but without diagnosing the failure)
7975 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7977 QualType vectorEltTy,
7978 QualType vectorTy) {
7979 // The conversion to apply to the scalar before splatting it,
7981 CastKind scalarCast = CK_Invalid;
7983 if (vectorEltTy->isIntegralType(S.Context)) {
7984 if (!scalarTy->isIntegralType(S.Context))
7986 if (S.getLangOpts().OpenCL &&
7987 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7989 scalarCast = CK_IntegralCast;
7990 } else if (vectorEltTy->isRealFloatingType()) {
7991 if (scalarTy->isRealFloatingType()) {
7992 if (S.getLangOpts().OpenCL &&
7993 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7995 scalarCast = CK_FloatingCast;
7997 else if (scalarTy->isIntegralType(S.Context))
7998 scalarCast = CK_IntegralToFloating;
8005 // Adjust scalar if desired.
8007 if (scalarCast != CK_Invalid)
8008 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8009 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8014 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8015 SourceLocation Loc, bool IsCompAssign,
8017 bool AllowBoolConversions) {
8018 if (!IsCompAssign) {
8019 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8020 if (LHS.isInvalid())
8023 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8024 if (RHS.isInvalid())
8027 // For conversion purposes, we ignore any qualifiers.
8028 // For example, "const float" and "float" are equivalent.
8029 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8030 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8032 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8033 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8034 assert(LHSVecType || RHSVecType);
8036 // AltiVec-style "vector bool op vector bool" combinations are allowed
8037 // for some operators but not others.
8038 if (!AllowBothBool &&
8039 LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8040 RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8041 return InvalidOperands(Loc, LHS, RHS);
8043 // If the vector types are identical, return.
8044 if (Context.hasSameType(LHSType, RHSType))
8047 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8048 if (LHSVecType && RHSVecType &&
8049 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8050 if (isa<ExtVectorType>(LHSVecType)) {
8051 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8056 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8060 // AllowBoolConversions says that bool and non-bool AltiVec vectors
8061 // can be mixed, with the result being the non-bool type. The non-bool
8062 // operand must have integer element type.
8063 if (AllowBoolConversions && LHSVecType && RHSVecType &&
8064 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8065 (Context.getTypeSize(LHSVecType->getElementType()) ==
8066 Context.getTypeSize(RHSVecType->getElementType()))) {
8067 if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8068 LHSVecType->getElementType()->isIntegerType() &&
8069 RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8070 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8073 if (!IsCompAssign &&
8074 LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8075 RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8076 RHSVecType->getElementType()->isIntegerType()) {
8077 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8082 // If there's an ext-vector type and a scalar, try to convert the scalar to
8083 // the vector element type and splat.
8084 // FIXME: this should also work for regular vector types as supported in GCC.
8085 if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8086 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8087 LHSVecType->getElementType(), LHSType))
8090 if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8091 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8092 LHSType, RHSVecType->getElementType(),
8097 // FIXME: The code below also handles convertion between vectors and
8098 // non-scalars, we should break this down into fine grained specific checks
8099 // and emit proper diagnostics.
8100 QualType VecType = LHSVecType ? LHSType : RHSType;
8101 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8102 QualType OtherType = LHSVecType ? RHSType : LHSType;
8103 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8104 if (isLaxVectorConversion(OtherType, VecType)) {
8105 // If we're allowing lax vector conversions, only the total (data) size
8106 // needs to be the same. For non compound assignment, if one of the types is
8107 // scalar, the result is always the vector type.
8108 if (!IsCompAssign) {
8109 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8111 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8112 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8113 // type. Note that this is already done by non-compound assignments in
8114 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8115 // <1 x T> -> T. The result is also a vector type.
8116 } else if (OtherType->isExtVectorType() ||
8117 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8118 ExprResult *RHSExpr = &RHS;
8119 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8124 // Okay, the expression is invalid.
8126 // If there's a non-vector, non-real operand, diagnose that.
8127 if ((!RHSVecType && !RHSType->isRealType()) ||
8128 (!LHSVecType && !LHSType->isRealType())) {
8129 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8130 << LHSType << RHSType
8131 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8135 // OpenCL V1.1 6.2.6.p1:
8136 // If the operands are of more than one vector type, then an error shall
8137 // occur. Implicit conversions between vector types are not permitted, per
8139 if (getLangOpts().OpenCL &&
8140 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8141 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8142 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8147 // Otherwise, use the generic diagnostic.
8148 Diag(Loc, diag::err_typecheck_vector_not_convertable)
8149 << LHSType << RHSType
8150 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8154 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8155 // expression. These are mainly cases where the null pointer is used as an
8156 // integer instead of a pointer.
8157 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8158 SourceLocation Loc, bool IsCompare) {
8159 // The canonical way to check for a GNU null is with isNullPointerConstant,
8160 // but we use a bit of a hack here for speed; this is a relatively
8161 // hot path, and isNullPointerConstant is slow.
8162 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8163 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8165 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8167 // Avoid analyzing cases where the result will either be invalid (and
8168 // diagnosed as such) or entirely valid and not something to warn about.
8169 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8170 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8173 // Comparison operations would not make sense with a null pointer no matter
8174 // what the other expression is.
8176 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8177 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8178 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8182 // The rest of the operations only make sense with a null pointer
8183 // if the other expression is a pointer.
8184 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8185 NonNullType->canDecayToPointerType())
8188 S.Diag(Loc, diag::warn_null_in_comparison_operation)
8189 << LHSNull /* LHS is NULL */ << NonNullType
8190 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8193 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8195 SourceLocation Loc, bool IsDiv) {
8196 // Check for division/remainder by zero.
8197 llvm::APSInt RHSValue;
8198 if (!RHS.get()->isValueDependent() &&
8199 RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8200 S.DiagRuntimeBehavior(Loc, RHS.get(),
8201 S.PDiag(diag::warn_remainder_division_by_zero)
8202 << IsDiv << RHS.get()->getSourceRange());
8205 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8207 bool IsCompAssign, bool IsDiv) {
8208 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8210 if (LHS.get()->getType()->isVectorType() ||
8211 RHS.get()->getType()->isVectorType())
8212 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8213 /*AllowBothBool*/getLangOpts().AltiVec,
8214 /*AllowBoolConversions*/false);
8216 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8217 if (LHS.isInvalid() || RHS.isInvalid())
8221 if (compType.isNull() || !compType->isArithmeticType())
8222 return InvalidOperands(Loc, LHS, RHS);
8224 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8228 QualType Sema::CheckRemainderOperands(
8229 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8230 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8232 if (LHS.get()->getType()->isVectorType() ||
8233 RHS.get()->getType()->isVectorType()) {
8234 if (LHS.get()->getType()->hasIntegerRepresentation() &&
8235 RHS.get()->getType()->hasIntegerRepresentation())
8236 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8237 /*AllowBothBool*/getLangOpts().AltiVec,
8238 /*AllowBoolConversions*/false);
8239 return InvalidOperands(Loc, LHS, RHS);
8242 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8243 if (LHS.isInvalid() || RHS.isInvalid())
8246 if (compType.isNull() || !compType->isIntegerType())
8247 return InvalidOperands(Loc, LHS, RHS);
8248 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8252 /// \brief Diagnose invalid arithmetic on two void pointers.
8253 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8254 Expr *LHSExpr, Expr *RHSExpr) {
8255 S.Diag(Loc, S.getLangOpts().CPlusPlus
8256 ? diag::err_typecheck_pointer_arith_void_type
8257 : diag::ext_gnu_void_ptr)
8258 << 1 /* two pointers */ << LHSExpr->getSourceRange()
8259 << RHSExpr->getSourceRange();
8262 /// \brief Diagnose invalid arithmetic on a void pointer.
8263 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8265 S.Diag(Loc, S.getLangOpts().CPlusPlus
8266 ? diag::err_typecheck_pointer_arith_void_type
8267 : diag::ext_gnu_void_ptr)
8268 << 0 /* one pointer */ << Pointer->getSourceRange();
8271 /// \brief Diagnose invalid arithmetic on two function pointers.
8272 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8273 Expr *LHS, Expr *RHS) {
8274 assert(LHS->getType()->isAnyPointerType());
8275 assert(RHS->getType()->isAnyPointerType());
8276 S.Diag(Loc, S.getLangOpts().CPlusPlus
8277 ? diag::err_typecheck_pointer_arith_function_type
8278 : diag::ext_gnu_ptr_func_arith)
8279 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8280 // We only show the second type if it differs from the first.
8281 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8283 << RHS->getType()->getPointeeType()
8284 << LHS->getSourceRange() << RHS->getSourceRange();
8287 /// \brief Diagnose invalid arithmetic on a function pointer.
8288 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8290 assert(Pointer->getType()->isAnyPointerType());
8291 S.Diag(Loc, S.getLangOpts().CPlusPlus
8292 ? diag::err_typecheck_pointer_arith_function_type
8293 : diag::ext_gnu_ptr_func_arith)
8294 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8295 << 0 /* one pointer, so only one type */
8296 << Pointer->getSourceRange();
8299 /// \brief Emit error if Operand is incomplete pointer type
8301 /// \returns True if pointer has incomplete type
8302 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8304 QualType ResType = Operand->getType();
8305 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8306 ResType = ResAtomicType->getValueType();
8308 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8309 QualType PointeeTy = ResType->getPointeeType();
8310 return S.RequireCompleteType(Loc, PointeeTy,
8311 diag::err_typecheck_arithmetic_incomplete_type,
8312 PointeeTy, Operand->getSourceRange());
8315 /// \brief Check the validity of an arithmetic pointer operand.
8317 /// If the operand has pointer type, this code will check for pointer types
8318 /// which are invalid in arithmetic operations. These will be diagnosed
8319 /// appropriately, including whether or not the use is supported as an
8322 /// \returns True when the operand is valid to use (even if as an extension).
8323 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8325 QualType ResType = Operand->getType();
8326 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8327 ResType = ResAtomicType->getValueType();
8329 if (!ResType->isAnyPointerType()) return true;
8331 QualType PointeeTy = ResType->getPointeeType();
8332 if (PointeeTy->isVoidType()) {
8333 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8334 return !S.getLangOpts().CPlusPlus;
8336 if (PointeeTy->isFunctionType()) {
8337 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8338 return !S.getLangOpts().CPlusPlus;
8341 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8346 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8349 /// This routine will diagnose any invalid arithmetic on pointer operands much
8350 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8351 /// for emitting a single diagnostic even for operations where both LHS and RHS
8352 /// are (potentially problematic) pointers.
8354 /// \returns True when the operand is valid to use (even if as an extension).
8355 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8356 Expr *LHSExpr, Expr *RHSExpr) {
8357 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8358 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8359 if (!isLHSPointer && !isRHSPointer) return true;
8361 QualType LHSPointeeTy, RHSPointeeTy;
8362 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8363 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8365 // if both are pointers check if operation is valid wrt address spaces
8366 if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8367 const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8368 const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8369 if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8371 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8372 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8373 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8378 // Check for arithmetic on pointers to incomplete types.
8379 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8380 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8381 if (isLHSVoidPtr || isRHSVoidPtr) {
8382 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8383 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8384 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8386 return !S.getLangOpts().CPlusPlus;
8389 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8390 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8391 if (isLHSFuncPtr || isRHSFuncPtr) {
8392 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8393 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8395 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8397 return !S.getLangOpts().CPlusPlus;
8400 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8402 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8408 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8410 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8411 Expr *LHSExpr, Expr *RHSExpr) {
8412 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8413 Expr* IndexExpr = RHSExpr;
8415 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8416 IndexExpr = LHSExpr;
8419 bool IsStringPlusInt = StrExpr &&
8420 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8421 if (!IsStringPlusInt || IndexExpr->isValueDependent())
8425 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8426 unsigned StrLenWithNull = StrExpr->getLength() + 1;
8427 if (index.isNonNegative() &&
8428 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8429 index.isUnsigned()))
8433 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8434 Self.Diag(OpLoc, diag::warn_string_plus_int)
8435 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8437 // Only print a fixit for "str" + int, not for int + "str".
8438 if (IndexExpr == RHSExpr) {
8439 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8440 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8441 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8442 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8443 << FixItHint::CreateInsertion(EndLoc, "]");
8445 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8448 /// \brief Emit a warning when adding a char literal to a string.
8449 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8450 Expr *LHSExpr, Expr *RHSExpr) {
8451 const Expr *StringRefExpr = LHSExpr;
8452 const CharacterLiteral *CharExpr =
8453 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8456 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8457 StringRefExpr = RHSExpr;
8460 if (!CharExpr || !StringRefExpr)
8463 const QualType StringType = StringRefExpr->getType();
8465 // Return if not a PointerType.
8466 if (!StringType->isAnyPointerType())
8469 // Return if not a CharacterType.
8470 if (!StringType->getPointeeType()->isAnyCharacterType())
8473 ASTContext &Ctx = Self.getASTContext();
8474 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8476 const QualType CharType = CharExpr->getType();
8477 if (!CharType->isAnyCharacterType() &&
8478 CharType->isIntegerType() &&
8479 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8480 Self.Diag(OpLoc, diag::warn_string_plus_char)
8481 << DiagRange << Ctx.CharTy;
8483 Self.Diag(OpLoc, diag::warn_string_plus_char)
8484 << DiagRange << CharExpr->getType();
8487 // Only print a fixit for str + char, not for char + str.
8488 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8489 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8490 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8491 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8492 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8493 << FixItHint::CreateInsertion(EndLoc, "]");
8495 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8499 /// \brief Emit error when two pointers are incompatible.
8500 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8501 Expr *LHSExpr, Expr *RHSExpr) {
8502 assert(LHSExpr->getType()->isAnyPointerType());
8503 assert(RHSExpr->getType()->isAnyPointerType());
8504 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8505 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8506 << RHSExpr->getSourceRange();
8510 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8511 SourceLocation Loc, BinaryOperatorKind Opc,
8512 QualType* CompLHSTy) {
8513 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8515 if (LHS.get()->getType()->isVectorType() ||
8516 RHS.get()->getType()->isVectorType()) {
8517 QualType compType = CheckVectorOperands(
8518 LHS, RHS, Loc, CompLHSTy,
8519 /*AllowBothBool*/getLangOpts().AltiVec,
8520 /*AllowBoolConversions*/getLangOpts().ZVector);
8521 if (CompLHSTy) *CompLHSTy = compType;
8525 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8526 if (LHS.isInvalid() || RHS.isInvalid())
8529 // Diagnose "string literal" '+' int and string '+' "char literal".
8530 if (Opc == BO_Add) {
8531 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8532 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8535 // handle the common case first (both operands are arithmetic).
8536 if (!compType.isNull() && compType->isArithmeticType()) {
8537 if (CompLHSTy) *CompLHSTy = compType;
8541 // Type-checking. Ultimately the pointer's going to be in PExp;
8542 // note that we bias towards the LHS being the pointer.
8543 Expr *PExp = LHS.get(), *IExp = RHS.get();
8546 if (PExp->getType()->isPointerType()) {
8547 isObjCPointer = false;
8548 } else if (PExp->getType()->isObjCObjectPointerType()) {
8549 isObjCPointer = true;
8551 std::swap(PExp, IExp);
8552 if (PExp->getType()->isPointerType()) {
8553 isObjCPointer = false;
8554 } else if (PExp->getType()->isObjCObjectPointerType()) {
8555 isObjCPointer = true;
8557 return InvalidOperands(Loc, LHS, RHS);
8560 assert(PExp->getType()->isAnyPointerType());
8562 if (!IExp->getType()->isIntegerType())
8563 return InvalidOperands(Loc, LHS, RHS);
8565 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8568 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8571 // Check array bounds for pointer arithemtic
8572 CheckArrayAccess(PExp, IExp);
8575 QualType LHSTy = Context.isPromotableBitField(LHS.get());
8576 if (LHSTy.isNull()) {
8577 LHSTy = LHS.get()->getType();
8578 if (LHSTy->isPromotableIntegerType())
8579 LHSTy = Context.getPromotedIntegerType(LHSTy);
8584 return PExp->getType();
8588 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8590 QualType* CompLHSTy) {
8591 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8593 if (LHS.get()->getType()->isVectorType() ||
8594 RHS.get()->getType()->isVectorType()) {
8595 QualType compType = CheckVectorOperands(
8596 LHS, RHS, Loc, CompLHSTy,
8597 /*AllowBothBool*/getLangOpts().AltiVec,
8598 /*AllowBoolConversions*/getLangOpts().ZVector);
8599 if (CompLHSTy) *CompLHSTy = compType;
8603 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8604 if (LHS.isInvalid() || RHS.isInvalid())
8607 // Enforce type constraints: C99 6.5.6p3.
8609 // Handle the common case first (both operands are arithmetic).
8610 if (!compType.isNull() && compType->isArithmeticType()) {
8611 if (CompLHSTy) *CompLHSTy = compType;
8615 // Either ptr - int or ptr - ptr.
8616 if (LHS.get()->getType()->isAnyPointerType()) {
8617 QualType lpointee = LHS.get()->getType()->getPointeeType();
8619 // Diagnose bad cases where we step over interface counts.
8620 if (LHS.get()->getType()->isObjCObjectPointerType() &&
8621 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8624 // The result type of a pointer-int computation is the pointer type.
8625 if (RHS.get()->getType()->isIntegerType()) {
8626 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8629 // Check array bounds for pointer arithemtic
8630 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8631 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8633 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8634 return LHS.get()->getType();
8637 // Handle pointer-pointer subtractions.
8638 if (const PointerType *RHSPTy
8639 = RHS.get()->getType()->getAs<PointerType>()) {
8640 QualType rpointee = RHSPTy->getPointeeType();
8642 if (getLangOpts().CPlusPlus) {
8643 // Pointee types must be the same: C++ [expr.add]
8644 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8645 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8648 // Pointee types must be compatible C99 6.5.6p3
8649 if (!Context.typesAreCompatible(
8650 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8651 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8652 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8657 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8658 LHS.get(), RHS.get()))
8661 // The pointee type may have zero size. As an extension, a structure or
8662 // union may have zero size or an array may have zero length. In this
8663 // case subtraction does not make sense.
8664 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8665 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8666 if (ElementSize.isZero()) {
8667 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8668 << rpointee.getUnqualifiedType()
8669 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8673 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8674 return Context.getPointerDiffType();
8678 return InvalidOperands(Loc, LHS, RHS);
8681 static bool isScopedEnumerationType(QualType T) {
8682 if (const EnumType *ET = T->getAs<EnumType>())
8683 return ET->getDecl()->isScoped();
8687 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8688 SourceLocation Loc, BinaryOperatorKind Opc,
8690 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8691 // so skip remaining warnings as we don't want to modify values within Sema.
8692 if (S.getLangOpts().OpenCL)
8696 // Check right/shifter operand
8697 if (RHS.get()->isValueDependent() ||
8698 !RHS.get()->EvaluateAsInt(Right, S.Context))
8701 if (Right.isNegative()) {
8702 S.DiagRuntimeBehavior(Loc, RHS.get(),
8703 S.PDiag(diag::warn_shift_negative)
8704 << RHS.get()->getSourceRange());
8707 llvm::APInt LeftBits(Right.getBitWidth(),
8708 S.Context.getTypeSize(LHS.get()->getType()));
8709 if (Right.uge(LeftBits)) {
8710 S.DiagRuntimeBehavior(Loc, RHS.get(),
8711 S.PDiag(diag::warn_shift_gt_typewidth)
8712 << RHS.get()->getSourceRange());
8718 // When left shifting an ICE which is signed, we can check for overflow which
8719 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8720 // integers have defined behavior modulo one more than the maximum value
8721 // representable in the result type, so never warn for those.
8723 if (LHS.get()->isValueDependent() ||
8724 LHSType->hasUnsignedIntegerRepresentation() ||
8725 !LHS.get()->EvaluateAsInt(Left, S.Context))
8728 // If LHS does not have a signed type and non-negative value
8729 // then, the behavior is undefined. Warn about it.
8730 if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8731 S.DiagRuntimeBehavior(Loc, LHS.get(),
8732 S.PDiag(diag::warn_shift_lhs_negative)
8733 << LHS.get()->getSourceRange());
8737 llvm::APInt ResultBits =
8738 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8739 if (LeftBits.uge(ResultBits))
8741 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8742 Result = Result.shl(Right);
8744 // Print the bit representation of the signed integer as an unsigned
8745 // hexadecimal number.
8746 SmallString<40> HexResult;
8747 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8749 // If we are only missing a sign bit, this is less likely to result in actual
8750 // bugs -- if the result is cast back to an unsigned type, it will have the
8751 // expected value. Thus we place this behind a different warning that can be
8752 // turned off separately if needed.
8753 if (LeftBits == ResultBits - 1) {
8754 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8755 << HexResult << LHSType
8756 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8760 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8761 << HexResult.str() << Result.getMinSignedBits() << LHSType
8762 << Left.getBitWidth() << LHS.get()->getSourceRange()
8763 << RHS.get()->getSourceRange();
8766 /// \brief Return the resulting type when a vector is shifted
8767 /// by a scalar or vector shift amount.
8768 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8769 SourceLocation Loc, bool IsCompAssign) {
8770 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8771 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
8772 !LHS.get()->getType()->isVectorType()) {
8773 S.Diag(Loc, diag::err_shift_rhs_only_vector)
8774 << RHS.get()->getType() << LHS.get()->getType()
8775 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8779 if (!IsCompAssign) {
8780 LHS = S.UsualUnaryConversions(LHS.get());
8781 if (LHS.isInvalid()) return QualType();
8784 RHS = S.UsualUnaryConversions(RHS.get());
8785 if (RHS.isInvalid()) return QualType();
8787 QualType LHSType = LHS.get()->getType();
8788 // Note that LHS might be a scalar because the routine calls not only in
8790 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8791 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
8793 // Note that RHS might not be a vector.
8794 QualType RHSType = RHS.get()->getType();
8795 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8796 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8798 // The operands need to be integers.
8799 if (!LHSEleType->isIntegerType()) {
8800 S.Diag(Loc, diag::err_typecheck_expect_int)
8801 << LHS.get()->getType() << LHS.get()->getSourceRange();
8805 if (!RHSEleType->isIntegerType()) {
8806 S.Diag(Loc, diag::err_typecheck_expect_int)
8807 << RHS.get()->getType() << RHS.get()->getSourceRange();
8815 if (LHSEleType != RHSEleType) {
8816 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
8817 LHSEleType = RHSEleType;
8820 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
8821 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
8823 } else if (RHSVecTy) {
8824 // OpenCL v1.1 s6.3.j says that for vector types, the operators
8825 // are applied component-wise. So if RHS is a vector, then ensure
8826 // that the number of elements is the same as LHS...
8827 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8828 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8829 << LHS.get()->getType() << RHS.get()->getType()
8830 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8833 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
8834 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
8835 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
8836 if (LHSBT != RHSBT &&
8837 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
8838 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
8839 << LHS.get()->getType() << RHS.get()->getType()
8840 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8844 // ...else expand RHS to match the number of elements in LHS.
8846 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8847 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8854 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8855 SourceLocation Loc, BinaryOperatorKind Opc,
8856 bool IsCompAssign) {
8857 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8859 // Vector shifts promote their scalar inputs to vector type.
8860 if (LHS.get()->getType()->isVectorType() ||
8861 RHS.get()->getType()->isVectorType()) {
8862 if (LangOpts.ZVector) {
8863 // The shift operators for the z vector extensions work basically
8864 // like general shifts, except that neither the LHS nor the RHS is
8865 // allowed to be a "vector bool".
8866 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8867 if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8868 return InvalidOperands(Loc, LHS, RHS);
8869 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8870 if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8871 return InvalidOperands(Loc, LHS, RHS);
8873 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8876 // Shifts don't perform usual arithmetic conversions, they just do integer
8877 // promotions on each operand. C99 6.5.7p3
8879 // For the LHS, do usual unary conversions, but then reset them away
8880 // if this is a compound assignment.
8881 ExprResult OldLHS = LHS;
8882 LHS = UsualUnaryConversions(LHS.get());
8883 if (LHS.isInvalid())
8885 QualType LHSType = LHS.get()->getType();
8886 if (IsCompAssign) LHS = OldLHS;
8888 // The RHS is simpler.
8889 RHS = UsualUnaryConversions(RHS.get());
8890 if (RHS.isInvalid())
8892 QualType RHSType = RHS.get()->getType();
8894 // C99 6.5.7p2: Each of the operands shall have integer type.
8895 if (!LHSType->hasIntegerRepresentation() ||
8896 !RHSType->hasIntegerRepresentation())
8897 return InvalidOperands(Loc, LHS, RHS);
8899 // C++0x: Don't allow scoped enums. FIXME: Use something better than
8900 // hasIntegerRepresentation() above instead of this.
8901 if (isScopedEnumerationType(LHSType) ||
8902 isScopedEnumerationType(RHSType)) {
8903 return InvalidOperands(Loc, LHS, RHS);
8905 // Sanity-check shift operands
8906 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8908 // "The type of the result is that of the promoted left operand."
8912 static bool IsWithinTemplateSpecialization(Decl *D) {
8913 if (DeclContext *DC = D->getDeclContext()) {
8914 if (isa<ClassTemplateSpecializationDecl>(DC))
8916 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8917 return FD->isFunctionTemplateSpecialization();
8922 /// If two different enums are compared, raise a warning.
8923 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8925 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8926 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8928 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8931 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8935 // Ignore anonymous enums.
8936 if (!LHSEnumType->getDecl()->getIdentifier())
8938 if (!RHSEnumType->getDecl()->getIdentifier())
8941 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8944 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8945 << LHSStrippedType << RHSStrippedType
8946 << LHS->getSourceRange() << RHS->getSourceRange();
8949 /// \brief Diagnose bad pointer comparisons.
8950 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8951 ExprResult &LHS, ExprResult &RHS,
8953 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8954 : diag::ext_typecheck_comparison_of_distinct_pointers)
8955 << LHS.get()->getType() << RHS.get()->getType()
8956 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8959 /// \brief Returns false if the pointers are converted to a composite type,
8961 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8962 ExprResult &LHS, ExprResult &RHS) {
8963 // C++ [expr.rel]p2:
8964 // [...] Pointer conversions (4.10) and qualification
8965 // conversions (4.4) are performed on pointer operands (or on
8966 // a pointer operand and a null pointer constant) to bring
8967 // them to their composite pointer type. [...]
8969 // C++ [expr.eq]p1 uses the same notion for (in)equality
8970 // comparisons of pointers.
8972 QualType LHSType = LHS.get()->getType();
8973 QualType RHSType = RHS.get()->getType();
8974 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
8975 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
8977 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
8979 if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
8980 (RHSType->isPointerType() || RHSType->isMemberPointerType()))
8981 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8983 S.InvalidOperands(Loc, LHS, RHS);
8987 LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8988 RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8992 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8996 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8997 : diag::ext_typecheck_comparison_of_fptr_to_void)
8998 << LHS.get()->getType() << RHS.get()->getType()
8999 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9002 static bool isObjCObjectLiteral(ExprResult &E) {
9003 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9004 case Stmt::ObjCArrayLiteralClass:
9005 case Stmt::ObjCDictionaryLiteralClass:
9006 case Stmt::ObjCStringLiteralClass:
9007 case Stmt::ObjCBoxedExprClass:
9010 // Note that ObjCBoolLiteral is NOT an object literal!
9015 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9016 const ObjCObjectPointerType *Type =
9017 LHS->getType()->getAs<ObjCObjectPointerType>();
9019 // If this is not actually an Objective-C object, bail out.
9023 // Get the LHS object's interface type.
9024 QualType InterfaceType = Type->getPointeeType();
9026 // If the RHS isn't an Objective-C object, bail out.
9027 if (!RHS->getType()->isObjCObjectPointerType())
9030 // Try to find the -isEqual: method.
9031 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9032 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9036 if (Type->isObjCIdType()) {
9037 // For 'id', just check the global pool.
9038 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9039 /*receiverId=*/true);
9042 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9050 QualType T = Method->parameters()[0]->getType();
9051 if (!T->isObjCObjectPointerType())
9054 QualType R = Method->getReturnType();
9055 if (!R->isScalarType())
9061 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9062 FromE = FromE->IgnoreParenImpCasts();
9063 switch (FromE->getStmtClass()) {
9066 case Stmt::ObjCStringLiteralClass:
9069 case Stmt::ObjCArrayLiteralClass:
9072 case Stmt::ObjCDictionaryLiteralClass:
9073 // "dictionary literal"
9074 return LK_Dictionary;
9075 case Stmt::BlockExprClass:
9077 case Stmt::ObjCBoxedExprClass: {
9078 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9079 switch (Inner->getStmtClass()) {
9080 case Stmt::IntegerLiteralClass:
9081 case Stmt::FloatingLiteralClass:
9082 case Stmt::CharacterLiteralClass:
9083 case Stmt::ObjCBoolLiteralExprClass:
9084 case Stmt::CXXBoolLiteralExprClass:
9085 // "numeric literal"
9087 case Stmt::ImplicitCastExprClass: {
9088 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9089 // Boolean literals can be represented by implicit casts.
9090 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9103 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9104 ExprResult &LHS, ExprResult &RHS,
9105 BinaryOperator::Opcode Opc){
9108 if (isObjCObjectLiteral(LHS)) {
9109 Literal = LHS.get();
9112 Literal = RHS.get();
9116 // Don't warn on comparisons against nil.
9117 Other = Other->IgnoreParenCasts();
9118 if (Other->isNullPointerConstant(S.getASTContext(),
9119 Expr::NPC_ValueDependentIsNotNull))
9122 // This should be kept in sync with warn_objc_literal_comparison.
9123 // LK_String should always be after the other literals, since it has its own
9125 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9126 assert(LiteralKind != Sema::LK_Block);
9127 if (LiteralKind == Sema::LK_None) {
9128 llvm_unreachable("Unknown Objective-C object literal kind");
9131 if (LiteralKind == Sema::LK_String)
9132 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9133 << Literal->getSourceRange();
9135 S.Diag(Loc, diag::warn_objc_literal_comparison)
9136 << LiteralKind << Literal->getSourceRange();
9138 if (BinaryOperator::isEqualityOp(Opc) &&
9139 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9140 SourceLocation Start = LHS.get()->getLocStart();
9141 SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9142 CharSourceRange OpRange =
9143 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9145 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9146 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9147 << FixItHint::CreateReplacement(OpRange, " isEqual:")
9148 << FixItHint::CreateInsertion(End, "]");
9152 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9153 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9154 ExprResult &RHS, SourceLocation Loc,
9155 BinaryOperatorKind Opc) {
9156 // Check that left hand side is !something.
9157 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9158 if (!UO || UO->getOpcode() != UO_LNot) return;
9160 // Only check if the right hand side is non-bool arithmetic type.
9161 if (RHS.get()->isKnownToHaveBooleanValue()) return;
9163 // Make sure that the something in !something is not bool.
9164 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9165 if (SubExpr->isKnownToHaveBooleanValue()) return;
9168 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9169 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9170 << Loc << IsBitwiseOp;
9172 // First note suggest !(x < y)
9173 SourceLocation FirstOpen = SubExpr->getLocStart();
9174 SourceLocation FirstClose = RHS.get()->getLocEnd();
9175 FirstClose = S.getLocForEndOfToken(FirstClose);
9176 if (FirstClose.isInvalid())
9177 FirstOpen = SourceLocation();
9178 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9180 << FixItHint::CreateInsertion(FirstOpen, "(")
9181 << FixItHint::CreateInsertion(FirstClose, ")");
9183 // Second note suggests (!x) < y
9184 SourceLocation SecondOpen = LHS.get()->getLocStart();
9185 SourceLocation SecondClose = LHS.get()->getLocEnd();
9186 SecondClose = S.getLocForEndOfToken(SecondClose);
9187 if (SecondClose.isInvalid())
9188 SecondOpen = SourceLocation();
9189 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9190 << FixItHint::CreateInsertion(SecondOpen, "(")
9191 << FixItHint::CreateInsertion(SecondClose, ")");
9194 // Get the decl for a simple expression: a reference to a variable,
9195 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9196 static ValueDecl *getCompareDecl(Expr *E) {
9197 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9198 return DR->getDecl();
9199 if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9200 if (Ivar->isFreeIvar())
9201 return Ivar->getDecl();
9203 if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9204 if (Mem->isImplicitAccess())
9205 return Mem->getMemberDecl();
9210 // C99 6.5.8, C++ [expr.rel]
9211 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9212 SourceLocation Loc, BinaryOperatorKind Opc,
9213 bool IsRelational) {
9214 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9216 // Handle vector comparisons separately.
9217 if (LHS.get()->getType()->isVectorType() ||
9218 RHS.get()->getType()->isVectorType())
9219 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9221 QualType LHSType = LHS.get()->getType();
9222 QualType RHSType = RHS.get()->getType();
9224 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9225 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9227 checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9228 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9230 if (!LHSType->hasFloatingRepresentation() &&
9231 !(LHSType->isBlockPointerType() && IsRelational) &&
9232 !LHS.get()->getLocStart().isMacroID() &&
9233 !RHS.get()->getLocStart().isMacroID() &&
9234 ActiveTemplateInstantiations.empty()) {
9235 // For non-floating point types, check for self-comparisons of the form
9236 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9237 // often indicate logic errors in the program.
9239 // NOTE: Don't warn about comparison expressions resulting from macro
9240 // expansion. Also don't warn about comparisons which are only self
9241 // comparisons within a template specialization. The warnings should catch
9242 // obvious cases in the definition of the template anyways. The idea is to
9243 // warn when the typed comparison operator will always evaluate to the same
9245 ValueDecl *DL = getCompareDecl(LHSStripped);
9246 ValueDecl *DR = getCompareDecl(RHSStripped);
9247 if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9248 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9253 } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9254 !DL->getType()->isReferenceType() &&
9255 !DR->getType()->isReferenceType()) {
9256 // what is it always going to eval to?
9257 char always_evals_to;
9259 case BO_EQ: // e.g. array1 == array2
9260 always_evals_to = 0; // false
9262 case BO_NE: // e.g. array1 != array2
9263 always_evals_to = 1; // true
9266 // best we can say is 'a constant'
9267 always_evals_to = 2; // e.g. array1 <= array2
9270 DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9272 << always_evals_to);
9275 if (isa<CastExpr>(LHSStripped))
9276 LHSStripped = LHSStripped->IgnoreParenCasts();
9277 if (isa<CastExpr>(RHSStripped))
9278 RHSStripped = RHSStripped->IgnoreParenCasts();
9280 // Warn about comparisons against a string constant (unless the other
9281 // operand is null), the user probably wants strcmp.
9282 Expr *literalString = nullptr;
9283 Expr *literalStringStripped = nullptr;
9284 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9285 !RHSStripped->isNullPointerConstant(Context,
9286 Expr::NPC_ValueDependentIsNull)) {
9287 literalString = LHS.get();
9288 literalStringStripped = LHSStripped;
9289 } else if ((isa<StringLiteral>(RHSStripped) ||
9290 isa<ObjCEncodeExpr>(RHSStripped)) &&
9291 !LHSStripped->isNullPointerConstant(Context,
9292 Expr::NPC_ValueDependentIsNull)) {
9293 literalString = RHS.get();
9294 literalStringStripped = RHSStripped;
9297 if (literalString) {
9298 DiagRuntimeBehavior(Loc, nullptr,
9299 PDiag(diag::warn_stringcompare)
9300 << isa<ObjCEncodeExpr>(literalStringStripped)
9301 << literalString->getSourceRange());
9305 // C99 6.5.8p3 / C99 6.5.9p4
9306 UsualArithmeticConversions(LHS, RHS);
9307 if (LHS.isInvalid() || RHS.isInvalid())
9310 LHSType = LHS.get()->getType();
9311 RHSType = RHS.get()->getType();
9313 // The result of comparisons is 'bool' in C++, 'int' in C.
9314 QualType ResultTy = Context.getLogicalOperationType();
9317 if (LHSType->isRealType() && RHSType->isRealType())
9320 // Check for comparisons of floating point operands using != and ==.
9321 if (LHSType->hasFloatingRepresentation())
9322 CheckFloatComparison(Loc, LHS.get(), RHS.get());
9324 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9328 const Expr::NullPointerConstantKind LHSNullKind =
9329 LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9330 const Expr::NullPointerConstantKind RHSNullKind =
9331 RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9332 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9333 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9335 if (!IsRelational && LHSIsNull != RHSIsNull) {
9336 bool IsEquality = Opc == BO_EQ;
9338 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9339 RHS.get()->getSourceRange());
9341 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9342 LHS.get()->getSourceRange());
9345 if ((LHSType->isIntegerType() && !LHSIsNull) ||
9346 (RHSType->isIntegerType() && !RHSIsNull)) {
9347 // Skip normal pointer conversion checks in this case; we have better
9348 // diagnostics for this below.
9349 } else if (getLangOpts().CPlusPlus) {
9350 // Equality comparison of a function pointer to a void pointer is invalid,
9351 // but we allow it as an extension.
9352 // FIXME: If we really want to allow this, should it be part of composite
9353 // pointer type computation so it works in conditionals too?
9354 if (!IsRelational &&
9355 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9356 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9357 // This is a gcc extension compatibility comparison.
9358 // In a SFINAE context, we treat this as a hard error to maintain
9359 // conformance with the C++ standard.
9360 diagnoseFunctionPointerToVoidComparison(
9361 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9363 if (isSFINAEContext())
9366 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9371 // If at least one operand is a pointer [...] bring them to their
9372 // composite pointer type.
9373 // C++ [expr.rel]p2:
9374 // If both operands are pointers, [...] bring them to their composite
9376 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9377 (IsRelational ? 2 : 1)) {
9378 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9383 } else if (LHSType->isPointerType() &&
9384 RHSType->isPointerType()) { // C99 6.5.8p2
9385 // All of the following pointer-related warnings are GCC extensions, except
9386 // when handling null pointer constants.
9387 QualType LCanPointeeTy =
9388 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9389 QualType RCanPointeeTy =
9390 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9392 // C99 6.5.9p2 and C99 6.5.8p2
9393 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9394 RCanPointeeTy.getUnqualifiedType())) {
9395 // Valid unless a relational comparison of function pointers
9396 if (IsRelational && LCanPointeeTy->isFunctionType()) {
9397 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9398 << LHSType << RHSType << LHS.get()->getSourceRange()
9399 << RHS.get()->getSourceRange();
9401 } else if (!IsRelational &&
9402 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9403 // Valid unless comparison between non-null pointer and function pointer
9404 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9405 && !LHSIsNull && !RHSIsNull)
9406 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9410 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9412 if (LCanPointeeTy != RCanPointeeTy) {
9413 // Treat NULL constant as a special case in OpenCL.
9414 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9415 const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9416 if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9418 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9419 << LHSType << RHSType << 0 /* comparison */
9420 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9423 unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9424 unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9425 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9427 if (LHSIsNull && !RHSIsNull)
9428 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9430 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9435 if (getLangOpts().CPlusPlus) {
9437 // Two operands of type std::nullptr_t or one operand of type
9438 // std::nullptr_t and the other a null pointer constant compare equal.
9439 if (!IsRelational && LHSIsNull && RHSIsNull) {
9440 if (LHSType->isNullPtrType()) {
9441 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9444 if (RHSType->isNullPtrType()) {
9445 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9450 // Comparison of Objective-C pointers and block pointers against nullptr_t.
9451 // These aren't covered by the composite pointer type rules.
9452 if (!IsRelational && RHSType->isNullPtrType() &&
9453 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9454 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9457 if (!IsRelational && LHSType->isNullPtrType() &&
9458 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9459 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9464 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9465 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9466 // HACK: Relational comparison of nullptr_t against a pointer type is
9467 // invalid per DR583, but we allow it within std::less<> and friends,
9468 // since otherwise common uses of it break.
9469 // FIXME: Consider removing this hack once LWG fixes std::less<> and
9470 // friends to have std::nullptr_t overload candidates.
9471 DeclContext *DC = CurContext;
9472 if (isa<FunctionDecl>(DC))
9473 DC = DC->getParent();
9474 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9475 if (CTSD->isInStdNamespace() &&
9476 llvm::StringSwitch<bool>(CTSD->getName())
9477 .Cases("less", "less_equal", "greater", "greater_equal", true)
9479 if (RHSType->isNullPtrType())
9480 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9482 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9489 // If at least one operand is a pointer to member, [...] bring them to
9490 // their composite pointer type.
9491 if (!IsRelational &&
9492 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9493 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9499 // Handle scoped enumeration types specifically, since they don't promote
9501 if (LHS.get()->getType()->isEnumeralType() &&
9502 Context.hasSameUnqualifiedType(LHS.get()->getType(),
9503 RHS.get()->getType()))
9507 // Handle block pointer types.
9508 if (!IsRelational && LHSType->isBlockPointerType() &&
9509 RHSType->isBlockPointerType()) {
9510 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9511 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9513 if (!LHSIsNull && !RHSIsNull &&
9514 !Context.typesAreCompatible(lpointee, rpointee)) {
9515 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9516 << LHSType << RHSType << LHS.get()->getSourceRange()
9517 << RHS.get()->getSourceRange();
9519 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9523 // Allow block pointers to be compared with null pointer constants.
9525 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9526 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9527 if (!LHSIsNull && !RHSIsNull) {
9528 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9529 ->getPointeeType()->isVoidType())
9530 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9531 ->getPointeeType()->isVoidType())))
9532 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9533 << LHSType << RHSType << LHS.get()->getSourceRange()
9534 << RHS.get()->getSourceRange();
9536 if (LHSIsNull && !RHSIsNull)
9537 LHS = ImpCastExprToType(LHS.get(), RHSType,
9538 RHSType->isPointerType() ? CK_BitCast
9539 : CK_AnyPointerToBlockPointerCast);
9541 RHS = ImpCastExprToType(RHS.get(), LHSType,
9542 LHSType->isPointerType() ? CK_BitCast
9543 : CK_AnyPointerToBlockPointerCast);
9547 if (LHSType->isObjCObjectPointerType() ||
9548 RHSType->isObjCObjectPointerType()) {
9549 const PointerType *LPT = LHSType->getAs<PointerType>();
9550 const PointerType *RPT = RHSType->getAs<PointerType>();
9552 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9553 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9555 if (!LPtrToVoid && !RPtrToVoid &&
9556 !Context.typesAreCompatible(LHSType, RHSType)) {
9557 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9560 if (LHSIsNull && !RHSIsNull) {
9561 Expr *E = LHS.get();
9562 if (getLangOpts().ObjCAutoRefCount)
9563 CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9564 LHS = ImpCastExprToType(E, RHSType,
9565 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9568 Expr *E = RHS.get();
9569 if (getLangOpts().ObjCAutoRefCount)
9570 CheckObjCARCConversion(SourceRange(), LHSType, E,
9571 CCK_ImplicitConversion, /*Diagnose=*/true,
9572 /*DiagnoseCFAudited=*/false, Opc);
9573 RHS = ImpCastExprToType(E, LHSType,
9574 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9578 if (LHSType->isObjCObjectPointerType() &&
9579 RHSType->isObjCObjectPointerType()) {
9580 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9581 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9583 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9584 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9586 if (LHSIsNull && !RHSIsNull)
9587 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9589 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9593 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9594 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9595 unsigned DiagID = 0;
9596 bool isError = false;
9597 if (LangOpts.DebuggerSupport) {
9598 // Under a debugger, allow the comparison of pointers to integers,
9599 // since users tend to want to compare addresses.
9600 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9601 (RHSIsNull && RHSType->isIntegerType())) {
9603 isError = getLangOpts().CPlusPlus;
9605 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
9606 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9608 } else if (getLangOpts().CPlusPlus) {
9609 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9611 } else if (IsRelational)
9612 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9614 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9618 << LHSType << RHSType << LHS.get()->getSourceRange()
9619 << RHS.get()->getSourceRange();
9624 if (LHSType->isIntegerType())
9625 LHS = ImpCastExprToType(LHS.get(), RHSType,
9626 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9628 RHS = ImpCastExprToType(RHS.get(), LHSType,
9629 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9633 // Handle block pointers.
9634 if (!IsRelational && RHSIsNull
9635 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9636 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9639 if (!IsRelational && LHSIsNull
9640 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9641 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9645 if (getLangOpts().OpenCLVersion >= 200) {
9646 if (LHSIsNull && RHSType->isQueueT()) {
9647 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9651 if (LHSType->isQueueT() && RHSIsNull) {
9652 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9657 return InvalidOperands(Loc, LHS, RHS);
9661 // Return a signed type that is of identical size and number of elements.
9662 // For floating point vectors, return an integer type of identical size
9663 // and number of elements.
9664 QualType Sema::GetSignedVectorType(QualType V) {
9665 const VectorType *VTy = V->getAs<VectorType>();
9666 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9667 if (TypeSize == Context.getTypeSize(Context.CharTy))
9668 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9669 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9670 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9671 else if (TypeSize == Context.getTypeSize(Context.IntTy))
9672 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9673 else if (TypeSize == Context.getTypeSize(Context.LongTy))
9674 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9675 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9676 "Unhandled vector element size in vector compare");
9677 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9680 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9681 /// operates on extended vector types. Instead of producing an IntTy result,
9682 /// like a scalar comparison, a vector comparison produces a vector of integer
9684 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9686 bool IsRelational) {
9687 // Check to make sure we're operating on vectors of the same type and width,
9688 // Allowing one side to be a scalar of element type.
9689 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9690 /*AllowBothBool*/true,
9691 /*AllowBoolConversions*/getLangOpts().ZVector);
9695 QualType LHSType = LHS.get()->getType();
9697 // If AltiVec, the comparison results in a numeric type, i.e.
9698 // bool for C++, int for C
9699 if (getLangOpts().AltiVec &&
9700 vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9701 return Context.getLogicalOperationType();
9703 // For non-floating point types, check for self-comparisons of the form
9704 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
9705 // often indicate logic errors in the program.
9706 if (!LHSType->hasFloatingRepresentation() &&
9707 ActiveTemplateInstantiations.empty()) {
9708 if (DeclRefExpr* DRL
9709 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9710 if (DeclRefExpr* DRR
9711 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9712 if (DRL->getDecl() == DRR->getDecl())
9713 DiagRuntimeBehavior(Loc, nullptr,
9714 PDiag(diag::warn_comparison_always)
9716 << 2 // "a constant"
9720 // Check for comparisons of floating point operands using != and ==.
9721 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9722 assert (RHS.get()->getType()->hasFloatingRepresentation());
9723 CheckFloatComparison(Loc, LHS.get(), RHS.get());
9726 // Return a signed type for the vector.
9727 return GetSignedVectorType(vType);
9730 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9731 SourceLocation Loc) {
9732 // Ensure that either both operands are of the same vector type, or
9733 // one operand is of a vector type and the other is of its element type.
9734 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9735 /*AllowBothBool*/true,
9736 /*AllowBoolConversions*/false);
9738 return InvalidOperands(Loc, LHS, RHS);
9739 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9740 vType->hasFloatingRepresentation())
9741 return InvalidOperands(Loc, LHS, RHS);
9743 return GetSignedVectorType(LHS.get()->getType());
9746 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
9748 BinaryOperatorKind Opc) {
9749 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9752 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
9754 if (LHS.get()->getType()->isVectorType() ||
9755 RHS.get()->getType()->isVectorType()) {
9756 if (LHS.get()->getType()->hasIntegerRepresentation() &&
9757 RHS.get()->getType()->hasIntegerRepresentation())
9758 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9759 /*AllowBothBool*/true,
9760 /*AllowBoolConversions*/getLangOpts().ZVector);
9761 return InvalidOperands(Loc, LHS, RHS);
9765 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9767 ExprResult LHSResult = LHS, RHSResult = RHS;
9768 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9770 if (LHSResult.isInvalid() || RHSResult.isInvalid())
9772 LHS = LHSResult.get();
9773 RHS = RHSResult.get();
9775 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9777 return InvalidOperands(Loc, LHS, RHS);
9781 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9783 BinaryOperatorKind Opc) {
9784 // Check vector operands differently.
9785 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9786 return CheckVectorLogicalOperands(LHS, RHS, Loc);
9788 // Diagnose cases where the user write a logical and/or but probably meant a
9789 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
9791 if (LHS.get()->getType()->isIntegerType() &&
9792 !LHS.get()->getType()->isBooleanType() &&
9793 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9794 // Don't warn in macros or template instantiations.
9795 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9796 // If the RHS can be constant folded, and if it constant folds to something
9797 // that isn't 0 or 1 (which indicate a potential logical operation that
9798 // happened to fold to true/false) then warn.
9799 // Parens on the RHS are ignored.
9800 llvm::APSInt Result;
9801 if (RHS.get()->EvaluateAsInt(Result, Context))
9802 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9803 !RHS.get()->getExprLoc().isMacroID()) ||
9804 (Result != 0 && Result != 1)) {
9805 Diag(Loc, diag::warn_logical_instead_of_bitwise)
9806 << RHS.get()->getSourceRange()
9807 << (Opc == BO_LAnd ? "&&" : "||");
9808 // Suggest replacing the logical operator with the bitwise version
9809 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9810 << (Opc == BO_LAnd ? "&" : "|")
9811 << FixItHint::CreateReplacement(SourceRange(
9812 Loc, getLocForEndOfToken(Loc)),
9813 Opc == BO_LAnd ? "&" : "|");
9815 // Suggest replacing "Foo() && kNonZero" with "Foo()"
9816 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9817 << FixItHint::CreateRemoval(
9818 SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9819 RHS.get()->getLocEnd()));
9823 if (!Context.getLangOpts().CPlusPlus) {
9824 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9825 // not operate on the built-in scalar and vector float types.
9826 if (Context.getLangOpts().OpenCL &&
9827 Context.getLangOpts().OpenCLVersion < 120) {
9828 if (LHS.get()->getType()->isFloatingType() ||
9829 RHS.get()->getType()->isFloatingType())
9830 return InvalidOperands(Loc, LHS, RHS);
9833 LHS = UsualUnaryConversions(LHS.get());
9834 if (LHS.isInvalid())
9837 RHS = UsualUnaryConversions(RHS.get());
9838 if (RHS.isInvalid())
9841 if (!LHS.get()->getType()->isScalarType() ||
9842 !RHS.get()->getType()->isScalarType())
9843 return InvalidOperands(Loc, LHS, RHS);
9845 return Context.IntTy;
9848 // The following is safe because we only use this method for
9849 // non-overloadable operands.
9851 // C++ [expr.log.and]p1
9852 // C++ [expr.log.or]p1
9853 // The operands are both contextually converted to type bool.
9854 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9855 if (LHSRes.isInvalid())
9856 return InvalidOperands(Loc, LHS, RHS);
9859 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9860 if (RHSRes.isInvalid())
9861 return InvalidOperands(Loc, LHS, RHS);
9864 // C++ [expr.log.and]p2
9865 // C++ [expr.log.or]p2
9866 // The result is a bool.
9867 return Context.BoolTy;
9870 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9871 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9872 if (!ME) return false;
9873 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9874 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
9875 ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
9876 if (!Base) return false;
9877 return Base->getMethodDecl() != nullptr;
9880 /// Is the given expression (which must be 'const') a reference to a
9881 /// variable which was originally non-const, but which has become
9882 /// 'const' due to being captured within a block?
9883 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9884 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9885 assert(E->isLValue() && E->getType().isConstQualified());
9886 E = E->IgnoreParens();
9888 // Must be a reference to a declaration from an enclosing scope.
9889 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9890 if (!DRE) return NCCK_None;
9891 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9893 // The declaration must be a variable which is not declared 'const'.
9894 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9895 if (!var) return NCCK_None;
9896 if (var->getType().isConstQualified()) return NCCK_None;
9897 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9899 // Decide whether the first capture was for a block or a lambda.
9900 DeclContext *DC = S.CurContext, *Prev = nullptr;
9901 // Decide whether the first capture was for a block or a lambda.
9903 // For init-capture, it is possible that the variable belongs to the
9904 // template pattern of the current context.
9905 if (auto *FD = dyn_cast<FunctionDecl>(DC))
9906 if (var->isInitCapture() &&
9907 FD->getTemplateInstantiationPattern() == var->getDeclContext())
9909 if (DC == var->getDeclContext())
9912 DC = DC->getParent();
9914 // Unless we have an init-capture, we've gone one step too far.
9915 if (!var->isInitCapture())
9917 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9920 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9921 Ty = Ty.getNonReferenceType();
9922 if (IsDereference && Ty->isPointerType())
9923 Ty = Ty->getPointeeType();
9924 return !Ty.isConstQualified();
9927 /// Emit the "read-only variable not assignable" error and print notes to give
9928 /// more information about why the variable is not assignable, such as pointing
9929 /// to the declaration of a const variable, showing that a method is const, or
9930 /// that the function is returning a const reference.
9931 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9932 SourceLocation Loc) {
9933 // Update err_typecheck_assign_const and note_typecheck_assign_const
9934 // when this enum is changed.
9940 ConstUnknown, // Keep as last element
9943 SourceRange ExprRange = E->getSourceRange();
9945 // Only emit one error on the first const found. All other consts will emit
9946 // a note to the error.
9947 bool DiagnosticEmitted = false;
9949 // Track if the current expression is the result of a dereference, and if the
9950 // next checked expression is the result of a dereference.
9951 bool IsDereference = false;
9952 bool NextIsDereference = false;
9954 // Loop to process MemberExpr chains.
9956 IsDereference = NextIsDereference;
9958 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
9959 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9960 NextIsDereference = ME->isArrow();
9961 const ValueDecl *VD = ME->getMemberDecl();
9962 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9963 // Mutable fields can be modified even if the class is const.
9964 if (Field->isMutable()) {
9965 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9969 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9970 if (!DiagnosticEmitted) {
9971 S.Diag(Loc, diag::err_typecheck_assign_const)
9972 << ExprRange << ConstMember << false /*static*/ << Field
9973 << Field->getType();
9974 DiagnosticEmitted = true;
9976 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9977 << ConstMember << false /*static*/ << Field << Field->getType()
9978 << Field->getSourceRange();
9982 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9983 if (VDecl->getType().isConstQualified()) {
9984 if (!DiagnosticEmitted) {
9985 S.Diag(Loc, diag::err_typecheck_assign_const)
9986 << ExprRange << ConstMember << true /*static*/ << VDecl
9987 << VDecl->getType();
9988 DiagnosticEmitted = true;
9990 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9991 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9992 << VDecl->getSourceRange();
9994 // Static fields do not inherit constness from parents.
10002 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10004 const FunctionDecl *FD = CE->getDirectCallee();
10005 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10006 if (!DiagnosticEmitted) {
10007 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10008 << ConstFunction << FD;
10009 DiagnosticEmitted = true;
10011 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10012 diag::note_typecheck_assign_const)
10013 << ConstFunction << FD << FD->getReturnType()
10014 << FD->getReturnTypeSourceRange();
10016 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10017 // Point to variable declaration.
10018 if (const ValueDecl *VD = DRE->getDecl()) {
10019 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10020 if (!DiagnosticEmitted) {
10021 S.Diag(Loc, diag::err_typecheck_assign_const)
10022 << ExprRange << ConstVariable << VD << VD->getType();
10023 DiagnosticEmitted = true;
10025 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10026 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10029 } else if (isa<CXXThisExpr>(E)) {
10030 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10031 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10032 if (MD->isConst()) {
10033 if (!DiagnosticEmitted) {
10034 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10035 << ConstMethod << MD;
10036 DiagnosticEmitted = true;
10038 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10039 << ConstMethod << MD << MD->getSourceRange();
10045 if (DiagnosticEmitted)
10048 // Can't determine a more specific message, so display the generic error.
10049 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10052 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
10053 /// emit an error and return true. If so, return false.
10054 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10055 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10057 S.CheckShadowingDeclModification(E, Loc);
10059 SourceLocation OrigLoc = Loc;
10060 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10062 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10063 IsLV = Expr::MLV_InvalidMessageExpression;
10064 if (IsLV == Expr::MLV_Valid)
10067 unsigned DiagID = 0;
10068 bool NeedType = false;
10069 switch (IsLV) { // C99 6.5.16p2
10070 case Expr::MLV_ConstQualified:
10071 // Use a specialized diagnostic when we're assigning to an object
10072 // from an enclosing function or block.
10073 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10074 if (NCCK == NCCK_Block)
10075 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10077 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10081 // In ARC, use some specialized diagnostics for occasions where we
10082 // infer 'const'. These are always pseudo-strong variables.
10083 if (S.getLangOpts().ObjCAutoRefCount) {
10084 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10085 if (declRef && isa<VarDecl>(declRef->getDecl())) {
10086 VarDecl *var = cast<VarDecl>(declRef->getDecl());
10088 // Use the normal diagnostic if it's pseudo-__strong but the
10089 // user actually wrote 'const'.
10090 if (var->isARCPseudoStrong() &&
10091 (!var->getTypeSourceInfo() ||
10092 !var->getTypeSourceInfo()->getType().isConstQualified())) {
10093 // There are two pseudo-strong cases:
10095 ObjCMethodDecl *method = S.getCurMethodDecl();
10096 if (method && var == method->getSelfDecl())
10097 DiagID = method->isClassMethod()
10098 ? diag::err_typecheck_arc_assign_self_class_method
10099 : diag::err_typecheck_arc_assign_self;
10101 // - fast enumeration variables
10103 DiagID = diag::err_typecheck_arr_assign_enumeration;
10105 SourceRange Assign;
10106 if (Loc != OrigLoc)
10107 Assign = SourceRange(OrigLoc, OrigLoc);
10108 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10109 // We need to preserve the AST regardless, so migration tool
10116 // If none of the special cases above are triggered, then this is a
10117 // simple const assignment.
10119 DiagnoseConstAssignment(S, E, Loc);
10124 case Expr::MLV_ConstAddrSpace:
10125 DiagnoseConstAssignment(S, E, Loc);
10127 case Expr::MLV_ArrayType:
10128 case Expr::MLV_ArrayTemporary:
10129 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10132 case Expr::MLV_NotObjectType:
10133 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10136 case Expr::MLV_LValueCast:
10137 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10139 case Expr::MLV_Valid:
10140 llvm_unreachable("did not take early return for MLV_Valid");
10141 case Expr::MLV_InvalidExpression:
10142 case Expr::MLV_MemberFunction:
10143 case Expr::MLV_ClassTemporary:
10144 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10146 case Expr::MLV_IncompleteType:
10147 case Expr::MLV_IncompleteVoidType:
10148 return S.RequireCompleteType(Loc, E->getType(),
10149 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10150 case Expr::MLV_DuplicateVectorComponents:
10151 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10153 case Expr::MLV_NoSetterProperty:
10154 llvm_unreachable("readonly properties should be processed differently");
10155 case Expr::MLV_InvalidMessageExpression:
10156 DiagID = diag::err_readonly_message_assignment;
10158 case Expr::MLV_SubObjCPropertySetting:
10159 DiagID = diag::err_no_subobject_property_setting;
10163 SourceRange Assign;
10164 if (Loc != OrigLoc)
10165 Assign = SourceRange(OrigLoc, OrigLoc);
10167 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10169 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10173 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10174 SourceLocation Loc,
10177 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10178 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10179 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10180 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10181 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10184 // Objective-C instance variables
10185 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10186 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10187 if (OL && OR && OL->getDecl() == OR->getDecl()) {
10188 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10189 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10190 if (RL && RR && RL->getDecl() == RR->getDecl())
10191 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10196 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10197 SourceLocation Loc,
10198 QualType CompoundType) {
10199 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10201 // Verify that LHS is a modifiable lvalue, and emit error if not.
10202 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10205 QualType LHSType = LHSExpr->getType();
10206 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10208 // OpenCL v1.2 s6.1.1.1 p2:
10209 // The half data type can only be used to declare a pointer to a buffer that
10210 // contains half values
10211 if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10212 LHSType->isHalfType()) {
10213 Diag(Loc, diag::err_opencl_half_load_store) << 1
10214 << LHSType.getUnqualifiedType();
10218 AssignConvertType ConvTy;
10219 if (CompoundType.isNull()) {
10220 Expr *RHSCheck = RHS.get();
10222 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10224 QualType LHSTy(LHSType);
10225 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10226 if (RHS.isInvalid())
10228 // Special case of NSObject attributes on c-style pointer types.
10229 if (ConvTy == IncompatiblePointer &&
10230 ((Context.isObjCNSObjectType(LHSType) &&
10231 RHSType->isObjCObjectPointerType()) ||
10232 (Context.isObjCNSObjectType(RHSType) &&
10233 LHSType->isObjCObjectPointerType())))
10234 ConvTy = Compatible;
10236 if (ConvTy == Compatible &&
10237 LHSType->isObjCObjectType())
10238 Diag(Loc, diag::err_objc_object_assignment)
10241 // If the RHS is a unary plus or minus, check to see if they = and + are
10242 // right next to each other. If so, the user may have typo'd "x =+ 4"
10243 // instead of "x += 4".
10244 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10245 RHSCheck = ICE->getSubExpr();
10246 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10247 if ((UO->getOpcode() == UO_Plus ||
10248 UO->getOpcode() == UO_Minus) &&
10249 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10250 // Only if the two operators are exactly adjacent.
10251 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10252 // And there is a space or other character before the subexpr of the
10253 // unary +/-. We don't want to warn on "x=-1".
10254 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10255 UO->getSubExpr()->getLocStart().isFileID()) {
10256 Diag(Loc, diag::warn_not_compound_assign)
10257 << (UO->getOpcode() == UO_Plus ? "+" : "-")
10258 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10262 if (ConvTy == Compatible) {
10263 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10264 // Warn about retain cycles where a block captures the LHS, but
10265 // not if the LHS is a simple variable into which the block is
10266 // being stored...unless that variable can be captured by reference!
10267 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10268 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10269 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10270 checkRetainCycles(LHSExpr, RHS.get());
10272 // It is safe to assign a weak reference into a strong variable.
10273 // Although this code can still have problems:
10274 // id x = self.weakProp;
10275 // id y = self.weakProp;
10276 // we do not warn to warn spuriously when 'x' and 'y' are on separate
10277 // paths through the function. This should be revisited if
10278 // -Wrepeated-use-of-weak is made flow-sensitive.
10279 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10280 RHS.get()->getLocStart()))
10281 getCurFunction()->markSafeWeakUse(RHS.get());
10283 } else if (getLangOpts().ObjCAutoRefCount) {
10284 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10288 // Compound assignment "x += y"
10289 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10292 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10293 RHS.get(), AA_Assigning))
10296 CheckForNullPointerDereference(*this, LHSExpr);
10298 // C99 6.5.16p3: The type of an assignment expression is the type of the
10299 // left operand unless the left operand has qualified type, in which case
10300 // it is the unqualified version of the type of the left operand.
10301 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10302 // is converted to the type of the assignment expression (above).
10303 // C++ 5.17p1: the type of the assignment expression is that of its left
10305 return (getLangOpts().CPlusPlus
10306 ? LHSType : LHSType.getUnqualifiedType());
10309 // Only ignore explicit casts to void.
10310 static bool IgnoreCommaOperand(const Expr *E) {
10311 E = E->IgnoreParens();
10313 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10314 if (CE->getCastKind() == CK_ToVoid) {
10322 // Look for instances where it is likely the comma operator is confused with
10323 // another operator. There is a whitelist of acceptable expressions for the
10324 // left hand side of the comma operator, otherwise emit a warning.
10325 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10326 // No warnings in macros
10327 if (Loc.isMacroID())
10330 // Don't warn in template instantiations.
10331 if (!ActiveTemplateInstantiations.empty())
10334 // Scope isn't fine-grained enough to whitelist the specific cases, so
10335 // instead, skip more than needed, then call back into here with the
10336 // CommaVisitor in SemaStmt.cpp.
10337 // The whitelisted locations are the initialization and increment portions
10338 // of a for loop. The additional checks are on the condition of
10339 // if statements, do/while loops, and for loops.
10340 const unsigned ForIncrementFlags =
10341 Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10342 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10343 const unsigned ScopeFlags = getCurScope()->getFlags();
10344 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10345 (ScopeFlags & ForInitFlags) == ForInitFlags)
10348 // If there are multiple comma operators used together, get the RHS of the
10349 // of the comma operator as the LHS.
10350 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10351 if (BO->getOpcode() != BO_Comma)
10353 LHS = BO->getRHS();
10356 // Only allow some expressions on LHS to not warn.
10357 if (IgnoreCommaOperand(LHS))
10360 Diag(Loc, diag::warn_comma_operator);
10361 Diag(LHS->getLocStart(), diag::note_cast_to_void)
10362 << LHS->getSourceRange()
10363 << FixItHint::CreateInsertion(LHS->getLocStart(),
10364 LangOpts.CPlusPlus ? "static_cast<void>("
10366 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10371 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10372 SourceLocation Loc) {
10373 LHS = S.CheckPlaceholderExpr(LHS.get());
10374 RHS = S.CheckPlaceholderExpr(RHS.get());
10375 if (LHS.isInvalid() || RHS.isInvalid())
10378 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10379 // operands, but not unary promotions.
10380 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10382 // So we treat the LHS as a ignored value, and in C++ we allow the
10383 // containing site to determine what should be done with the RHS.
10384 LHS = S.IgnoredValueConversions(LHS.get());
10385 if (LHS.isInvalid())
10388 S.DiagnoseUnusedExprResult(LHS.get());
10390 if (!S.getLangOpts().CPlusPlus) {
10391 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10392 if (RHS.isInvalid())
10394 if (!RHS.get()->getType()->isVoidType())
10395 S.RequireCompleteType(Loc, RHS.get()->getType(),
10396 diag::err_incomplete_type);
10399 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10400 S.DiagnoseCommaOperator(LHS.get(), Loc);
10402 return RHS.get()->getType();
10405 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10406 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10407 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10409 ExprObjectKind &OK,
10410 SourceLocation OpLoc,
10411 bool IsInc, bool IsPrefix) {
10412 if (Op->isTypeDependent())
10413 return S.Context.DependentTy;
10415 QualType ResType = Op->getType();
10416 // Atomic types can be used for increment / decrement where the non-atomic
10417 // versions can, so ignore the _Atomic() specifier for the purpose of
10419 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10420 ResType = ResAtomicType->getValueType();
10422 assert(!ResType.isNull() && "no type for increment/decrement expression");
10424 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10425 // Decrement of bool is not allowed.
10427 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10430 // Increment of bool sets it to true, but is deprecated.
10431 S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10432 : diag::warn_increment_bool)
10433 << Op->getSourceRange();
10434 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10435 // Error on enum increments and decrements in C++ mode
10436 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10438 } else if (ResType->isRealType()) {
10440 } else if (ResType->isPointerType()) {
10441 // C99 6.5.2.4p2, 6.5.6p2
10442 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10444 } else if (ResType->isObjCObjectPointerType()) {
10445 // On modern runtimes, ObjC pointer arithmetic is forbidden.
10446 // Otherwise, we just need a complete type.
10447 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10448 checkArithmeticOnObjCPointer(S, OpLoc, Op))
10450 } else if (ResType->isAnyComplexType()) {
10451 // C99 does not support ++/-- on complex types, we allow as an extension.
10452 S.Diag(OpLoc, diag::ext_integer_increment_complex)
10453 << ResType << Op->getSourceRange();
10454 } else if (ResType->isPlaceholderType()) {
10455 ExprResult PR = S.CheckPlaceholderExpr(Op);
10456 if (PR.isInvalid()) return QualType();
10457 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10459 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10460 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10461 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10462 (ResType->getAs<VectorType>()->getVectorKind() !=
10463 VectorType::AltiVecBool)) {
10464 // The z vector extensions allow ++ and -- for non-bool vectors.
10465 } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10466 ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10467 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10469 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10470 << ResType << int(IsInc) << Op->getSourceRange();
10473 // At this point, we know we have a real, complex or pointer type.
10474 // Now make sure the operand is a modifiable lvalue.
10475 if (CheckForModifiableLvalue(Op, OpLoc, S))
10477 // In C++, a prefix increment is the same type as the operand. Otherwise
10478 // (in C or with postfix), the increment is the unqualified type of the
10480 if (IsPrefix && S.getLangOpts().CPlusPlus) {
10482 OK = Op->getObjectKind();
10486 return ResType.getUnqualifiedType();
10491 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10492 /// This routine allows us to typecheck complex/recursive expressions
10493 /// where the declaration is needed for type checking. We only need to
10494 /// handle cases when the expression references a function designator
10495 /// or is an lvalue. Here are some examples:
10497 /// - &*****f => f for f a function designator.
10499 /// - &s.zz[1].yy -> s, if zz is an array
10500 /// - *(x + 1) -> x, if x is an array
10501 /// - &"123"[2] -> 0
10502 /// - & __real__ x -> x
10503 static ValueDecl *getPrimaryDecl(Expr *E) {
10504 switch (E->getStmtClass()) {
10505 case Stmt::DeclRefExprClass:
10506 return cast<DeclRefExpr>(E)->getDecl();
10507 case Stmt::MemberExprClass:
10508 // If this is an arrow operator, the address is an offset from
10509 // the base's value, so the object the base refers to is
10511 if (cast<MemberExpr>(E)->isArrow())
10513 // Otherwise, the expression refers to a part of the base
10514 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10515 case Stmt::ArraySubscriptExprClass: {
10516 // FIXME: This code shouldn't be necessary! We should catch the implicit
10517 // promotion of register arrays earlier.
10518 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10519 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10520 if (ICE->getSubExpr()->getType()->isArrayType())
10521 return getPrimaryDecl(ICE->getSubExpr());
10525 case Stmt::UnaryOperatorClass: {
10526 UnaryOperator *UO = cast<UnaryOperator>(E);
10528 switch(UO->getOpcode()) {
10532 return getPrimaryDecl(UO->getSubExpr());
10537 case Stmt::ParenExprClass:
10538 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10539 case Stmt::ImplicitCastExprClass:
10540 // If the result of an implicit cast is an l-value, we care about
10541 // the sub-expression; otherwise, the result here doesn't matter.
10542 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10551 AO_Vector_Element = 1,
10552 AO_Property_Expansion = 2,
10553 AO_Register_Variable = 3,
10557 /// \brief Diagnose invalid operand for address of operations.
10559 /// \param Type The type of operand which cannot have its address taken.
10560 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10561 Expr *E, unsigned Type) {
10562 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10565 /// CheckAddressOfOperand - The operand of & must be either a function
10566 /// designator or an lvalue designating an object. If it is an lvalue, the
10567 /// object cannot be declared with storage class register or be a bit field.
10568 /// Note: The usual conversions are *not* applied to the operand of the &
10569 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10570 /// In C++, the operand might be an overloaded function name, in which case
10571 /// we allow the '&' but retain the overloaded-function type.
10572 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10573 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10574 if (PTy->getKind() == BuiltinType::Overload) {
10575 Expr *E = OrigOp.get()->IgnoreParens();
10576 if (!isa<OverloadExpr>(E)) {
10577 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10578 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10579 << OrigOp.get()->getSourceRange();
10583 OverloadExpr *Ovl = cast<OverloadExpr>(E);
10584 if (isa<UnresolvedMemberExpr>(Ovl))
10585 if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10586 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10587 << OrigOp.get()->getSourceRange();
10591 return Context.OverloadTy;
10594 if (PTy->getKind() == BuiltinType::UnknownAny)
10595 return Context.UnknownAnyTy;
10597 if (PTy->getKind() == BuiltinType::BoundMember) {
10598 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10599 << OrigOp.get()->getSourceRange();
10603 OrigOp = CheckPlaceholderExpr(OrigOp.get());
10604 if (OrigOp.isInvalid()) return QualType();
10607 if (OrigOp.get()->isTypeDependent())
10608 return Context.DependentTy;
10610 assert(!OrigOp.get()->getType()->isPlaceholderType());
10612 // Make sure to ignore parentheses in subsequent checks
10613 Expr *op = OrigOp.get()->IgnoreParens();
10615 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10616 if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10617 Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10621 if (getLangOpts().C99) {
10622 // Implement C99-only parts of addressof rules.
10623 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10624 if (uOp->getOpcode() == UO_Deref)
10625 // Per C99 6.5.3.2, the address of a deref always returns a valid result
10626 // (assuming the deref expression is valid).
10627 return uOp->getSubExpr()->getType();
10629 // Technically, there should be a check for array subscript
10630 // expressions here, but the result of one is always an lvalue anyway.
10632 ValueDecl *dcl = getPrimaryDecl(op);
10634 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10635 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10636 op->getLocStart()))
10639 Expr::LValueClassification lval = op->ClassifyLValue(Context);
10640 unsigned AddressOfError = AO_No_Error;
10642 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10643 bool sfinae = (bool)isSFINAEContext();
10644 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10645 : diag::ext_typecheck_addrof_temporary)
10646 << op->getType() << op->getSourceRange();
10649 // Materialize the temporary as an lvalue so that we can take its address.
10651 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10652 } else if (isa<ObjCSelectorExpr>(op)) {
10653 return Context.getPointerType(op->getType());
10654 } else if (lval == Expr::LV_MemberFunction) {
10655 // If it's an instance method, make a member pointer.
10656 // The expression must have exactly the form &A::foo.
10658 // If the underlying expression isn't a decl ref, give up.
10659 if (!isa<DeclRefExpr>(op)) {
10660 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10661 << OrigOp.get()->getSourceRange();
10664 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10665 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10667 // The id-expression was parenthesized.
10668 if (OrigOp.get() != DRE) {
10669 Diag(OpLoc, diag::err_parens_pointer_member_function)
10670 << OrigOp.get()->getSourceRange();
10672 // The method was named without a qualifier.
10673 } else if (!DRE->getQualifier()) {
10674 if (MD->getParent()->getName().empty())
10675 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10676 << op->getSourceRange();
10678 SmallString<32> Str;
10679 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10680 Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10681 << op->getSourceRange()
10682 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10686 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10687 if (isa<CXXDestructorDecl>(MD))
10688 Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10690 QualType MPTy = Context.getMemberPointerType(
10691 op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10692 // Under the MS ABI, lock down the inheritance model now.
10693 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10694 (void)isCompleteType(OpLoc, MPTy);
10696 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10698 // The operand must be either an l-value or a function designator
10699 if (!op->getType()->isFunctionType()) {
10700 // Use a special diagnostic for loads from property references.
10701 if (isa<PseudoObjectExpr>(op)) {
10702 AddressOfError = AO_Property_Expansion;
10704 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10705 << op->getType() << op->getSourceRange();
10709 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10710 // The operand cannot be a bit-field
10711 AddressOfError = AO_Bit_Field;
10712 } else if (op->getObjectKind() == OK_VectorComponent) {
10713 // The operand cannot be an element of a vector
10714 AddressOfError = AO_Vector_Element;
10715 } else if (dcl) { // C99 6.5.3.2p1
10716 // We have an lvalue with a decl. Make sure the decl is not declared
10717 // with the register storage-class specifier.
10718 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10719 // in C++ it is not error to take address of a register
10720 // variable (c++03 7.1.1P3)
10721 if (vd->getStorageClass() == SC_Register &&
10722 !getLangOpts().CPlusPlus) {
10723 AddressOfError = AO_Register_Variable;
10725 } else if (isa<MSPropertyDecl>(dcl)) {
10726 AddressOfError = AO_Property_Expansion;
10727 } else if (isa<FunctionTemplateDecl>(dcl)) {
10728 return Context.OverloadTy;
10729 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10730 // Okay: we can take the address of a field.
10731 // Could be a pointer to member, though, if there is an explicit
10732 // scope qualifier for the class.
10733 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10734 DeclContext *Ctx = dcl->getDeclContext();
10735 if (Ctx && Ctx->isRecord()) {
10736 if (dcl->getType()->isReferenceType()) {
10738 diag::err_cannot_form_pointer_to_member_of_reference_type)
10739 << dcl->getDeclName() << dcl->getType();
10743 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10744 Ctx = Ctx->getParent();
10746 QualType MPTy = Context.getMemberPointerType(
10748 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10749 // Under the MS ABI, lock down the inheritance model now.
10750 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10751 (void)isCompleteType(OpLoc, MPTy);
10755 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10756 !isa<BindingDecl>(dcl))
10757 llvm_unreachable("Unknown/unexpected decl type");
10760 if (AddressOfError != AO_No_Error) {
10761 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10765 if (lval == Expr::LV_IncompleteVoidType) {
10766 // Taking the address of a void variable is technically illegal, but we
10767 // allow it in cases which are otherwise valid.
10768 // Example: "extern void x; void* y = &x;".
10769 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10772 // If the operand has type "type", the result has type "pointer to type".
10773 if (op->getType()->isObjCObjectType())
10774 return Context.getObjCObjectPointerType(op->getType());
10776 CheckAddressOfPackedMember(op);
10778 return Context.getPointerType(op->getType());
10781 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10782 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10785 const Decl *D = DRE->getDecl();
10788 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10791 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10792 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10794 if (FunctionScopeInfo *FD = S.getCurFunction())
10795 if (!FD->ModifiedNonNullParams.count(Param))
10796 FD->ModifiedNonNullParams.insert(Param);
10799 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10800 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10801 SourceLocation OpLoc) {
10802 if (Op->isTypeDependent())
10803 return S.Context.DependentTy;
10805 ExprResult ConvResult = S.UsualUnaryConversions(Op);
10806 if (ConvResult.isInvalid())
10808 Op = ConvResult.get();
10809 QualType OpTy = Op->getType();
10812 if (isa<CXXReinterpretCastExpr>(Op)) {
10813 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10814 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10815 Op->getSourceRange());
10818 if (const PointerType *PT = OpTy->getAs<PointerType>())
10820 Result = PT->getPointeeType();
10822 else if (const ObjCObjectPointerType *OPT =
10823 OpTy->getAs<ObjCObjectPointerType>())
10824 Result = OPT->getPointeeType();
10826 ExprResult PR = S.CheckPlaceholderExpr(Op);
10827 if (PR.isInvalid()) return QualType();
10828 if (PR.get() != Op)
10829 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10832 if (Result.isNull()) {
10833 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10834 << OpTy << Op->getSourceRange();
10838 // Note that per both C89 and C99, indirection is always legal, even if Result
10839 // is an incomplete type or void. It would be possible to warn about
10840 // dereferencing a void pointer, but it's completely well-defined, and such a
10841 // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10842 // for pointers to 'void' but is fine for any other pointer type:
10844 // C++ [expr.unary.op]p1:
10845 // [...] the expression to which [the unary * operator] is applied shall
10846 // be a pointer to an object type, or a pointer to a function type
10847 if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10848 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10849 << OpTy << Op->getSourceRange();
10851 // Dereferences are usually l-values...
10854 // ...except that certain expressions are never l-values in C.
10855 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10861 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10862 BinaryOperatorKind Opc;
10864 default: llvm_unreachable("Unknown binop!");
10865 case tok::periodstar: Opc = BO_PtrMemD; break;
10866 case tok::arrowstar: Opc = BO_PtrMemI; break;
10867 case tok::star: Opc = BO_Mul; break;
10868 case tok::slash: Opc = BO_Div; break;
10869 case tok::percent: Opc = BO_Rem; break;
10870 case tok::plus: Opc = BO_Add; break;
10871 case tok::minus: Opc = BO_Sub; break;
10872 case tok::lessless: Opc = BO_Shl; break;
10873 case tok::greatergreater: Opc = BO_Shr; break;
10874 case tok::lessequal: Opc = BO_LE; break;
10875 case tok::less: Opc = BO_LT; break;
10876 case tok::greaterequal: Opc = BO_GE; break;
10877 case tok::greater: Opc = BO_GT; break;
10878 case tok::exclaimequal: Opc = BO_NE; break;
10879 case tok::equalequal: Opc = BO_EQ; break;
10880 case tok::amp: Opc = BO_And; break;
10881 case tok::caret: Opc = BO_Xor; break;
10882 case tok::pipe: Opc = BO_Or; break;
10883 case tok::ampamp: Opc = BO_LAnd; break;
10884 case tok::pipepipe: Opc = BO_LOr; break;
10885 case tok::equal: Opc = BO_Assign; break;
10886 case tok::starequal: Opc = BO_MulAssign; break;
10887 case tok::slashequal: Opc = BO_DivAssign; break;
10888 case tok::percentequal: Opc = BO_RemAssign; break;
10889 case tok::plusequal: Opc = BO_AddAssign; break;
10890 case tok::minusequal: Opc = BO_SubAssign; break;
10891 case tok::lesslessequal: Opc = BO_ShlAssign; break;
10892 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
10893 case tok::ampequal: Opc = BO_AndAssign; break;
10894 case tok::caretequal: Opc = BO_XorAssign; break;
10895 case tok::pipeequal: Opc = BO_OrAssign; break;
10896 case tok::comma: Opc = BO_Comma; break;
10901 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10902 tok::TokenKind Kind) {
10903 UnaryOperatorKind Opc;
10905 default: llvm_unreachable("Unknown unary op!");
10906 case tok::plusplus: Opc = UO_PreInc; break;
10907 case tok::minusminus: Opc = UO_PreDec; break;
10908 case tok::amp: Opc = UO_AddrOf; break;
10909 case tok::star: Opc = UO_Deref; break;
10910 case tok::plus: Opc = UO_Plus; break;
10911 case tok::minus: Opc = UO_Minus; break;
10912 case tok::tilde: Opc = UO_Not; break;
10913 case tok::exclaim: Opc = UO_LNot; break;
10914 case tok::kw___real: Opc = UO_Real; break;
10915 case tok::kw___imag: Opc = UO_Imag; break;
10916 case tok::kw___extension__: Opc = UO_Extension; break;
10921 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10922 /// This warning is only emitted for builtin assignment operations. It is also
10923 /// suppressed in the event of macro expansions.
10924 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10925 SourceLocation OpLoc) {
10926 if (!S.ActiveTemplateInstantiations.empty())
10928 if (OpLoc.isInvalid() || OpLoc.isMacroID())
10930 LHSExpr = LHSExpr->IgnoreParenImpCasts();
10931 RHSExpr = RHSExpr->IgnoreParenImpCasts();
10932 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10933 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10934 if (!LHSDeclRef || !RHSDeclRef ||
10935 LHSDeclRef->getLocation().isMacroID() ||
10936 RHSDeclRef->getLocation().isMacroID())
10938 const ValueDecl *LHSDecl =
10939 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10940 const ValueDecl *RHSDecl =
10941 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10942 if (LHSDecl != RHSDecl)
10944 if (LHSDecl->getType().isVolatileQualified())
10946 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10947 if (RefTy->getPointeeType().isVolatileQualified())
10950 S.Diag(OpLoc, diag::warn_self_assignment)
10951 << LHSDeclRef->getType()
10952 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10955 /// Check if a bitwise-& is performed on an Objective-C pointer. This
10956 /// is usually indicative of introspection within the Objective-C pointer.
10957 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10958 SourceLocation OpLoc) {
10959 if (!S.getLangOpts().ObjC1)
10962 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10963 const Expr *LHS = L.get();
10964 const Expr *RHS = R.get();
10966 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10967 ObjCPointerExpr = LHS;
10970 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10971 ObjCPointerExpr = RHS;
10975 // This warning is deliberately made very specific to reduce false
10976 // positives with logic that uses '&' for hashing. This logic mainly
10977 // looks for code trying to introspect into tagged pointers, which
10978 // code should generally never do.
10979 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10980 unsigned Diag = diag::warn_objc_pointer_masking;
10981 // Determine if we are introspecting the result of performSelectorXXX.
10982 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10983 // Special case messages to -performSelector and friends, which
10984 // can return non-pointer values boxed in a pointer value.
10985 // Some clients may wish to silence warnings in this subcase.
10986 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10987 Selector S = ME->getSelector();
10988 StringRef SelArg0 = S.getNameForSlot(0);
10989 if (SelArg0.startswith("performSelector"))
10990 Diag = diag::warn_objc_pointer_masking_performSelector;
10993 S.Diag(OpLoc, Diag)
10994 << ObjCPointerExpr->getSourceRange();
10998 static NamedDecl *getDeclFromExpr(Expr *E) {
11001 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11002 return DRE->getDecl();
11003 if (auto *ME = dyn_cast<MemberExpr>(E))
11004 return ME->getMemberDecl();
11005 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11006 return IRE->getDecl();
11010 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11011 /// operator @p Opc at location @c TokLoc. This routine only supports
11012 /// built-in operations; ActOnBinOp handles overloaded operators.
11013 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11014 BinaryOperatorKind Opc,
11015 Expr *LHSExpr, Expr *RHSExpr) {
11016 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11017 // The syntax only allows initializer lists on the RHS of assignment,
11018 // so we don't need to worry about accepting invalid code for
11019 // non-assignment operators.
11021 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11022 // of x = {} is x = T().
11023 InitializationKind Kind =
11024 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
11025 InitializedEntity Entity =
11026 InitializedEntity::InitializeTemporary(LHSExpr->getType());
11027 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11028 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11029 if (Init.isInvalid())
11031 RHSExpr = Init.get();
11034 ExprResult LHS = LHSExpr, RHS = RHSExpr;
11035 QualType ResultTy; // Result type of the binary operator.
11036 // The following two variables are used for compound assignment operators
11037 QualType CompLHSTy; // Type of LHS after promotions for computation
11038 QualType CompResultTy; // Type of computation result
11039 ExprValueKind VK = VK_RValue;
11040 ExprObjectKind OK = OK_Ordinary;
11042 if (!getLangOpts().CPlusPlus) {
11043 // C cannot handle TypoExpr nodes on either side of a binop because it
11044 // doesn't handle dependent types properly, so make sure any TypoExprs have
11045 // been dealt with before checking the operands.
11046 LHS = CorrectDelayedTyposInExpr(LHSExpr);
11047 RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
11048 if (Opc != BO_Assign)
11049 return ExprResult(E);
11050 // Avoid correcting the RHS to the same Expr as the LHS.
11051 Decl *D = getDeclFromExpr(E);
11052 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11054 if (!LHS.isUsable() || !RHS.isUsable())
11055 return ExprError();
11058 if (getLangOpts().OpenCL) {
11059 QualType LHSTy = LHSExpr->getType();
11060 QualType RHSTy = RHSExpr->getType();
11061 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11062 // the ATOMIC_VAR_INIT macro.
11063 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11064 SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11065 if (BO_Assign == Opc)
11066 Diag(OpLoc, diag::err_atomic_init_constant) << SR;
11068 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11069 return ExprError();
11072 // OpenCL special types - image, sampler, pipe, and blocks are to be used
11073 // only with a builtin functions and therefore should be disallowed here.
11074 if (LHSTy->isImageType() || RHSTy->isImageType() ||
11075 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11076 LHSTy->isPipeType() || RHSTy->isPipeType() ||
11077 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11078 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11079 return ExprError();
11085 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11086 if (getLangOpts().CPlusPlus &&
11087 LHS.get()->getObjectKind() != OK_ObjCProperty) {
11088 VK = LHS.get()->getValueKind();
11089 OK = LHS.get()->getObjectKind();
11091 if (!ResultTy.isNull()) {
11092 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11093 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11095 RecordModifiableNonNullParam(*this, LHS.get());
11099 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11100 Opc == BO_PtrMemI);
11104 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11108 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11111 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11114 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11118 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11124 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11128 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11131 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11134 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11138 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11142 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11143 Opc == BO_DivAssign);
11144 CompLHSTy = CompResultTy;
11145 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11146 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11149 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11150 CompLHSTy = CompResultTy;
11151 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11152 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11155 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11156 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11157 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11160 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11161 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11162 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11166 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11167 CompLHSTy = CompResultTy;
11168 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11169 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11172 case BO_OrAssign: // fallthrough
11173 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11175 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11176 CompLHSTy = CompResultTy;
11177 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11178 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11181 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11182 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11183 VK = RHS.get()->getValueKind();
11184 OK = RHS.get()->getObjectKind();
11188 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11189 return ExprError();
11191 // Check for array bounds violations for both sides of the BinaryOperator
11192 CheckArrayAccess(LHS.get());
11193 CheckArrayAccess(RHS.get());
11195 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11196 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11197 &Context.Idents.get("object_setClass"),
11198 SourceLocation(), LookupOrdinaryName);
11199 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11200 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11201 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11202 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11203 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11204 FixItHint::CreateInsertion(RHSLocEnd, ")");
11207 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11209 else if (const ObjCIvarRefExpr *OIRE =
11210 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11211 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11213 if (CompResultTy.isNull())
11214 return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11215 OK, OpLoc, FPFeatures.fp_contract);
11216 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11219 OK = LHS.get()->getObjectKind();
11221 return new (Context) CompoundAssignOperator(
11222 LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11223 OpLoc, FPFeatures.fp_contract);
11226 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11227 /// operators are mixed in a way that suggests that the programmer forgot that
11228 /// comparison operators have higher precedence. The most typical example of
11229 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11230 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11231 SourceLocation OpLoc, Expr *LHSExpr,
11233 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11234 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11236 // Check that one of the sides is a comparison operator and the other isn't.
11237 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11238 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11239 if (isLeftComp == isRightComp)
11242 // Bitwise operations are sometimes used as eager logical ops.
11243 // Don't diagnose this.
11244 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11245 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11246 if (isLeftBitwise || isRightBitwise)
11249 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11251 : SourceRange(OpLoc, RHSExpr->getLocEnd());
11252 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11253 SourceRange ParensRange = isLeftComp ?
11254 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11255 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11257 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11258 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11259 SuggestParentheses(Self, OpLoc,
11260 Self.PDiag(diag::note_precedence_silence) << OpStr,
11261 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11262 SuggestParentheses(Self, OpLoc,
11263 Self.PDiag(diag::note_precedence_bitwise_first)
11264 << BinaryOperator::getOpcodeStr(Opc),
11268 /// \brief It accepts a '&&' expr that is inside a '||' one.
11269 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11270 /// in parentheses.
11272 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11273 BinaryOperator *Bop) {
11274 assert(Bop->getOpcode() == BO_LAnd);
11275 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11276 << Bop->getSourceRange() << OpLoc;
11277 SuggestParentheses(Self, Bop->getOperatorLoc(),
11278 Self.PDiag(diag::note_precedence_silence)
11279 << Bop->getOpcodeStr(),
11280 Bop->getSourceRange());
11283 /// \brief Returns true if the given expression can be evaluated as a constant
11285 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11287 return !E->isValueDependent() &&
11288 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11291 /// \brief Returns true if the given expression can be evaluated as a constant
11293 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11295 return !E->isValueDependent() &&
11296 E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11299 /// \brief Look for '&&' in the left hand of a '||' expr.
11300 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11301 Expr *LHSExpr, Expr *RHSExpr) {
11302 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11303 if (Bop->getOpcode() == BO_LAnd) {
11304 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11305 if (EvaluatesAsFalse(S, RHSExpr))
11307 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11308 if (!EvaluatesAsTrue(S, Bop->getLHS()))
11309 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11310 } else if (Bop->getOpcode() == BO_LOr) {
11311 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11312 // If it's "a || b && 1 || c" we didn't warn earlier for
11313 // "a || b && 1", but warn now.
11314 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11315 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11321 /// \brief Look for '&&' in the right hand of a '||' expr.
11322 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11323 Expr *LHSExpr, Expr *RHSExpr) {
11324 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11325 if (Bop->getOpcode() == BO_LAnd) {
11326 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11327 if (EvaluatesAsFalse(S, LHSExpr))
11329 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11330 if (!EvaluatesAsTrue(S, Bop->getRHS()))
11331 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11336 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11337 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11338 /// the '&' expression in parentheses.
11339 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11340 SourceLocation OpLoc, Expr *SubExpr) {
11341 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11342 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11343 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11344 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11345 << Bop->getSourceRange() << OpLoc;
11346 SuggestParentheses(S, Bop->getOperatorLoc(),
11347 S.PDiag(diag::note_precedence_silence)
11348 << Bop->getOpcodeStr(),
11349 Bop->getSourceRange());
11354 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11355 Expr *SubExpr, StringRef Shift) {
11356 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11357 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11358 StringRef Op = Bop->getOpcodeStr();
11359 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11360 << Bop->getSourceRange() << OpLoc << Shift << Op;
11361 SuggestParentheses(S, Bop->getOperatorLoc(),
11362 S.PDiag(diag::note_precedence_silence) << Op,
11363 Bop->getSourceRange());
11368 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11369 Expr *LHSExpr, Expr *RHSExpr) {
11370 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11374 FunctionDecl *FD = OCE->getDirectCallee();
11375 if (!FD || !FD->isOverloadedOperator())
11378 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11379 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11382 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11383 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11384 << (Kind == OO_LessLess);
11385 SuggestParentheses(S, OCE->getOperatorLoc(),
11386 S.PDiag(diag::note_precedence_silence)
11387 << (Kind == OO_LessLess ? "<<" : ">>"),
11388 OCE->getSourceRange());
11389 SuggestParentheses(S, OpLoc,
11390 S.PDiag(diag::note_evaluate_comparison_first),
11391 SourceRange(OCE->getArg(1)->getLocStart(),
11392 RHSExpr->getLocEnd()));
11395 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11397 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11398 SourceLocation OpLoc, Expr *LHSExpr,
11400 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11401 if (BinaryOperator::isBitwiseOp(Opc))
11402 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11404 // Diagnose "arg1 & arg2 | arg3"
11405 if ((Opc == BO_Or || Opc == BO_Xor) &&
11406 !OpLoc.isMacroID()/* Don't warn in macros. */) {
11407 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11408 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11411 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11412 // We don't warn for 'assert(a || b && "bad")' since this is safe.
11413 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11414 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11415 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11418 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11419 || Opc == BO_Shr) {
11420 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11421 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11422 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11425 // Warn on overloaded shift operators and comparisons, such as:
11427 if (BinaryOperator::isComparisonOp(Opc))
11428 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11431 // Binary Operators. 'Tok' is the token for the operator.
11432 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11433 tok::TokenKind Kind,
11434 Expr *LHSExpr, Expr *RHSExpr) {
11435 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11436 assert(LHSExpr && "ActOnBinOp(): missing left expression");
11437 assert(RHSExpr && "ActOnBinOp(): missing right expression");
11439 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11440 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11442 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11445 /// Build an overloaded binary operator expression in the given scope.
11446 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11447 BinaryOperatorKind Opc,
11448 Expr *LHS, Expr *RHS) {
11449 // Find all of the overloaded operators visible from this
11450 // point. We perform both an operator-name lookup from the local
11451 // scope and an argument-dependent lookup based on the types of
11453 UnresolvedSet<16> Functions;
11454 OverloadedOperatorKind OverOp
11455 = BinaryOperator::getOverloadedOperator(Opc);
11456 if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11457 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11458 RHS->getType(), Functions);
11460 // Build the (potentially-overloaded, potentially-dependent)
11461 // binary operation.
11462 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11465 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11466 BinaryOperatorKind Opc,
11467 Expr *LHSExpr, Expr *RHSExpr) {
11468 // We want to end up calling one of checkPseudoObjectAssignment
11469 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11470 // both expressions are overloadable or either is type-dependent),
11471 // or CreateBuiltinBinOp (in any other case). We also want to get
11472 // any placeholder types out of the way.
11474 // Handle pseudo-objects in the LHS.
11475 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11476 // Assignments with a pseudo-object l-value need special analysis.
11477 if (pty->getKind() == BuiltinType::PseudoObject &&
11478 BinaryOperator::isAssignmentOp(Opc))
11479 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11481 // Don't resolve overloads if the other type is overloadable.
11482 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
11483 // We can't actually test that if we still have a placeholder,
11484 // though. Fortunately, none of the exceptions we see in that
11485 // code below are valid when the LHS is an overload set. Note
11486 // that an overload set can be dependently-typed, but it never
11487 // instantiates to having an overloadable type.
11488 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11489 if (resolvedRHS.isInvalid()) return ExprError();
11490 RHSExpr = resolvedRHS.get();
11492 if (RHSExpr->isTypeDependent() ||
11493 RHSExpr->getType()->isOverloadableType())
11494 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11497 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11498 if (LHS.isInvalid()) return ExprError();
11499 LHSExpr = LHS.get();
11502 // Handle pseudo-objects in the RHS.
11503 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11504 // An overload in the RHS can potentially be resolved by the type
11505 // being assigned to.
11506 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11507 if (getLangOpts().CPlusPlus &&
11508 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
11509 LHSExpr->getType()->isOverloadableType()))
11510 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11512 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11515 // Don't resolve overloads if the other type is overloadable.
11516 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
11517 LHSExpr->getType()->isOverloadableType())
11518 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11520 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11521 if (!resolvedRHS.isUsable()) return ExprError();
11522 RHSExpr = resolvedRHS.get();
11525 if (getLangOpts().CPlusPlus) {
11526 // If either expression is type-dependent, always build an
11528 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11529 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11531 // Otherwise, build an overloaded op if either expression has an
11532 // overloadable type.
11533 if (LHSExpr->getType()->isOverloadableType() ||
11534 RHSExpr->getType()->isOverloadableType())
11535 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11538 // Build a built-in binary operation.
11539 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11542 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11543 UnaryOperatorKind Opc,
11545 ExprResult Input = InputExpr;
11546 ExprValueKind VK = VK_RValue;
11547 ExprObjectKind OK = OK_Ordinary;
11548 QualType resultType;
11549 if (getLangOpts().OpenCL) {
11550 QualType Ty = InputExpr->getType();
11551 // The only legal unary operation for atomics is '&'.
11552 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11553 // OpenCL special types - image, sampler, pipe, and blocks are to be used
11554 // only with a builtin functions and therefore should be disallowed here.
11555 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11556 || Ty->isBlockPointerType())) {
11557 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11558 << InputExpr->getType()
11559 << Input.get()->getSourceRange());
11567 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11569 Opc == UO_PreInc ||
11571 Opc == UO_PreInc ||
11575 resultType = CheckAddressOfOperand(Input, OpLoc);
11576 RecordModifiableNonNullParam(*this, InputExpr);
11579 Input = DefaultFunctionArrayLvalueConversion(Input.get());
11580 if (Input.isInvalid()) return ExprError();
11581 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11586 Input = UsualUnaryConversions(Input.get());
11587 if (Input.isInvalid()) return ExprError();
11588 resultType = Input.get()->getType();
11589 if (resultType->isDependentType())
11591 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11593 else if (resultType->isVectorType() &&
11594 // The z vector extensions don't allow + or - with bool vectors.
11595 (!Context.getLangOpts().ZVector ||
11596 resultType->getAs<VectorType>()->getVectorKind() !=
11597 VectorType::AltiVecBool))
11599 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11601 resultType->isPointerType())
11604 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11605 << resultType << Input.get()->getSourceRange());
11607 case UO_Not: // bitwise complement
11608 Input = UsualUnaryConversions(Input.get());
11609 if (Input.isInvalid())
11610 return ExprError();
11611 resultType = Input.get()->getType();
11612 if (resultType->isDependentType())
11614 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11615 if (resultType->isComplexType() || resultType->isComplexIntegerType())
11616 // C99 does not support '~' for complex conjugation.
11617 Diag(OpLoc, diag::ext_integer_complement_complex)
11618 << resultType << Input.get()->getSourceRange();
11619 else if (resultType->hasIntegerRepresentation())
11621 else if (resultType->isExtVectorType()) {
11622 if (Context.getLangOpts().OpenCL) {
11623 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11624 // on vector float types.
11625 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11626 if (!T->isIntegerType())
11627 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11628 << resultType << Input.get()->getSourceRange());
11632 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11633 << resultType << Input.get()->getSourceRange());
11637 case UO_LNot: // logical negation
11638 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11639 Input = DefaultFunctionArrayLvalueConversion(Input.get());
11640 if (Input.isInvalid()) return ExprError();
11641 resultType = Input.get()->getType();
11643 // Though we still have to promote half FP to float...
11644 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11645 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11646 resultType = Context.FloatTy;
11649 if (resultType->isDependentType())
11651 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11652 // C99 6.5.3.3p1: ok, fallthrough;
11653 if (Context.getLangOpts().CPlusPlus) {
11654 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11655 // operand contextually converted to bool.
11656 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11657 ScalarTypeToBooleanCastKind(resultType));
11658 } else if (Context.getLangOpts().OpenCL &&
11659 Context.getLangOpts().OpenCLVersion < 120) {
11660 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11661 // operate on scalar float types.
11662 if (!resultType->isIntegerType())
11663 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11664 << resultType << Input.get()->getSourceRange());
11666 } else if (resultType->isExtVectorType()) {
11667 if (Context.getLangOpts().OpenCL &&
11668 Context.getLangOpts().OpenCLVersion < 120) {
11669 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11670 // operate on vector float types.
11671 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11672 if (!T->isIntegerType())
11673 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11674 << resultType << Input.get()->getSourceRange());
11676 // Vector logical not returns the signed variant of the operand type.
11677 resultType = GetSignedVectorType(resultType);
11680 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11681 << resultType << Input.get()->getSourceRange());
11684 // LNot always has type int. C99 6.5.3.3p5.
11685 // In C++, it's bool. C++ 5.3.1p8
11686 resultType = Context.getLogicalOperationType();
11690 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11691 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11692 // complex l-values to ordinary l-values and all other values to r-values.
11693 if (Input.isInvalid()) return ExprError();
11694 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11695 if (Input.get()->getValueKind() != VK_RValue &&
11696 Input.get()->getObjectKind() == OK_Ordinary)
11697 VK = Input.get()->getValueKind();
11698 } else if (!getLangOpts().CPlusPlus) {
11699 // In C, a volatile scalar is read by __imag. In C++, it is not.
11700 Input = DefaultLvalueConversion(Input.get());
11705 resultType = Input.get()->getType();
11706 VK = Input.get()->getValueKind();
11707 OK = Input.get()->getObjectKind();
11710 if (resultType.isNull() || Input.isInvalid())
11711 return ExprError();
11713 // Check for array bounds violations in the operand of the UnaryOperator,
11714 // except for the '*' and '&' operators that have to be handled specially
11715 // by CheckArrayAccess (as there are special cases like &array[arraysize]
11716 // that are explicitly defined as valid by the standard).
11717 if (Opc != UO_AddrOf && Opc != UO_Deref)
11718 CheckArrayAccess(Input.get());
11720 return new (Context)
11721 UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11724 /// \brief Determine whether the given expression is a qualified member
11725 /// access expression, of a form that could be turned into a pointer to member
11726 /// with the address-of operator.
11727 static bool isQualifiedMemberAccess(Expr *E) {
11728 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11729 if (!DRE->getQualifier())
11732 ValueDecl *VD = DRE->getDecl();
11733 if (!VD->isCXXClassMember())
11736 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11738 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11739 return Method->isInstance();
11744 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11745 if (!ULE->getQualifier())
11748 for (NamedDecl *D : ULE->decls()) {
11749 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11750 if (Method->isInstance())
11753 // Overload set does not contain methods.
11764 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11765 UnaryOperatorKind Opc, Expr *Input) {
11766 // First things first: handle placeholders so that the
11767 // overloaded-operator check considers the right type.
11768 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11769 // Increment and decrement of pseudo-object references.
11770 if (pty->getKind() == BuiltinType::PseudoObject &&
11771 UnaryOperator::isIncrementDecrementOp(Opc))
11772 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11774 // extension is always a builtin operator.
11775 if (Opc == UO_Extension)
11776 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11778 // & gets special logic for several kinds of placeholder.
11779 // The builtin code knows what to do.
11780 if (Opc == UO_AddrOf &&
11781 (pty->getKind() == BuiltinType::Overload ||
11782 pty->getKind() == BuiltinType::UnknownAny ||
11783 pty->getKind() == BuiltinType::BoundMember))
11784 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11786 // Anything else needs to be handled now.
11787 ExprResult Result = CheckPlaceholderExpr(Input);
11788 if (Result.isInvalid()) return ExprError();
11789 Input = Result.get();
11792 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11793 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11794 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11795 // Find all of the overloaded operators visible from this
11796 // point. We perform both an operator-name lookup from the local
11797 // scope and an argument-dependent lookup based on the types of
11799 UnresolvedSet<16> Functions;
11800 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11801 if (S && OverOp != OO_None)
11802 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11805 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11808 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11811 // Unary Operators. 'Tok' is the token for the operator.
11812 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11813 tok::TokenKind Op, Expr *Input) {
11814 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11817 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11818 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11819 LabelDecl *TheDecl) {
11820 TheDecl->markUsed(Context);
11821 // Create the AST node. The address of a label always has type 'void*'.
11822 return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11823 Context.getPointerType(Context.VoidTy));
11826 /// Given the last statement in a statement-expression, check whether
11827 /// the result is a producing expression (like a call to an
11828 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11829 /// release out of the full-expression. Otherwise, return null.
11831 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11832 // Should always be wrapped with one of these.
11833 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11834 if (!cleanups) return nullptr;
11836 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11837 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11840 // Splice out the cast. This shouldn't modify any interesting
11841 // features of the statement.
11842 Expr *producer = cast->getSubExpr();
11843 assert(producer->getType() == cast->getType());
11844 assert(producer->getValueKind() == cast->getValueKind());
11845 cleanups->setSubExpr(producer);
11849 void Sema::ActOnStartStmtExpr() {
11850 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11853 void Sema::ActOnStmtExprError() {
11854 // Note that function is also called by TreeTransform when leaving a
11855 // StmtExpr scope without rebuilding anything.
11857 DiscardCleanupsInEvaluationContext();
11858 PopExpressionEvaluationContext();
11862 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11863 SourceLocation RPLoc) { // "({..})"
11864 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11865 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11867 if (hasAnyUnrecoverableErrorsInThisFunction())
11868 DiscardCleanupsInEvaluationContext();
11869 assert(!Cleanup.exprNeedsCleanups() &&
11870 "cleanups within StmtExpr not correctly bound!");
11871 PopExpressionEvaluationContext();
11873 // FIXME: there are a variety of strange constraints to enforce here, for
11874 // example, it is not possible to goto into a stmt expression apparently.
11875 // More semantic analysis is needed.
11877 // If there are sub-stmts in the compound stmt, take the type of the last one
11878 // as the type of the stmtexpr.
11879 QualType Ty = Context.VoidTy;
11880 bool StmtExprMayBindToTemp = false;
11881 if (!Compound->body_empty()) {
11882 Stmt *LastStmt = Compound->body_back();
11883 LabelStmt *LastLabelStmt = nullptr;
11884 // If LastStmt is a label, skip down through into the body.
11885 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11886 LastLabelStmt = Label;
11887 LastStmt = Label->getSubStmt();
11890 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11891 // Do function/array conversion on the last expression, but not
11892 // lvalue-to-rvalue. However, initialize an unqualified type.
11893 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11894 if (LastExpr.isInvalid())
11895 return ExprError();
11896 Ty = LastExpr.get()->getType().getUnqualifiedType();
11898 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11899 // In ARC, if the final expression ends in a consume, splice
11900 // the consume out and bind it later. In the alternate case
11901 // (when dealing with a retainable type), the result
11902 // initialization will create a produce. In both cases the
11903 // result will be +1, and we'll need to balance that out with
11905 if (Expr *rebuiltLastStmt
11906 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11907 LastExpr = rebuiltLastStmt;
11909 LastExpr = PerformCopyInitialization(
11910 InitializedEntity::InitializeResult(LPLoc,
11917 if (LastExpr.isInvalid())
11918 return ExprError();
11919 if (LastExpr.get() != nullptr) {
11920 if (!LastLabelStmt)
11921 Compound->setLastStmt(LastExpr.get());
11923 LastLabelStmt->setSubStmt(LastExpr.get());
11924 StmtExprMayBindToTemp = true;
11930 // FIXME: Check that expression type is complete/non-abstract; statement
11931 // expressions are not lvalues.
11932 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11933 if (StmtExprMayBindToTemp)
11934 return MaybeBindToTemporary(ResStmtExpr);
11935 return ResStmtExpr;
11938 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11939 TypeSourceInfo *TInfo,
11940 ArrayRef<OffsetOfComponent> Components,
11941 SourceLocation RParenLoc) {
11942 QualType ArgTy = TInfo->getType();
11943 bool Dependent = ArgTy->isDependentType();
11944 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11946 // We must have at least one component that refers to the type, and the first
11947 // one is known to be a field designator. Verify that the ArgTy represents
11948 // a struct/union/class.
11949 if (!Dependent && !ArgTy->isRecordType())
11950 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11951 << ArgTy << TypeRange);
11953 // Type must be complete per C99 7.17p3 because a declaring a variable
11954 // with an incomplete type would be ill-formed.
11956 && RequireCompleteType(BuiltinLoc, ArgTy,
11957 diag::err_offsetof_incomplete_type, TypeRange))
11958 return ExprError();
11960 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11961 // GCC extension, diagnose them.
11962 // FIXME: This diagnostic isn't actually visible because the location is in
11963 // a system header!
11964 if (Components.size() != 1)
11965 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11966 << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11968 bool DidWarnAboutNonPOD = false;
11969 QualType CurrentType = ArgTy;
11970 SmallVector<OffsetOfNode, 4> Comps;
11971 SmallVector<Expr*, 4> Exprs;
11972 for (const OffsetOfComponent &OC : Components) {
11973 if (OC.isBrackets) {
11974 // Offset of an array sub-field. TODO: Should we allow vector elements?
11975 if (!CurrentType->isDependentType()) {
11976 const ArrayType *AT = Context.getAsArrayType(CurrentType);
11978 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11980 CurrentType = AT->getElementType();
11982 CurrentType = Context.DependentTy;
11984 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11985 if (IdxRval.isInvalid())
11986 return ExprError();
11987 Expr *Idx = IdxRval.get();
11989 // The expression must be an integral expression.
11990 // FIXME: An integral constant expression?
11991 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11992 !Idx->getType()->isIntegerType())
11993 return ExprError(Diag(Idx->getLocStart(),
11994 diag::err_typecheck_subscript_not_integer)
11995 << Idx->getSourceRange());
11997 // Record this array index.
11998 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11999 Exprs.push_back(Idx);
12003 // Offset of a field.
12004 if (CurrentType->isDependentType()) {
12005 // We have the offset of a field, but we can't look into the dependent
12006 // type. Just record the identifier of the field.
12007 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12008 CurrentType = Context.DependentTy;
12012 // We need to have a complete type to look into.
12013 if (RequireCompleteType(OC.LocStart, CurrentType,
12014 diag::err_offsetof_incomplete_type))
12015 return ExprError();
12017 // Look for the designated field.
12018 const RecordType *RC = CurrentType->getAs<RecordType>();
12020 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12022 RecordDecl *RD = RC->getDecl();
12024 // C++ [lib.support.types]p5:
12025 // The macro offsetof accepts a restricted set of type arguments in this
12026 // International Standard. type shall be a POD structure or a POD union
12028 // C++11 [support.types]p4:
12029 // If type is not a standard-layout class (Clause 9), the results are
12031 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12032 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12034 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12035 : diag::ext_offsetof_non_pod_type;
12037 if (!IsSafe && !DidWarnAboutNonPOD &&
12038 DiagRuntimeBehavior(BuiltinLoc, nullptr,
12040 << SourceRange(Components[0].LocStart, OC.LocEnd)
12042 DidWarnAboutNonPOD = true;
12045 // Look for the field.
12046 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12047 LookupQualifiedName(R, RD);
12048 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12049 IndirectFieldDecl *IndirectMemberDecl = nullptr;
12051 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12052 MemberDecl = IndirectMemberDecl->getAnonField();
12056 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12057 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12061 // (If the specified member is a bit-field, the behavior is undefined.)
12063 // We diagnose this as an error.
12064 if (MemberDecl->isBitField()) {
12065 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12066 << MemberDecl->getDeclName()
12067 << SourceRange(BuiltinLoc, RParenLoc);
12068 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12069 return ExprError();
12072 RecordDecl *Parent = MemberDecl->getParent();
12073 if (IndirectMemberDecl)
12074 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12076 // If the member was found in a base class, introduce OffsetOfNodes for
12077 // the base class indirections.
12078 CXXBasePaths Paths;
12079 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12081 if (Paths.getDetectedVirtual()) {
12082 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12083 << MemberDecl->getDeclName()
12084 << SourceRange(BuiltinLoc, RParenLoc);
12085 return ExprError();
12088 CXXBasePath &Path = Paths.front();
12089 for (const CXXBasePathElement &B : Path)
12090 Comps.push_back(OffsetOfNode(B.Base));
12093 if (IndirectMemberDecl) {
12094 for (auto *FI : IndirectMemberDecl->chain()) {
12095 assert(isa<FieldDecl>(FI));
12096 Comps.push_back(OffsetOfNode(OC.LocStart,
12097 cast<FieldDecl>(FI), OC.LocEnd));
12100 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12102 CurrentType = MemberDecl->getType().getNonReferenceType();
12105 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12106 Comps, Exprs, RParenLoc);
12109 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12110 SourceLocation BuiltinLoc,
12111 SourceLocation TypeLoc,
12112 ParsedType ParsedArgTy,
12113 ArrayRef<OffsetOfComponent> Components,
12114 SourceLocation RParenLoc) {
12116 TypeSourceInfo *ArgTInfo;
12117 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12118 if (ArgTy.isNull())
12119 return ExprError();
12122 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12124 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12128 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12130 Expr *LHSExpr, Expr *RHSExpr,
12131 SourceLocation RPLoc) {
12132 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12134 ExprValueKind VK = VK_RValue;
12135 ExprObjectKind OK = OK_Ordinary;
12137 bool ValueDependent = false;
12138 bool CondIsTrue = false;
12139 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12140 resType = Context.DependentTy;
12141 ValueDependent = true;
12143 // The conditional expression is required to be a constant expression.
12144 llvm::APSInt condEval(32);
12146 = VerifyIntegerConstantExpression(CondExpr, &condEval,
12147 diag::err_typecheck_choose_expr_requires_constant, false);
12148 if (CondICE.isInvalid())
12149 return ExprError();
12150 CondExpr = CondICE.get();
12151 CondIsTrue = condEval.getZExtValue();
12153 // If the condition is > zero, then the AST type is the same as the LSHExpr.
12154 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12156 resType = ActiveExpr->getType();
12157 ValueDependent = ActiveExpr->isValueDependent();
12158 VK = ActiveExpr->getValueKind();
12159 OK = ActiveExpr->getObjectKind();
12162 return new (Context)
12163 ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12164 CondIsTrue, resType->isDependentType(), ValueDependent);
12167 //===----------------------------------------------------------------------===//
12168 // Clang Extensions.
12169 //===----------------------------------------------------------------------===//
12171 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12172 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12173 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12175 if (LangOpts.CPlusPlus) {
12176 Decl *ManglingContextDecl;
12177 if (MangleNumberingContext *MCtx =
12178 getCurrentMangleNumberContext(Block->getDeclContext(),
12179 ManglingContextDecl)) {
12180 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12181 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12185 PushBlockScope(CurScope, Block);
12186 CurContext->addDecl(Block);
12188 PushDeclContext(CurScope, Block);
12190 CurContext = Block;
12192 getCurBlock()->HasImplicitReturnType = true;
12194 // Enter a new evaluation context to insulate the block from any
12195 // cleanups from the enclosing full-expression.
12196 PushExpressionEvaluationContext(PotentiallyEvaluated);
12199 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12201 assert(ParamInfo.getIdentifier() == nullptr &&
12202 "block-id should have no identifier!");
12203 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12204 BlockScopeInfo *CurBlock = getCurBlock();
12206 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12207 QualType T = Sig->getType();
12209 // FIXME: We should allow unexpanded parameter packs here, but that would,
12210 // in turn, make the block expression contain unexpanded parameter packs.
12211 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12212 // Drop the parameters.
12213 FunctionProtoType::ExtProtoInfo EPI;
12214 EPI.HasTrailingReturn = false;
12215 EPI.TypeQuals |= DeclSpec::TQ_const;
12216 T = Context.getFunctionType(Context.DependentTy, None, EPI);
12217 Sig = Context.getTrivialTypeSourceInfo(T);
12220 // GetTypeForDeclarator always produces a function type for a block
12221 // literal signature. Furthermore, it is always a FunctionProtoType
12222 // unless the function was written with a typedef.
12223 assert(T->isFunctionType() &&
12224 "GetTypeForDeclarator made a non-function block signature");
12226 // Look for an explicit signature in that function type.
12227 FunctionProtoTypeLoc ExplicitSignature;
12229 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12230 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12232 // Check whether that explicit signature was synthesized by
12233 // GetTypeForDeclarator. If so, don't save that as part of the
12234 // written signature.
12235 if (ExplicitSignature.getLocalRangeBegin() ==
12236 ExplicitSignature.getLocalRangeEnd()) {
12237 // This would be much cheaper if we stored TypeLocs instead of
12238 // TypeSourceInfos.
12239 TypeLoc Result = ExplicitSignature.getReturnLoc();
12240 unsigned Size = Result.getFullDataSize();
12241 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12242 Sig->getTypeLoc().initializeFullCopy(Result, Size);
12244 ExplicitSignature = FunctionProtoTypeLoc();
12248 CurBlock->TheDecl->setSignatureAsWritten(Sig);
12249 CurBlock->FunctionType = T;
12251 const FunctionType *Fn = T->getAs<FunctionType>();
12252 QualType RetTy = Fn->getReturnType();
12254 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12256 CurBlock->TheDecl->setIsVariadic(isVariadic);
12258 // Context.DependentTy is used as a placeholder for a missing block
12259 // return type. TODO: what should we do with declarators like:
12261 // If the answer is "apply template argument deduction"....
12262 if (RetTy != Context.DependentTy) {
12263 CurBlock->ReturnType = RetTy;
12264 CurBlock->TheDecl->setBlockMissingReturnType(false);
12265 CurBlock->HasImplicitReturnType = false;
12268 // Push block parameters from the declarator if we had them.
12269 SmallVector<ParmVarDecl*, 8> Params;
12270 if (ExplicitSignature) {
12271 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12272 ParmVarDecl *Param = ExplicitSignature.getParam(I);
12273 if (Param->getIdentifier() == nullptr &&
12274 !Param->isImplicit() &&
12275 !Param->isInvalidDecl() &&
12276 !getLangOpts().CPlusPlus)
12277 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12278 Params.push_back(Param);
12281 // Fake up parameter variables if we have a typedef, like
12282 // ^ fntype { ... }
12283 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12284 for (const auto &I : Fn->param_types()) {
12285 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12286 CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12287 Params.push_back(Param);
12291 // Set the parameters on the block decl.
12292 if (!Params.empty()) {
12293 CurBlock->TheDecl->setParams(Params);
12294 CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12295 /*CheckParameterNames=*/false);
12298 // Finally we can process decl attributes.
12299 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12301 // Put the parameter variables in scope.
12302 for (auto AI : CurBlock->TheDecl->parameters()) {
12303 AI->setOwningFunction(CurBlock->TheDecl);
12305 // If this has an identifier, add it to the scope stack.
12306 if (AI->getIdentifier()) {
12307 CheckShadow(CurBlock->TheScope, AI);
12309 PushOnScopeChains(AI, CurBlock->TheScope);
12314 /// ActOnBlockError - If there is an error parsing a block, this callback
12315 /// is invoked to pop the information about the block from the action impl.
12316 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12317 // Leave the expression-evaluation context.
12318 DiscardCleanupsInEvaluationContext();
12319 PopExpressionEvaluationContext();
12321 // Pop off CurBlock, handle nested blocks.
12323 PopFunctionScopeInfo();
12326 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12327 /// literal was successfully completed. ^(int x){...}
12328 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12329 Stmt *Body, Scope *CurScope) {
12330 // If blocks are disabled, emit an error.
12331 if (!LangOpts.Blocks)
12332 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12334 // Leave the expression-evaluation context.
12335 if (hasAnyUnrecoverableErrorsInThisFunction())
12336 DiscardCleanupsInEvaluationContext();
12337 assert(!Cleanup.exprNeedsCleanups() &&
12338 "cleanups within block not correctly bound!");
12339 PopExpressionEvaluationContext();
12341 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12343 if (BSI->HasImplicitReturnType)
12344 deduceClosureReturnType(*BSI);
12348 QualType RetTy = Context.VoidTy;
12349 if (!BSI->ReturnType.isNull())
12350 RetTy = BSI->ReturnType;
12352 bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12355 // Set the captured variables on the block.
12356 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12357 SmallVector<BlockDecl::Capture, 4> Captures;
12358 for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12359 if (Cap.isThisCapture())
12361 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12362 Cap.isNested(), Cap.getInitExpr());
12363 Captures.push_back(NewCap);
12365 BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12367 // If the user wrote a function type in some form, try to use that.
12368 if (!BSI->FunctionType.isNull()) {
12369 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12371 FunctionType::ExtInfo Ext = FTy->getExtInfo();
12372 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12374 // Turn protoless block types into nullary block types.
12375 if (isa<FunctionNoProtoType>(FTy)) {
12376 FunctionProtoType::ExtProtoInfo EPI;
12378 BlockTy = Context.getFunctionType(RetTy, None, EPI);
12380 // Otherwise, if we don't need to change anything about the function type,
12381 // preserve its sugar structure.
12382 } else if (FTy->getReturnType() == RetTy &&
12383 (!NoReturn || FTy->getNoReturnAttr())) {
12384 BlockTy = BSI->FunctionType;
12386 // Otherwise, make the minimal modifications to the function type.
12388 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12389 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12390 EPI.TypeQuals = 0; // FIXME: silently?
12392 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12395 // If we don't have a function type, just build one from nothing.
12397 FunctionProtoType::ExtProtoInfo EPI;
12398 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12399 BlockTy = Context.getFunctionType(RetTy, None, EPI);
12402 DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12403 BlockTy = Context.getBlockPointerType(BlockTy);
12405 // If needed, diagnose invalid gotos and switches in the block.
12406 if (getCurFunction()->NeedsScopeChecking() &&
12407 !PP.isCodeCompletionEnabled())
12408 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12410 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12412 // Try to apply the named return value optimization. We have to check again
12413 // if we can do this, though, because blocks keep return statements around
12414 // to deduce an implicit return type.
12415 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12416 !BSI->TheDecl->isDependentContext())
12417 computeNRVO(Body, BSI);
12419 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12420 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12421 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12423 // If the block isn't obviously global, i.e. it captures anything at
12424 // all, then we need to do a few things in the surrounding context:
12425 if (Result->getBlockDecl()->hasCaptures()) {
12426 // First, this expression has a new cleanup object.
12427 ExprCleanupObjects.push_back(Result->getBlockDecl());
12428 Cleanup.setExprNeedsCleanups(true);
12430 // It also gets a branch-protected scope if any of the captured
12431 // variables needs destruction.
12432 for (const auto &CI : Result->getBlockDecl()->captures()) {
12433 const VarDecl *var = CI.getVariable();
12434 if (var->getType().isDestructedType() != QualType::DK_none) {
12435 getCurFunction()->setHasBranchProtectedScope();
12444 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12445 SourceLocation RPLoc) {
12446 TypeSourceInfo *TInfo;
12447 GetTypeFromParser(Ty, &TInfo);
12448 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12451 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12452 Expr *E, TypeSourceInfo *TInfo,
12453 SourceLocation RPLoc) {
12454 Expr *OrigExpr = E;
12457 // CUDA device code does not support varargs.
12458 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12459 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12460 CUDAFunctionTarget T = IdentifyCUDATarget(F);
12461 if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12462 return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12466 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12467 // as Microsoft ABI on an actual Microsoft platform, where
12468 // __builtin_ms_va_list and __builtin_va_list are the same.)
12469 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12470 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12471 QualType MSVaListType = Context.getBuiltinMSVaListType();
12472 if (Context.hasSameType(MSVaListType, E->getType())) {
12473 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12474 return ExprError();
12479 // Get the va_list type
12480 QualType VaListType = Context.getBuiltinVaListType();
12482 if (VaListType->isArrayType()) {
12483 // Deal with implicit array decay; for example, on x86-64,
12484 // va_list is an array, but it's supposed to decay to
12485 // a pointer for va_arg.
12486 VaListType = Context.getArrayDecayedType(VaListType);
12487 // Make sure the input expression also decays appropriately.
12488 ExprResult Result = UsualUnaryConversions(E);
12489 if (Result.isInvalid())
12490 return ExprError();
12492 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12493 // If va_list is a record type and we are compiling in C++ mode,
12494 // check the argument using reference binding.
12495 InitializedEntity Entity = InitializedEntity::InitializeParameter(
12496 Context, Context.getLValueReferenceType(VaListType), false);
12497 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12498 if (Init.isInvalid())
12499 return ExprError();
12500 E = Init.getAs<Expr>();
12502 // Otherwise, the va_list argument must be an l-value because
12503 // it is modified by va_arg.
12504 if (!E->isTypeDependent() &&
12505 CheckForModifiableLvalue(E, BuiltinLoc, *this))
12506 return ExprError();
12510 if (!IsMS && !E->isTypeDependent() &&
12511 !Context.hasSameType(VaListType, E->getType()))
12512 return ExprError(Diag(E->getLocStart(),
12513 diag::err_first_argument_to_va_arg_not_of_type_va_list)
12514 << OrigExpr->getType() << E->getSourceRange());
12516 if (!TInfo->getType()->isDependentType()) {
12517 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12518 diag::err_second_parameter_to_va_arg_incomplete,
12519 TInfo->getTypeLoc()))
12520 return ExprError();
12522 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12524 diag::err_second_parameter_to_va_arg_abstract,
12525 TInfo->getTypeLoc()))
12526 return ExprError();
12528 if (!TInfo->getType().isPODType(Context)) {
12529 Diag(TInfo->getTypeLoc().getBeginLoc(),
12530 TInfo->getType()->isObjCLifetimeType()
12531 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12532 : diag::warn_second_parameter_to_va_arg_not_pod)
12533 << TInfo->getType()
12534 << TInfo->getTypeLoc().getSourceRange();
12537 // Check for va_arg where arguments of the given type will be promoted
12538 // (i.e. this va_arg is guaranteed to have undefined behavior).
12539 QualType PromoteType;
12540 if (TInfo->getType()->isPromotableIntegerType()) {
12541 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12542 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12543 PromoteType = QualType();
12545 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12546 PromoteType = Context.DoubleTy;
12547 if (!PromoteType.isNull())
12548 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12549 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12550 << TInfo->getType()
12552 << TInfo->getTypeLoc().getSourceRange());
12555 QualType T = TInfo->getType().getNonLValueExprType(Context);
12556 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12559 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12560 // The type of __null will be int or long, depending on the size of
12561 // pointers on the target.
12563 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12564 if (pw == Context.getTargetInfo().getIntWidth())
12565 Ty = Context.IntTy;
12566 else if (pw == Context.getTargetInfo().getLongWidth())
12567 Ty = Context.LongTy;
12568 else if (pw == Context.getTargetInfo().getLongLongWidth())
12569 Ty = Context.LongLongTy;
12571 llvm_unreachable("I don't know size of pointer!");
12574 return new (Context) GNUNullExpr(Ty, TokenLoc);
12577 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12579 if (!getLangOpts().ObjC1)
12582 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12586 if (!PT->isObjCIdType()) {
12587 // Check if the destination is the 'NSString' interface.
12588 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12589 if (!ID || !ID->getIdentifier()->isStr("NSString"))
12593 // Ignore any parens, implicit casts (should only be
12594 // array-to-pointer decays), and not-so-opaque values. The last is
12595 // important for making this trigger for property assignments.
12596 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12597 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12598 if (OV->getSourceExpr())
12599 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12601 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12602 if (!SL || !SL->isAscii())
12605 Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12606 << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12607 Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12612 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12613 const Expr *SrcExpr) {
12614 if (!DstType->isFunctionPointerType() ||
12615 !SrcExpr->getType()->isFunctionType())
12618 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12622 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12626 return !S.checkAddressOfFunctionIsAvailable(FD,
12628 SrcExpr->getLocStart());
12631 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12632 SourceLocation Loc,
12633 QualType DstType, QualType SrcType,
12634 Expr *SrcExpr, AssignmentAction Action,
12635 bool *Complained) {
12637 *Complained = false;
12639 // Decode the result (notice that AST's are still created for extensions).
12640 bool CheckInferredResultType = false;
12641 bool isInvalid = false;
12642 unsigned DiagKind = 0;
12644 ConversionFixItGenerator ConvHints;
12645 bool MayHaveConvFixit = false;
12646 bool MayHaveFunctionDiff = false;
12647 const ObjCInterfaceDecl *IFace = nullptr;
12648 const ObjCProtocolDecl *PDecl = nullptr;
12652 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12656 DiagKind = diag::ext_typecheck_convert_pointer_int;
12657 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12658 MayHaveConvFixit = true;
12661 DiagKind = diag::ext_typecheck_convert_int_pointer;
12662 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12663 MayHaveConvFixit = true;
12665 case IncompatiblePointer:
12666 if (Action == AA_Passing_CFAudited)
12667 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12668 else if (SrcType->isFunctionPointerType() &&
12669 DstType->isFunctionPointerType())
12670 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12672 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12674 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12675 SrcType->isObjCObjectPointerType();
12676 if (Hint.isNull() && !CheckInferredResultType) {
12677 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12679 else if (CheckInferredResultType) {
12680 SrcType = SrcType.getUnqualifiedType();
12681 DstType = DstType.getUnqualifiedType();
12683 MayHaveConvFixit = true;
12685 case IncompatiblePointerSign:
12686 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12688 case FunctionVoidPointer:
12689 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12691 case IncompatiblePointerDiscardsQualifiers: {
12692 // Perform array-to-pointer decay if necessary.
12693 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12695 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12696 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12697 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12698 DiagKind = diag::err_typecheck_incompatible_address_space;
12702 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12703 DiagKind = diag::err_typecheck_incompatible_ownership;
12707 llvm_unreachable("unknown error case for discarding qualifiers!");
12710 case CompatiblePointerDiscardsQualifiers:
12711 // If the qualifiers lost were because we were applying the
12712 // (deprecated) C++ conversion from a string literal to a char*
12713 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
12714 // Ideally, this check would be performed in
12715 // checkPointerTypesForAssignment. However, that would require a
12716 // bit of refactoring (so that the second argument is an
12717 // expression, rather than a type), which should be done as part
12718 // of a larger effort to fix checkPointerTypesForAssignment for
12720 if (getLangOpts().CPlusPlus &&
12721 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12723 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12725 case IncompatibleNestedPointerQualifiers:
12726 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12728 case IntToBlockPointer:
12729 DiagKind = diag::err_int_to_block_pointer;
12731 case IncompatibleBlockPointer:
12732 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12734 case IncompatibleObjCQualifiedId: {
12735 if (SrcType->isObjCQualifiedIdType()) {
12736 const ObjCObjectPointerType *srcOPT =
12737 SrcType->getAs<ObjCObjectPointerType>();
12738 for (auto *srcProto : srcOPT->quals()) {
12742 if (const ObjCInterfaceType *IFaceT =
12743 DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12744 IFace = IFaceT->getDecl();
12746 else if (DstType->isObjCQualifiedIdType()) {
12747 const ObjCObjectPointerType *dstOPT =
12748 DstType->getAs<ObjCObjectPointerType>();
12749 for (auto *dstProto : dstOPT->quals()) {
12753 if (const ObjCInterfaceType *IFaceT =
12754 SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12755 IFace = IFaceT->getDecl();
12757 DiagKind = diag::warn_incompatible_qualified_id;
12760 case IncompatibleVectors:
12761 DiagKind = diag::warn_incompatible_vectors;
12763 case IncompatibleObjCWeakRef:
12764 DiagKind = diag::err_arc_weak_unavailable_assign;
12767 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12769 *Complained = true;
12773 DiagKind = diag::err_typecheck_convert_incompatible;
12774 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12775 MayHaveConvFixit = true;
12777 MayHaveFunctionDiff = true;
12781 QualType FirstType, SecondType;
12784 case AA_Initializing:
12785 // The destination type comes first.
12786 FirstType = DstType;
12787 SecondType = SrcType;
12792 case AA_Passing_CFAudited:
12793 case AA_Converting:
12796 // The source type comes first.
12797 FirstType = SrcType;
12798 SecondType = DstType;
12802 PartialDiagnostic FDiag = PDiag(DiagKind);
12803 if (Action == AA_Passing_CFAudited)
12804 FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12806 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12808 // If we can fix the conversion, suggest the FixIts.
12809 assert(ConvHints.isNull() || Hint.isNull());
12810 if (!ConvHints.isNull()) {
12811 for (FixItHint &H : ConvHints.Hints)
12816 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12818 if (MayHaveFunctionDiff)
12819 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12822 if (DiagKind == diag::warn_incompatible_qualified_id &&
12823 PDecl && IFace && !IFace->hasDefinition())
12824 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
12825 << IFace->getName() << PDecl->getName();
12827 if (SecondType == Context.OverloadTy)
12828 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12829 FirstType, /*TakingAddress=*/true);
12831 if (CheckInferredResultType)
12832 EmitRelatedResultTypeNote(SrcExpr);
12834 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12835 EmitRelatedResultTypeNoteForReturn(DstType);
12838 *Complained = true;
12842 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12843 llvm::APSInt *Result) {
12844 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12846 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12847 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12851 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12854 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12855 llvm::APSInt *Result,
12858 class IDDiagnoser : public VerifyICEDiagnoser {
12862 IDDiagnoser(unsigned DiagID)
12863 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12865 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12866 S.Diag(Loc, DiagID) << SR;
12868 } Diagnoser(DiagID);
12870 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12873 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12875 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12879 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12880 VerifyICEDiagnoser &Diagnoser,
12882 SourceLocation DiagLoc = E->getLocStart();
12884 if (getLangOpts().CPlusPlus11) {
12885 // C++11 [expr.const]p5:
12886 // If an expression of literal class type is used in a context where an
12887 // integral constant expression is required, then that class type shall
12888 // have a single non-explicit conversion function to an integral or
12889 // unscoped enumeration type
12890 ExprResult Converted;
12891 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12893 CXX11ConvertDiagnoser(bool Silent)
12894 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12897 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12898 QualType T) override {
12899 return S.Diag(Loc, diag::err_ice_not_integral) << T;
12902 SemaDiagnosticBuilder diagnoseIncomplete(
12903 Sema &S, SourceLocation Loc, QualType T) override {
12904 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12907 SemaDiagnosticBuilder diagnoseExplicitConv(
12908 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12909 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12912 SemaDiagnosticBuilder noteExplicitConv(
12913 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12914 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12915 << ConvTy->isEnumeralType() << ConvTy;
12918 SemaDiagnosticBuilder diagnoseAmbiguous(
12919 Sema &S, SourceLocation Loc, QualType T) override {
12920 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12923 SemaDiagnosticBuilder noteAmbiguous(
12924 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12925 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12926 << ConvTy->isEnumeralType() << ConvTy;
12929 SemaDiagnosticBuilder diagnoseConversion(
12930 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12931 llvm_unreachable("conversion functions are permitted");
12933 } ConvertDiagnoser(Diagnoser.Suppress);
12935 Converted = PerformContextualImplicitConversion(DiagLoc, E,
12937 if (Converted.isInvalid())
12939 E = Converted.get();
12940 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12941 return ExprError();
12942 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12943 // An ICE must be of integral or unscoped enumeration type.
12944 if (!Diagnoser.Suppress)
12945 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12946 return ExprError();
12949 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12950 // in the non-ICE case.
12951 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12953 *Result = E->EvaluateKnownConstInt(Context);
12957 Expr::EvalResult EvalResult;
12958 SmallVector<PartialDiagnosticAt, 8> Notes;
12959 EvalResult.Diag = &Notes;
12961 // Try to evaluate the expression, and produce diagnostics explaining why it's
12962 // not a constant expression as a side-effect.
12963 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12964 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12966 // In C++11, we can rely on diagnostics being produced for any expression
12967 // which is not a constant expression. If no diagnostics were produced, then
12968 // this is a constant expression.
12969 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12971 *Result = EvalResult.Val.getInt();
12975 // If our only note is the usual "invalid subexpression" note, just point
12976 // the caret at its location rather than producing an essentially
12978 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12979 diag::note_invalid_subexpr_in_const_expr) {
12980 DiagLoc = Notes[0].first;
12984 if (!Folded || !AllowFold) {
12985 if (!Diagnoser.Suppress) {
12986 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12987 for (const PartialDiagnosticAt &Note : Notes)
12988 Diag(Note.first, Note.second);
12991 return ExprError();
12994 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12995 for (const PartialDiagnosticAt &Note : Notes)
12996 Diag(Note.first, Note.second);
12999 *Result = EvalResult.Val.getInt();
13004 // Handle the case where we conclude a expression which we speculatively
13005 // considered to be unevaluated is actually evaluated.
13006 class TransformToPE : public TreeTransform<TransformToPE> {
13007 typedef TreeTransform<TransformToPE> BaseTransform;
13010 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13012 // Make sure we redo semantic analysis
13013 bool AlwaysRebuild() { return true; }
13015 // Make sure we handle LabelStmts correctly.
13016 // FIXME: This does the right thing, but maybe we need a more general
13017 // fix to TreeTransform?
13018 StmtResult TransformLabelStmt(LabelStmt *S) {
13019 S->getDecl()->setStmt(nullptr);
13020 return BaseTransform::TransformLabelStmt(S);
13023 // We need to special-case DeclRefExprs referring to FieldDecls which
13024 // are not part of a member pointer formation; normal TreeTransforming
13025 // doesn't catch this case because of the way we represent them in the AST.
13026 // FIXME: This is a bit ugly; is it really the best way to handle this
13029 // Error on DeclRefExprs referring to FieldDecls.
13030 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13031 if (isa<FieldDecl>(E->getDecl()) &&
13032 !SemaRef.isUnevaluatedContext())
13033 return SemaRef.Diag(E->getLocation(),
13034 diag::err_invalid_non_static_member_use)
13035 << E->getDecl() << E->getSourceRange();
13037 return BaseTransform::TransformDeclRefExpr(E);
13040 // Exception: filter out member pointer formation
13041 ExprResult TransformUnaryOperator(UnaryOperator *E) {
13042 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13045 return BaseTransform::TransformUnaryOperator(E);
13048 ExprResult TransformLambdaExpr(LambdaExpr *E) {
13049 // Lambdas never need to be transformed.
13055 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13056 assert(isUnevaluatedContext() &&
13057 "Should only transform unevaluated expressions");
13058 ExprEvalContexts.back().Context =
13059 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13060 if (isUnevaluatedContext())
13062 return TransformToPE(*this).TransformExpr(E);
13066 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13067 Decl *LambdaContextDecl,
13069 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13070 LambdaContextDecl, IsDecltype);
13072 if (!MaybeODRUseExprs.empty())
13073 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13077 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13078 ReuseLambdaContextDecl_t,
13080 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13081 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13084 void Sema::PopExpressionEvaluationContext() {
13085 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13086 unsigned NumTypos = Rec.NumTypos;
13088 if (!Rec.Lambdas.empty()) {
13089 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13091 if (Rec.isUnevaluated()) {
13092 // C++11 [expr.prim.lambda]p2:
13093 // A lambda-expression shall not appear in an unevaluated operand
13095 D = diag::err_lambda_unevaluated_operand;
13097 // C++1y [expr.const]p2:
13098 // A conditional-expression e is a core constant expression unless the
13099 // evaluation of e, following the rules of the abstract machine, would
13100 // evaluate [...] a lambda-expression.
13101 D = diag::err_lambda_in_constant_expression;
13104 // C++1z allows lambda expressions as core constant expressions.
13105 // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13106 // 1607) from appearing within template-arguments and array-bounds that
13107 // are part of function-signatures. Be mindful that P0315 (Lambdas in
13108 // unevaluated contexts) might lift some of these restrictions in a
13110 if (Rec.Context != ConstantEvaluated || !getLangOpts().CPlusPlus1z)
13111 for (const auto *L : Rec.Lambdas)
13112 Diag(L->getLocStart(), D);
13114 // Mark the capture expressions odr-used. This was deferred
13115 // during lambda expression creation.
13116 for (auto *Lambda : Rec.Lambdas) {
13117 for (auto *C : Lambda->capture_inits())
13118 MarkDeclarationsReferencedInExpr(C);
13123 // When are coming out of an unevaluated context, clear out any
13124 // temporaries that we may have created as part of the evaluation of
13125 // the expression in that context: they aren't relevant because they
13126 // will never be constructed.
13127 if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
13128 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13129 ExprCleanupObjects.end());
13130 Cleanup = Rec.ParentCleanup;
13131 CleanupVarDeclMarking();
13132 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13133 // Otherwise, merge the contexts together.
13135 Cleanup.mergeFrom(Rec.ParentCleanup);
13136 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13137 Rec.SavedMaybeODRUseExprs.end());
13140 // Pop the current expression evaluation context off the stack.
13141 ExprEvalContexts.pop_back();
13143 if (!ExprEvalContexts.empty())
13144 ExprEvalContexts.back().NumTypos += NumTypos;
13146 assert(NumTypos == 0 && "There are outstanding typos after popping the "
13147 "last ExpressionEvaluationContextRecord");
13150 void Sema::DiscardCleanupsInEvaluationContext() {
13151 ExprCleanupObjects.erase(
13152 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13153 ExprCleanupObjects.end());
13155 MaybeODRUseExprs.clear();
13158 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13159 if (!E->getType()->isVariablyModifiedType())
13161 return TransformToPotentiallyEvaluated(E);
13164 /// Are we within a context in which some evaluation could be performed (be it
13165 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13166 /// captured by C++'s idea of an "unevaluated context".
13167 static bool isEvaluatableContext(Sema &SemaRef) {
13168 switch (SemaRef.ExprEvalContexts.back().Context) {
13169 case Sema::Unevaluated:
13170 case Sema::UnevaluatedAbstract:
13171 case Sema::DiscardedStatement:
13172 // Expressions in this context are never evaluated.
13175 case Sema::UnevaluatedList:
13176 case Sema::ConstantEvaluated:
13177 case Sema::PotentiallyEvaluated:
13178 // Expressions in this context could be evaluated.
13181 case Sema::PotentiallyEvaluatedIfUsed:
13182 // Referenced declarations will only be used if the construct in the
13183 // containing expression is used, at which point we'll be given another
13184 // turn to mark them.
13187 llvm_unreachable("Invalid context");
13190 /// Are we within a context in which references to resolved functions or to
13191 /// variables result in odr-use?
13192 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13193 // An expression in a template is not really an expression until it's been
13194 // instantiated, so it doesn't trigger odr-use.
13195 if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13198 switch (SemaRef.ExprEvalContexts.back().Context) {
13199 case Sema::Unevaluated:
13200 case Sema::UnevaluatedList:
13201 case Sema::UnevaluatedAbstract:
13202 case Sema::DiscardedStatement:
13205 case Sema::ConstantEvaluated:
13206 case Sema::PotentiallyEvaluated:
13209 case Sema::PotentiallyEvaluatedIfUsed:
13212 llvm_unreachable("Invalid context");
13215 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13216 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13217 return Func->isConstexpr() &&
13218 (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13221 /// \brief Mark a function referenced, and check whether it is odr-used
13222 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13223 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13224 bool MightBeOdrUse) {
13225 assert(Func && "No function?");
13227 Func->setReferenced();
13229 // C++11 [basic.def.odr]p3:
13230 // A function whose name appears as a potentially-evaluated expression is
13231 // odr-used if it is the unique lookup result or the selected member of a
13232 // set of overloaded functions [...].
13234 // We (incorrectly) mark overload resolution as an unevaluated context, so we
13235 // can just check that here.
13236 bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13238 // Determine whether we require a function definition to exist, per
13239 // C++11 [temp.inst]p3:
13240 // Unless a function template specialization has been explicitly
13241 // instantiated or explicitly specialized, the function template
13242 // specialization is implicitly instantiated when the specialization is
13243 // referenced in a context that requires a function definition to exist.
13245 // That is either when this is an odr-use, or when a usage of a constexpr
13246 // function occurs within an evaluatable context.
13247 bool NeedDefinition =
13248 OdrUse || (isEvaluatableContext(*this) &&
13249 isImplicitlyDefinableConstexprFunction(Func));
13251 // C++14 [temp.expl.spec]p6:
13252 // If a template [...] is explicitly specialized then that specialization
13253 // shall be declared before the first use of that specialization that would
13254 // cause an implicit instantiation to take place, in every translation unit
13255 // in which such a use occurs
13256 if (NeedDefinition &&
13257 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13258 Func->getMemberSpecializationInfo()))
13259 checkSpecializationVisibility(Loc, Func);
13261 // C++14 [except.spec]p17:
13262 // An exception-specification is considered to be needed when:
13263 // - the function is odr-used or, if it appears in an unevaluated operand,
13264 // would be odr-used if the expression were potentially-evaluated;
13266 // Note, we do this even if MightBeOdrUse is false. That indicates that the
13267 // function is a pure virtual function we're calling, and in that case the
13268 // function was selected by overload resolution and we need to resolve its
13269 // exception specification for a different reason.
13270 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13271 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13272 ResolveExceptionSpec(Loc, FPT);
13274 // If we don't need to mark the function as used, and we don't need to
13275 // try to provide a definition, there's nothing more to do.
13276 if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13277 (!NeedDefinition || Func->getBody()))
13280 // Note that this declaration has been used.
13281 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13282 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13283 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13284 if (Constructor->isDefaultConstructor()) {
13285 if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13287 DefineImplicitDefaultConstructor(Loc, Constructor);
13288 } else if (Constructor->isCopyConstructor()) {
13289 DefineImplicitCopyConstructor(Loc, Constructor);
13290 } else if (Constructor->isMoveConstructor()) {
13291 DefineImplicitMoveConstructor(Loc, Constructor);
13293 } else if (Constructor->getInheritedConstructor()) {
13294 DefineInheritingConstructor(Loc, Constructor);
13296 } else if (CXXDestructorDecl *Destructor =
13297 dyn_cast<CXXDestructorDecl>(Func)) {
13298 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13299 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13300 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13302 DefineImplicitDestructor(Loc, Destructor);
13304 if (Destructor->isVirtual() && getLangOpts().AppleKext)
13305 MarkVTableUsed(Loc, Destructor->getParent());
13306 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13307 if (MethodDecl->isOverloadedOperator() &&
13308 MethodDecl->getOverloadedOperator() == OO_Equal) {
13309 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13310 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13311 if (MethodDecl->isCopyAssignmentOperator())
13312 DefineImplicitCopyAssignment(Loc, MethodDecl);
13313 else if (MethodDecl->isMoveAssignmentOperator())
13314 DefineImplicitMoveAssignment(Loc, MethodDecl);
13316 } else if (isa<CXXConversionDecl>(MethodDecl) &&
13317 MethodDecl->getParent()->isLambda()) {
13318 CXXConversionDecl *Conversion =
13319 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13320 if (Conversion->isLambdaToBlockPointerConversion())
13321 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13323 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13324 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13325 MarkVTableUsed(Loc, MethodDecl->getParent());
13328 // Recursive functions should be marked when used from another function.
13329 // FIXME: Is this really right?
13330 if (CurContext == Func) return;
13332 // Implicit instantiation of function templates and member functions of
13333 // class templates.
13334 if (Func->isImplicitlyInstantiable()) {
13335 bool AlreadyInstantiated = false;
13336 SourceLocation PointOfInstantiation = Loc;
13337 if (FunctionTemplateSpecializationInfo *SpecInfo
13338 = Func->getTemplateSpecializationInfo()) {
13339 if (SpecInfo->getPointOfInstantiation().isInvalid())
13340 SpecInfo->setPointOfInstantiation(Loc);
13341 else if (SpecInfo->getTemplateSpecializationKind()
13342 == TSK_ImplicitInstantiation) {
13343 AlreadyInstantiated = true;
13344 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13346 } else if (MemberSpecializationInfo *MSInfo
13347 = Func->getMemberSpecializationInfo()) {
13348 if (MSInfo->getPointOfInstantiation().isInvalid())
13349 MSInfo->setPointOfInstantiation(Loc);
13350 else if (MSInfo->getTemplateSpecializationKind()
13351 == TSK_ImplicitInstantiation) {
13352 AlreadyInstantiated = true;
13353 PointOfInstantiation = MSInfo->getPointOfInstantiation();
13357 if (!AlreadyInstantiated || Func->isConstexpr()) {
13358 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13359 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13360 ActiveTemplateInstantiations.size())
13361 PendingLocalImplicitInstantiations.push_back(
13362 std::make_pair(Func, PointOfInstantiation));
13363 else if (Func->isConstexpr())
13364 // Do not defer instantiations of constexpr functions, to avoid the
13365 // expression evaluator needing to call back into Sema if it sees a
13366 // call to such a function.
13367 InstantiateFunctionDefinition(PointOfInstantiation, Func);
13369 PendingInstantiations.push_back(std::make_pair(Func,
13370 PointOfInstantiation));
13371 // Notify the consumer that a function was implicitly instantiated.
13372 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13376 // Walk redefinitions, as some of them may be instantiable.
13377 for (auto i : Func->redecls()) {
13378 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13379 MarkFunctionReferenced(Loc, i, OdrUse);
13383 if (!OdrUse) return;
13385 // Keep track of used but undefined functions.
13386 if (!Func->isDefined()) {
13387 if (mightHaveNonExternalLinkage(Func))
13388 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13389 else if (Func->getMostRecentDecl()->isInlined() &&
13390 !LangOpts.GNUInline &&
13391 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13392 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13395 Func->markUsed(Context);
13399 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13400 ValueDecl *var, DeclContext *DC) {
13401 DeclContext *VarDC = var->getDeclContext();
13403 // If the parameter still belongs to the translation unit, then
13404 // we're actually just using one parameter in the declaration of
13406 if (isa<ParmVarDecl>(var) &&
13407 isa<TranslationUnitDecl>(VarDC))
13410 // For C code, don't diagnose about capture if we're not actually in code
13411 // right now; it's impossible to write a non-constant expression outside of
13412 // function context, so we'll get other (more useful) diagnostics later.
13414 // For C++, things get a bit more nasty... it would be nice to suppress this
13415 // diagnostic for certain cases like using a local variable in an array bound
13416 // for a member of a local class, but the correct predicate is not obvious.
13417 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13420 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13421 unsigned ContextKind = 3; // unknown
13422 if (isa<CXXMethodDecl>(VarDC) &&
13423 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13425 } else if (isa<FunctionDecl>(VarDC)) {
13427 } else if (isa<BlockDecl>(VarDC)) {
13431 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13432 << var << ValueKind << ContextKind << VarDC;
13433 S.Diag(var->getLocation(), diag::note_entity_declared_at)
13436 // FIXME: Add additional diagnostic info about class etc. which prevents
13441 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13442 bool &SubCapturesAreNested,
13443 QualType &CaptureType,
13444 QualType &DeclRefType) {
13445 // Check whether we've already captured it.
13446 if (CSI->CaptureMap.count(Var)) {
13447 // If we found a capture, any subcaptures are nested.
13448 SubCapturesAreNested = true;
13450 // Retrieve the capture type for this variable.
13451 CaptureType = CSI->getCapture(Var).getCaptureType();
13453 // Compute the type of an expression that refers to this variable.
13454 DeclRefType = CaptureType.getNonReferenceType();
13456 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13457 // are mutable in the sense that user can change their value - they are
13458 // private instances of the captured declarations.
13459 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13460 if (Cap.isCopyCapture() &&
13461 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13462 !(isa<CapturedRegionScopeInfo>(CSI) &&
13463 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13464 DeclRefType.addConst();
13470 // Only block literals, captured statements, and lambda expressions can
13471 // capture; other scopes don't work.
13472 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13473 SourceLocation Loc,
13474 const bool Diagnose, Sema &S) {
13475 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13476 return getLambdaAwareParentOfDeclContext(DC);
13477 else if (Var->hasLocalStorage()) {
13479 diagnoseUncapturableValueReference(S, Loc, Var, DC);
13484 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13485 // certain types of variables (unnamed, variably modified types etc.)
13486 // so check for eligibility.
13487 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13488 SourceLocation Loc,
13489 const bool Diagnose, Sema &S) {
13491 bool IsBlock = isa<BlockScopeInfo>(CSI);
13492 bool IsLambda = isa<LambdaScopeInfo>(CSI);
13494 // Lambdas are not allowed to capture unnamed variables
13495 // (e.g. anonymous unions).
13496 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13497 // assuming that's the intent.
13498 if (IsLambda && !Var->getDeclName()) {
13500 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13501 S.Diag(Var->getLocation(), diag::note_declared_at);
13506 // Prohibit variably-modified types in blocks; they're difficult to deal with.
13507 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13509 S.Diag(Loc, diag::err_ref_vm_type);
13510 S.Diag(Var->getLocation(), diag::note_previous_decl)
13511 << Var->getDeclName();
13515 // Prohibit structs with flexible array members too.
13516 // We cannot capture what is in the tail end of the struct.
13517 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13518 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13521 S.Diag(Loc, diag::err_ref_flexarray_type);
13523 S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13524 << Var->getDeclName();
13525 S.Diag(Var->getLocation(), diag::note_previous_decl)
13526 << Var->getDeclName();
13531 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13532 // Lambdas and captured statements are not allowed to capture __block
13533 // variables; they don't support the expected semantics.
13534 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13536 S.Diag(Loc, diag::err_capture_block_variable)
13537 << Var->getDeclName() << !IsLambda;
13538 S.Diag(Var->getLocation(), diag::note_previous_decl)
13539 << Var->getDeclName();
13547 // Returns true if the capture by block was successful.
13548 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13549 SourceLocation Loc,
13550 const bool BuildAndDiagnose,
13551 QualType &CaptureType,
13552 QualType &DeclRefType,
13555 Expr *CopyExpr = nullptr;
13556 bool ByRef = false;
13558 // Blocks are not allowed to capture arrays.
13559 if (CaptureType->isArrayType()) {
13560 if (BuildAndDiagnose) {
13561 S.Diag(Loc, diag::err_ref_array_type);
13562 S.Diag(Var->getLocation(), diag::note_previous_decl)
13563 << Var->getDeclName();
13568 // Forbid the block-capture of autoreleasing variables.
13569 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13570 if (BuildAndDiagnose) {
13571 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13573 S.Diag(Var->getLocation(), diag::note_previous_decl)
13574 << Var->getDeclName();
13579 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
13580 if (auto *PT = dyn_cast<PointerType>(CaptureType)) {
13581 QualType PointeeTy = PT->getPointeeType();
13582 if (isa<ObjCObjectPointerType>(PointeeTy.getCanonicalType()) &&
13583 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
13584 !isa<AttributedType>(PointeeTy)) {
13585 if (BuildAndDiagnose) {
13586 SourceLocation VarLoc = Var->getLocation();
13587 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
13588 S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing) <<
13589 FixItHint::CreateInsertion(VarLoc, "__autoreleasing");
13590 S.Diag(VarLoc, diag::note_declare_parameter_strong);
13595 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13596 if (HasBlocksAttr || CaptureType->isReferenceType() ||
13597 (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13598 // Block capture by reference does not change the capture or
13599 // declaration reference types.
13602 // Block capture by copy introduces 'const'.
13603 CaptureType = CaptureType.getNonReferenceType().withConst();
13604 DeclRefType = CaptureType;
13606 if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13607 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13608 // The capture logic needs the destructor, so make sure we mark it.
13609 // Usually this is unnecessary because most local variables have
13610 // their destructors marked at declaration time, but parameters are
13611 // an exception because it's technically only the call site that
13612 // actually requires the destructor.
13613 if (isa<ParmVarDecl>(Var))
13614 S.FinalizeVarWithDestructor(Var, Record);
13616 // Enter a new evaluation context to insulate the copy
13617 // full-expression.
13618 EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13620 // According to the blocks spec, the capture of a variable from
13621 // the stack requires a const copy constructor. This is not true
13622 // of the copy/move done to move a __block variable to the heap.
13623 Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13624 DeclRefType.withConst(),
13628 = S.PerformCopyInitialization(
13629 InitializedEntity::InitializeBlock(Var->getLocation(),
13630 CaptureType, false),
13633 // Build a full-expression copy expression if initialization
13634 // succeeded and used a non-trivial constructor. Recover from
13635 // errors by pretending that the copy isn't necessary.
13636 if (!Result.isInvalid() &&
13637 !cast<CXXConstructExpr>(Result.get())->getConstructor()
13639 Result = S.MaybeCreateExprWithCleanups(Result);
13640 CopyExpr = Result.get();
13646 // Actually capture the variable.
13647 if (BuildAndDiagnose)
13648 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13649 SourceLocation(), CaptureType, CopyExpr);
13656 /// \brief Capture the given variable in the captured region.
13657 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13659 SourceLocation Loc,
13660 const bool BuildAndDiagnose,
13661 QualType &CaptureType,
13662 QualType &DeclRefType,
13663 const bool RefersToCapturedVariable,
13665 // By default, capture variables by reference.
13667 // Using an LValue reference type is consistent with Lambdas (see below).
13668 if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13669 if (S.IsOpenMPCapturedDecl(Var))
13670 DeclRefType = DeclRefType.getUnqualifiedType();
13671 ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13675 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13677 CaptureType = DeclRefType;
13679 Expr *CopyExpr = nullptr;
13680 if (BuildAndDiagnose) {
13681 // The current implementation assumes that all variables are captured
13682 // by references. Since there is no capture by copy, no expression
13683 // evaluation will be needed.
13684 RecordDecl *RD = RSI->TheRecordDecl;
13687 = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13688 S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13689 nullptr, false, ICIS_NoInit);
13690 Field->setImplicit(true);
13691 Field->setAccess(AS_private);
13692 RD->addDecl(Field);
13694 CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13695 DeclRefType, VK_LValue, Loc);
13696 Var->setReferenced(true);
13697 Var->markUsed(S.Context);
13700 // Actually capture the variable.
13701 if (BuildAndDiagnose)
13702 RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13703 SourceLocation(), CaptureType, CopyExpr);
13709 /// \brief Create a field within the lambda class for the variable
13710 /// being captured.
13711 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13712 QualType FieldType, QualType DeclRefType,
13713 SourceLocation Loc,
13714 bool RefersToCapturedVariable) {
13715 CXXRecordDecl *Lambda = LSI->Lambda;
13717 // Build the non-static data member.
13719 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13720 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13721 nullptr, false, ICIS_NoInit);
13722 Field->setImplicit(true);
13723 Field->setAccess(AS_private);
13724 Lambda->addDecl(Field);
13727 /// \brief Capture the given variable in the lambda.
13728 static bool captureInLambda(LambdaScopeInfo *LSI,
13730 SourceLocation Loc,
13731 const bool BuildAndDiagnose,
13732 QualType &CaptureType,
13733 QualType &DeclRefType,
13734 const bool RefersToCapturedVariable,
13735 const Sema::TryCaptureKind Kind,
13736 SourceLocation EllipsisLoc,
13737 const bool IsTopScope,
13740 // Determine whether we are capturing by reference or by value.
13741 bool ByRef = false;
13742 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13743 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13745 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13748 // Compute the type of the field that will capture this variable.
13750 // C++11 [expr.prim.lambda]p15:
13751 // An entity is captured by reference if it is implicitly or
13752 // explicitly captured but not captured by copy. It is
13753 // unspecified whether additional unnamed non-static data
13754 // members are declared in the closure type for entities
13755 // captured by reference.
13757 // FIXME: It is not clear whether we want to build an lvalue reference
13758 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13759 // to do the former, while EDG does the latter. Core issue 1249 will
13760 // clarify, but for now we follow GCC because it's a more permissive and
13761 // easily defensible position.
13762 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13764 // C++11 [expr.prim.lambda]p14:
13765 // For each entity captured by copy, an unnamed non-static
13766 // data member is declared in the closure type. The
13767 // declaration order of these members is unspecified. The type
13768 // of such a data member is the type of the corresponding
13769 // captured entity if the entity is not a reference to an
13770 // object, or the referenced type otherwise. [Note: If the
13771 // captured entity is a reference to a function, the
13772 // corresponding data member is also a reference to a
13773 // function. - end note ]
13774 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13775 if (!RefType->getPointeeType()->isFunctionType())
13776 CaptureType = RefType->getPointeeType();
13779 // Forbid the lambda copy-capture of autoreleasing variables.
13780 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13781 if (BuildAndDiagnose) {
13782 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13783 S.Diag(Var->getLocation(), diag::note_previous_decl)
13784 << Var->getDeclName();
13789 // Make sure that by-copy captures are of a complete and non-abstract type.
13790 if (BuildAndDiagnose) {
13791 if (!CaptureType->isDependentType() &&
13792 S.RequireCompleteType(Loc, CaptureType,
13793 diag::err_capture_of_incomplete_type,
13794 Var->getDeclName()))
13797 if (S.RequireNonAbstractType(Loc, CaptureType,
13798 diag::err_capture_of_abstract_type))
13803 // Capture this variable in the lambda.
13804 if (BuildAndDiagnose)
13805 addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13806 RefersToCapturedVariable);
13808 // Compute the type of a reference to this captured variable.
13810 DeclRefType = CaptureType.getNonReferenceType();
13812 // C++ [expr.prim.lambda]p5:
13813 // The closure type for a lambda-expression has a public inline
13814 // function call operator [...]. This function call operator is
13815 // declared const (9.3.1) if and only if the lambda-expression's
13816 // parameter-declaration-clause is not followed by mutable.
13817 DeclRefType = CaptureType.getNonReferenceType();
13818 if (!LSI->Mutable && !CaptureType->isReferenceType())
13819 DeclRefType.addConst();
13822 // Add the capture.
13823 if (BuildAndDiagnose)
13824 LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13825 Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13830 bool Sema::tryCaptureVariable(
13831 VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13832 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13833 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13834 // An init-capture is notionally from the context surrounding its
13835 // declaration, but its parent DC is the lambda class.
13836 DeclContext *VarDC = Var->getDeclContext();
13837 if (Var->isInitCapture())
13838 VarDC = VarDC->getParent();
13840 DeclContext *DC = CurContext;
13841 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13842 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13843 // We need to sync up the Declaration Context with the
13844 // FunctionScopeIndexToStopAt
13845 if (FunctionScopeIndexToStopAt) {
13846 unsigned FSIndex = FunctionScopes.size() - 1;
13847 while (FSIndex != MaxFunctionScopesIndex) {
13848 DC = getLambdaAwareParentOfDeclContext(DC);
13854 // If the variable is declared in the current context, there is no need to
13856 if (VarDC == DC) return true;
13858 // Capture global variables if it is required to use private copy of this
13860 bool IsGlobal = !Var->hasLocalStorage();
13861 if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13864 // Walk up the stack to determine whether we can capture the variable,
13865 // performing the "simple" checks that don't depend on type. We stop when
13866 // we've either hit the declared scope of the variable or find an existing
13867 // capture of that variable. We start from the innermost capturing-entity
13868 // (the DC) and ensure that all intervening capturing-entities
13869 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13870 // declcontext can either capture the variable or have already captured
13872 CaptureType = Var->getType();
13873 DeclRefType = CaptureType.getNonReferenceType();
13874 bool Nested = false;
13875 bool Explicit = (Kind != TryCapture_Implicit);
13876 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13878 // Only block literals, captured statements, and lambda expressions can
13879 // capture; other scopes don't work.
13880 DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13884 // We need to check for the parent *first* because, if we *have*
13885 // private-captured a global variable, we need to recursively capture it in
13886 // intermediate blocks, lambdas, etc.
13889 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13895 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
13896 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13899 // Check whether we've already captured it.
13900 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13903 // If we are instantiating a generic lambda call operator body,
13904 // we do not want to capture new variables. What was captured
13905 // during either a lambdas transformation or initial parsing
13907 if (isGenericLambdaCallOperatorSpecialization(DC)) {
13908 if (BuildAndDiagnose) {
13909 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13910 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13911 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13912 Diag(Var->getLocation(), diag::note_previous_decl)
13913 << Var->getDeclName();
13914 Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13916 diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13920 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13921 // certain types of variables (unnamed, variably modified types etc.)
13922 // so check for eligibility.
13923 if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13926 // Try to capture variable-length arrays types.
13927 if (Var->getType()->isVariablyModifiedType()) {
13928 // We're going to walk down into the type and look for VLA
13930 QualType QTy = Var->getType();
13931 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13932 QTy = PVD->getOriginalType();
13933 captureVariablyModifiedType(Context, QTy, CSI);
13936 if (getLangOpts().OpenMP) {
13937 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13938 // OpenMP private variables should not be captured in outer scope, so
13939 // just break here. Similarly, global variables that are captured in a
13940 // target region should not be captured outside the scope of the region.
13941 if (RSI->CapRegionKind == CR_OpenMP) {
13942 auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
13943 // When we detect target captures we are looking from inside the
13944 // target region, therefore we need to propagate the capture from the
13945 // enclosing region. Therefore, the capture is not initially nested.
13947 FunctionScopesIndex--;
13949 if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13950 Nested = !IsTargetCap;
13951 DeclRefType = DeclRefType.getUnqualifiedType();
13952 CaptureType = Context.getLValueReferenceType(DeclRefType);
13958 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13959 // No capture-default, and this is not an explicit capture
13960 // so cannot capture this variable.
13961 if (BuildAndDiagnose) {
13962 Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13963 Diag(Var->getLocation(), diag::note_previous_decl)
13964 << Var->getDeclName();
13965 if (cast<LambdaScopeInfo>(CSI)->Lambda)
13966 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13967 diag::note_lambda_decl);
13968 // FIXME: If we error out because an outer lambda can not implicitly
13969 // capture a variable that an inner lambda explicitly captures, we
13970 // should have the inner lambda do the explicit capture - because
13971 // it makes for cleaner diagnostics later. This would purely be done
13972 // so that the diagnostic does not misleadingly claim that a variable
13973 // can not be captured by a lambda implicitly even though it is captured
13974 // explicitly. Suggestion:
13975 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13976 // at the function head
13977 // - cache the StartingDeclContext - this must be a lambda
13978 // - captureInLambda in the innermost lambda the variable.
13983 FunctionScopesIndex--;
13986 } while (!VarDC->Equals(DC));
13988 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13989 // computing the type of the capture at each step, checking type-specific
13990 // requirements, and adding captures if requested.
13991 // If the variable had already been captured previously, we start capturing
13992 // at the lambda nested within that one.
13993 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13995 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13997 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13998 if (!captureInBlock(BSI, Var, ExprLoc,
13999 BuildAndDiagnose, CaptureType,
14000 DeclRefType, Nested, *this))
14003 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14004 if (!captureInCapturedRegion(RSI, Var, ExprLoc,
14005 BuildAndDiagnose, CaptureType,
14006 DeclRefType, Nested, *this))
14010 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14011 if (!captureInLambda(LSI, Var, ExprLoc,
14012 BuildAndDiagnose, CaptureType,
14013 DeclRefType, Nested, Kind, EllipsisLoc,
14014 /*IsTopScope*/I == N - 1, *this))
14022 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14023 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14024 QualType CaptureType;
14025 QualType DeclRefType;
14026 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14027 /*BuildAndDiagnose=*/true, CaptureType,
14028 DeclRefType, nullptr);
14031 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14032 QualType CaptureType;
14033 QualType DeclRefType;
14034 return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14035 /*BuildAndDiagnose=*/false, CaptureType,
14036 DeclRefType, nullptr);
14039 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14040 QualType CaptureType;
14041 QualType DeclRefType;
14043 // Determine whether we can capture this variable.
14044 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14045 /*BuildAndDiagnose=*/false, CaptureType,
14046 DeclRefType, nullptr))
14049 return DeclRefType;
14054 // If either the type of the variable or the initializer is dependent,
14055 // return false. Otherwise, determine whether the variable is a constant
14056 // expression. Use this if you need to know if a variable that might or
14057 // might not be dependent is truly a constant expression.
14058 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14059 ASTContext &Context) {
14061 if (Var->getType()->isDependentType())
14063 const VarDecl *DefVD = nullptr;
14064 Var->getAnyInitializer(DefVD);
14067 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14068 Expr *Init = cast<Expr>(Eval->Value);
14069 if (Init->isValueDependent())
14071 return IsVariableAConstantExpression(Var, Context);
14075 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14076 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14077 // an object that satisfies the requirements for appearing in a
14078 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14079 // is immediately applied." This function handles the lvalue-to-rvalue
14080 // conversion part.
14081 MaybeODRUseExprs.erase(E->IgnoreParens());
14083 // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14084 // to a variable that is a constant expression, and if so, identify it as
14085 // a reference to a variable that does not involve an odr-use of that
14087 if (LambdaScopeInfo *LSI = getCurLambda()) {
14088 Expr *SansParensExpr = E->IgnoreParens();
14089 VarDecl *Var = nullptr;
14090 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14091 Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14092 else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14093 Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14095 if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14096 LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14100 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14101 Res = CorrectDelayedTyposInExpr(Res);
14103 if (!Res.isUsable())
14106 // If a constant-expression is a reference to a variable where we delay
14107 // deciding whether it is an odr-use, just assume we will apply the
14108 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
14109 // (a non-type template argument), we have special handling anyway.
14110 UpdateMarkingForLValueToRValue(Res.get());
14114 void Sema::CleanupVarDeclMarking() {
14115 for (Expr *E : MaybeODRUseExprs) {
14117 SourceLocation Loc;
14118 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14119 Var = cast<VarDecl>(DRE->getDecl());
14120 Loc = DRE->getLocation();
14121 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14122 Var = cast<VarDecl>(ME->getMemberDecl());
14123 Loc = ME->getMemberLoc();
14125 llvm_unreachable("Unexpected expression");
14128 MarkVarDeclODRUsed(Var, Loc, *this,
14129 /*MaxFunctionScopeIndex Pointer*/ nullptr);
14132 MaybeODRUseExprs.clear();
14136 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14137 VarDecl *Var, Expr *E) {
14138 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14139 "Invalid Expr argument to DoMarkVarDeclReferenced");
14140 Var->setReferenced();
14142 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14144 bool OdrUseContext = isOdrUseContext(SemaRef);
14145 bool NeedDefinition =
14146 OdrUseContext || (isEvaluatableContext(SemaRef) &&
14147 Var->isUsableInConstantExpressions(SemaRef.Context));
14149 VarTemplateSpecializationDecl *VarSpec =
14150 dyn_cast<VarTemplateSpecializationDecl>(Var);
14151 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14152 "Can't instantiate a partial template specialization.");
14154 // If this might be a member specialization of a static data member, check
14155 // the specialization is visible. We already did the checks for variable
14156 // template specializations when we created them.
14157 if (NeedDefinition && TSK != TSK_Undeclared &&
14158 !isa<VarTemplateSpecializationDecl>(Var))
14159 SemaRef.checkSpecializationVisibility(Loc, Var);
14161 // Perform implicit instantiation of static data members, static data member
14162 // templates of class templates, and variable template specializations. Delay
14163 // instantiations of variable templates, except for those that could be used
14164 // in a constant expression.
14165 if (NeedDefinition && isTemplateInstantiation(TSK)) {
14166 bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14168 if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14169 if (Var->getPointOfInstantiation().isInvalid()) {
14170 // This is a modification of an existing AST node. Notify listeners.
14171 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14172 L->StaticDataMemberInstantiated(Var);
14173 } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14174 // Don't bother trying to instantiate it again, unless we might need
14175 // its initializer before we get to the end of the TU.
14176 TryInstantiating = false;
14179 if (Var->getPointOfInstantiation().isInvalid())
14180 Var->setTemplateSpecializationKind(TSK, Loc);
14182 if (TryInstantiating) {
14183 SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14184 bool InstantiationDependent = false;
14185 bool IsNonDependent =
14186 VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14187 VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14190 // Do not instantiate specializations that are still type-dependent.
14191 if (IsNonDependent) {
14192 if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14193 // Do not defer instantiations of variables which could be used in a
14194 // constant expression.
14195 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14197 SemaRef.PendingInstantiations
14198 .push_back(std::make_pair(Var, PointOfInstantiation));
14204 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14205 // the requirements for appearing in a constant expression (5.19) and, if
14206 // it is an object, the lvalue-to-rvalue conversion (4.1)
14207 // is immediately applied." We check the first part here, and
14208 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14209 // Note that we use the C++11 definition everywhere because nothing in
14210 // C++03 depends on whether we get the C++03 version correct. The second
14211 // part does not apply to references, since they are not objects.
14212 if (OdrUseContext && E &&
14213 IsVariableAConstantExpression(Var, SemaRef.Context)) {
14214 // A reference initialized by a constant expression can never be
14215 // odr-used, so simply ignore it.
14216 if (!Var->getType()->isReferenceType())
14217 SemaRef.MaybeODRUseExprs.insert(E);
14218 } else if (OdrUseContext) {
14219 MarkVarDeclODRUsed(Var, Loc, SemaRef,
14220 /*MaxFunctionScopeIndex ptr*/ nullptr);
14221 } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
14222 // If this is a dependent context, we don't need to mark variables as
14223 // odr-used, but we may still need to track them for lambda capture.
14224 // FIXME: Do we also need to do this inside dependent typeid expressions
14225 // (which are modeled as unevaluated at this point)?
14226 const bool RefersToEnclosingScope =
14227 (SemaRef.CurContext != Var->getDeclContext() &&
14228 Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
14229 if (RefersToEnclosingScope) {
14230 if (LambdaScopeInfo *const LSI =
14231 SemaRef.getCurLambda(/*IgnoreCapturedRegions=*/true)) {
14232 // If a variable could potentially be odr-used, defer marking it so
14233 // until we finish analyzing the full expression for any
14234 // lvalue-to-rvalue
14235 // or discarded value conversions that would obviate odr-use.
14236 // Add it to the list of potential captures that will be analyzed
14237 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14238 // unless the variable is a reference that was initialized by a constant
14239 // expression (this will never need to be captured or odr-used).
14240 assert(E && "Capture variable should be used in an expression.");
14241 if (!Var->getType()->isReferenceType() ||
14242 !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14243 LSI->addPotentialCapture(E->IgnoreParens());
14249 /// \brief Mark a variable referenced, and check whether it is odr-used
14250 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
14251 /// used directly for normal expressions referring to VarDecl.
14252 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14253 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14256 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14257 Decl *D, Expr *E, bool MightBeOdrUse) {
14258 if (SemaRef.isInOpenMPDeclareTargetContext())
14259 SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14261 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14262 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14266 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14268 // If this is a call to a method via a cast, also mark the method in the
14269 // derived class used in case codegen can devirtualize the call.
14270 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14273 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14276 // Only attempt to devirtualize if this is truly a virtual call.
14277 bool IsVirtualCall = MD->isVirtual() &&
14278 ME->performsVirtualDispatch(SemaRef.getLangOpts());
14279 if (!IsVirtualCall)
14281 const Expr *Base = ME->getBase();
14282 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14283 if (!MostDerivedClassDecl)
14285 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14286 if (!DM || DM->isPure())
14288 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14291 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14292 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14293 // TODO: update this with DR# once a defect report is filed.
14294 // C++11 defect. The address of a pure member should not be an ODR use, even
14295 // if it's a qualified reference.
14296 bool OdrUse = true;
14297 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14298 if (Method->isVirtual())
14300 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14303 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14304 void Sema::MarkMemberReferenced(MemberExpr *E) {
14305 // C++11 [basic.def.odr]p2:
14306 // A non-overloaded function whose name appears as a potentially-evaluated
14307 // expression or a member of a set of candidate functions, if selected by
14308 // overload resolution when referred to from a potentially-evaluated
14309 // expression, is odr-used, unless it is a pure virtual function and its
14310 // name is not explicitly qualified.
14311 bool MightBeOdrUse = true;
14312 if (E->performsVirtualDispatch(getLangOpts())) {
14313 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14314 if (Method->isPure())
14315 MightBeOdrUse = false;
14317 SourceLocation Loc = E->getMemberLoc().isValid() ?
14318 E->getMemberLoc() : E->getLocStart();
14319 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14322 /// \brief Perform marking for a reference to an arbitrary declaration. It
14323 /// marks the declaration referenced, and performs odr-use checking for
14324 /// functions and variables. This method should not be used when building a
14325 /// normal expression which refers to a variable.
14326 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14327 bool MightBeOdrUse) {
14328 if (MightBeOdrUse) {
14329 if (auto *VD = dyn_cast<VarDecl>(D)) {
14330 MarkVariableReferenced(Loc, VD);
14334 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14335 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14338 D->setReferenced();
14342 // Mark all of the declarations used by a type as referenced.
14343 // FIXME: Not fully implemented yet! We need to have a better understanding
14344 // of when we're entering a context we should not recurse into.
14345 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
14346 // TreeTransforms rebuilding the type in a new context. Rather than
14347 // duplicating the TreeTransform logic, we should consider reusing it here.
14348 // Currently that causes problems when rebuilding LambdaExprs.
14349 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14351 SourceLocation Loc;
14354 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14356 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14358 bool TraverseTemplateArgument(const TemplateArgument &Arg);
14362 bool MarkReferencedDecls::TraverseTemplateArgument(
14363 const TemplateArgument &Arg) {
14365 // A non-type template argument is a constant-evaluated context.
14366 EnterExpressionEvaluationContext Evaluated(S, Sema::ConstantEvaluated);
14367 if (Arg.getKind() == TemplateArgument::Declaration) {
14368 if (Decl *D = Arg.getAsDecl())
14369 S.MarkAnyDeclReferenced(Loc, D, true);
14370 } else if (Arg.getKind() == TemplateArgument::Expression) {
14371 S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
14375 return Inherited::TraverseTemplateArgument(Arg);
14378 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14379 MarkReferencedDecls Marker(*this, Loc);
14380 Marker.TraverseType(T);
14384 /// \brief Helper class that marks all of the declarations referenced by
14385 /// potentially-evaluated subexpressions as "referenced".
14386 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14388 bool SkipLocalVariables;
14391 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14393 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14394 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14396 void VisitDeclRefExpr(DeclRefExpr *E) {
14397 // If we were asked not to visit local variables, don't.
14398 if (SkipLocalVariables) {
14399 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14400 if (VD->hasLocalStorage())
14404 S.MarkDeclRefReferenced(E);
14407 void VisitMemberExpr(MemberExpr *E) {
14408 S.MarkMemberReferenced(E);
14409 Inherited::VisitMemberExpr(E);
14412 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14413 S.MarkFunctionReferenced(E->getLocStart(),
14414 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14415 Visit(E->getSubExpr());
14418 void VisitCXXNewExpr(CXXNewExpr *E) {
14419 if (E->getOperatorNew())
14420 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14421 if (E->getOperatorDelete())
14422 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14423 Inherited::VisitCXXNewExpr(E);
14426 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14427 if (E->getOperatorDelete())
14428 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14429 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14430 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14431 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14432 S.MarkFunctionReferenced(E->getLocStart(),
14433 S.LookupDestructor(Record));
14436 Inherited::VisitCXXDeleteExpr(E);
14439 void VisitCXXConstructExpr(CXXConstructExpr *E) {
14440 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14441 Inherited::VisitCXXConstructExpr(E);
14444 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14445 Visit(E->getExpr());
14448 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14449 Inherited::VisitImplicitCastExpr(E);
14451 if (E->getCastKind() == CK_LValueToRValue)
14452 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14457 /// \brief Mark any declarations that appear within this expression or any
14458 /// potentially-evaluated subexpressions as "referenced".
14460 /// \param SkipLocalVariables If true, don't mark local variables as
14462 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14463 bool SkipLocalVariables) {
14464 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14467 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14468 /// of the program being compiled.
14470 /// This routine emits the given diagnostic when the code currently being
14471 /// type-checked is "potentially evaluated", meaning that there is a
14472 /// possibility that the code will actually be executable. Code in sizeof()
14473 /// expressions, code used only during overload resolution, etc., are not
14474 /// potentially evaluated. This routine will suppress such diagnostics or,
14475 /// in the absolutely nutty case of potentially potentially evaluated
14476 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14479 /// This routine should be used for all diagnostics that describe the run-time
14480 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14481 /// Failure to do so will likely result in spurious diagnostics or failures
14482 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14483 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14484 const PartialDiagnostic &PD) {
14485 switch (ExprEvalContexts.back().Context) {
14487 case UnevaluatedList:
14488 case UnevaluatedAbstract:
14489 case DiscardedStatement:
14490 // The argument will never be evaluated, so don't complain.
14493 case ConstantEvaluated:
14494 // Relevant diagnostics should be produced by constant evaluation.
14497 case PotentiallyEvaluated:
14498 case PotentiallyEvaluatedIfUsed:
14499 if (Statement && getCurFunctionOrMethodDecl()) {
14500 FunctionScopes.back()->PossiblyUnreachableDiags.
14501 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14512 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14513 CallExpr *CE, FunctionDecl *FD) {
14514 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14517 // If we're inside a decltype's expression, don't check for a valid return
14518 // type or construct temporaries until we know whether this is the last call.
14519 if (ExprEvalContexts.back().IsDecltype) {
14520 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14524 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14529 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14530 : FD(FD), CE(CE) { }
14532 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14534 S.Diag(Loc, diag::err_call_incomplete_return)
14535 << T << CE->getSourceRange();
14539 S.Diag(Loc, diag::err_call_function_incomplete_return)
14540 << CE->getSourceRange() << FD->getDeclName() << T;
14541 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14542 << FD->getDeclName();
14544 } Diagnoser(FD, CE);
14546 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14552 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14553 // will prevent this condition from triggering, which is what we want.
14554 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14555 SourceLocation Loc;
14557 unsigned diagnostic = diag::warn_condition_is_assignment;
14558 bool IsOrAssign = false;
14560 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14561 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14564 IsOrAssign = Op->getOpcode() == BO_OrAssign;
14566 // Greylist some idioms by putting them into a warning subcategory.
14567 if (ObjCMessageExpr *ME
14568 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14569 Selector Sel = ME->getSelector();
14571 // self = [<foo> init...]
14572 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14573 diagnostic = diag::warn_condition_is_idiomatic_assignment;
14575 // <foo> = [<bar> nextObject]
14576 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14577 diagnostic = diag::warn_condition_is_idiomatic_assignment;
14580 Loc = Op->getOperatorLoc();
14581 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14582 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14585 IsOrAssign = Op->getOperator() == OO_PipeEqual;
14586 Loc = Op->getOperatorLoc();
14587 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14588 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14590 // Not an assignment.
14594 Diag(Loc, diagnostic) << E->getSourceRange();
14596 SourceLocation Open = E->getLocStart();
14597 SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14598 Diag(Loc, diag::note_condition_assign_silence)
14599 << FixItHint::CreateInsertion(Open, "(")
14600 << FixItHint::CreateInsertion(Close, ")");
14603 Diag(Loc, diag::note_condition_or_assign_to_comparison)
14604 << FixItHint::CreateReplacement(Loc, "!=");
14606 Diag(Loc, diag::note_condition_assign_to_comparison)
14607 << FixItHint::CreateReplacement(Loc, "==");
14610 /// \brief Redundant parentheses over an equality comparison can indicate
14611 /// that the user intended an assignment used as condition.
14612 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14613 // Don't warn if the parens came from a macro.
14614 SourceLocation parenLoc = ParenE->getLocStart();
14615 if (parenLoc.isInvalid() || parenLoc.isMacroID())
14617 // Don't warn for dependent expressions.
14618 if (ParenE->isTypeDependent())
14621 Expr *E = ParenE->IgnoreParens();
14623 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14624 if (opE->getOpcode() == BO_EQ &&
14625 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14626 == Expr::MLV_Valid) {
14627 SourceLocation Loc = opE->getOperatorLoc();
14629 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14630 SourceRange ParenERange = ParenE->getSourceRange();
14631 Diag(Loc, diag::note_equality_comparison_silence)
14632 << FixItHint::CreateRemoval(ParenERange.getBegin())
14633 << FixItHint::CreateRemoval(ParenERange.getEnd());
14634 Diag(Loc, diag::note_equality_comparison_to_assign)
14635 << FixItHint::CreateReplacement(Loc, "=");
14639 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14640 bool IsConstexpr) {
14641 DiagnoseAssignmentAsCondition(E);
14642 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14643 DiagnoseEqualityWithExtraParens(parenE);
14645 ExprResult result = CheckPlaceholderExpr(E);
14646 if (result.isInvalid()) return ExprError();
14649 if (!E->isTypeDependent()) {
14650 if (getLangOpts().CPlusPlus)
14651 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14653 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14654 if (ERes.isInvalid())
14655 return ExprError();
14658 QualType T = E->getType();
14659 if (!T->isScalarType()) { // C99 6.8.4.1p1
14660 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14661 << T << E->getSourceRange();
14662 return ExprError();
14664 CheckBoolLikeConversion(E, Loc);
14670 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14671 Expr *SubExpr, ConditionKind CK) {
14672 // Empty conditions are valid in for-statements.
14674 return ConditionResult();
14678 case ConditionKind::Boolean:
14679 Cond = CheckBooleanCondition(Loc, SubExpr);
14682 case ConditionKind::ConstexprIf:
14683 Cond = CheckBooleanCondition(Loc, SubExpr, true);
14686 case ConditionKind::Switch:
14687 Cond = CheckSwitchCondition(Loc, SubExpr);
14690 if (Cond.isInvalid())
14691 return ConditionError();
14693 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14694 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14695 if (!FullExpr.get())
14696 return ConditionError();
14698 return ConditionResult(*this, nullptr, FullExpr,
14699 CK == ConditionKind::ConstexprIf);
14703 /// A visitor for rebuilding a call to an __unknown_any expression
14704 /// to have an appropriate type.
14705 struct RebuildUnknownAnyFunction
14706 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14710 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14712 ExprResult VisitStmt(Stmt *S) {
14713 llvm_unreachable("unexpected statement!");
14716 ExprResult VisitExpr(Expr *E) {
14717 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14718 << E->getSourceRange();
14719 return ExprError();
14722 /// Rebuild an expression which simply semantically wraps another
14723 /// expression which it shares the type and value kind of.
14724 template <class T> ExprResult rebuildSugarExpr(T *E) {
14725 ExprResult SubResult = Visit(E->getSubExpr());
14726 if (SubResult.isInvalid()) return ExprError();
14728 Expr *SubExpr = SubResult.get();
14729 E->setSubExpr(SubExpr);
14730 E->setType(SubExpr->getType());
14731 E->setValueKind(SubExpr->getValueKind());
14732 assert(E->getObjectKind() == OK_Ordinary);
14736 ExprResult VisitParenExpr(ParenExpr *E) {
14737 return rebuildSugarExpr(E);
14740 ExprResult VisitUnaryExtension(UnaryOperator *E) {
14741 return rebuildSugarExpr(E);
14744 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14745 ExprResult SubResult = Visit(E->getSubExpr());
14746 if (SubResult.isInvalid()) return ExprError();
14748 Expr *SubExpr = SubResult.get();
14749 E->setSubExpr(SubExpr);
14750 E->setType(S.Context.getPointerType(SubExpr->getType()));
14751 assert(E->getValueKind() == VK_RValue);
14752 assert(E->getObjectKind() == OK_Ordinary);
14756 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14757 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14759 E->setType(VD->getType());
14761 assert(E->getValueKind() == VK_RValue);
14762 if (S.getLangOpts().CPlusPlus &&
14763 !(isa<CXXMethodDecl>(VD) &&
14764 cast<CXXMethodDecl>(VD)->isInstance()))
14765 E->setValueKind(VK_LValue);
14770 ExprResult VisitMemberExpr(MemberExpr *E) {
14771 return resolveDecl(E, E->getMemberDecl());
14774 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14775 return resolveDecl(E, E->getDecl());
14780 /// Given a function expression of unknown-any type, try to rebuild it
14781 /// to have a function type.
14782 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14783 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14784 if (Result.isInvalid()) return ExprError();
14785 return S.DefaultFunctionArrayConversion(Result.get());
14789 /// A visitor for rebuilding an expression of type __unknown_anytype
14790 /// into one which resolves the type directly on the referring
14791 /// expression. Strict preservation of the original source
14792 /// structure is not a goal.
14793 struct RebuildUnknownAnyExpr
14794 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14798 /// The current destination type.
14801 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14802 : S(S), DestType(CastType) {}
14804 ExprResult VisitStmt(Stmt *S) {
14805 llvm_unreachable("unexpected statement!");
14808 ExprResult VisitExpr(Expr *E) {
14809 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14810 << E->getSourceRange();
14811 return ExprError();
14814 ExprResult VisitCallExpr(CallExpr *E);
14815 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14817 /// Rebuild an expression which simply semantically wraps another
14818 /// expression which it shares the type and value kind of.
14819 template <class T> ExprResult rebuildSugarExpr(T *E) {
14820 ExprResult SubResult = Visit(E->getSubExpr());
14821 if (SubResult.isInvalid()) return ExprError();
14822 Expr *SubExpr = SubResult.get();
14823 E->setSubExpr(SubExpr);
14824 E->setType(SubExpr->getType());
14825 E->setValueKind(SubExpr->getValueKind());
14826 assert(E->getObjectKind() == OK_Ordinary);
14830 ExprResult VisitParenExpr(ParenExpr *E) {
14831 return rebuildSugarExpr(E);
14834 ExprResult VisitUnaryExtension(UnaryOperator *E) {
14835 return rebuildSugarExpr(E);
14838 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14839 const PointerType *Ptr = DestType->getAs<PointerType>();
14841 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14842 << E->getSourceRange();
14843 return ExprError();
14846 if (isa<CallExpr>(E->getSubExpr())) {
14847 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
14848 << E->getSourceRange();
14849 return ExprError();
14852 assert(E->getValueKind() == VK_RValue);
14853 assert(E->getObjectKind() == OK_Ordinary);
14854 E->setType(DestType);
14856 // Build the sub-expression as if it were an object of the pointee type.
14857 DestType = Ptr->getPointeeType();
14858 ExprResult SubResult = Visit(E->getSubExpr());
14859 if (SubResult.isInvalid()) return ExprError();
14860 E->setSubExpr(SubResult.get());
14864 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14866 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14868 ExprResult VisitMemberExpr(MemberExpr *E) {
14869 return resolveDecl(E, E->getMemberDecl());
14872 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14873 return resolveDecl(E, E->getDecl());
14878 /// Rebuilds a call expression which yielded __unknown_anytype.
14879 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14880 Expr *CalleeExpr = E->getCallee();
14884 FK_FunctionPointer,
14889 QualType CalleeType = CalleeExpr->getType();
14890 if (CalleeType == S.Context.BoundMemberTy) {
14891 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14892 Kind = FK_MemberFunction;
14893 CalleeType = Expr::findBoundMemberType(CalleeExpr);
14894 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14895 CalleeType = Ptr->getPointeeType();
14896 Kind = FK_FunctionPointer;
14898 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14899 Kind = FK_BlockPointer;
14901 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14903 // Verify that this is a legal result type of a function.
14904 if (DestType->isArrayType() || DestType->isFunctionType()) {
14905 unsigned diagID = diag::err_func_returning_array_function;
14906 if (Kind == FK_BlockPointer)
14907 diagID = diag::err_block_returning_array_function;
14909 S.Diag(E->getExprLoc(), diagID)
14910 << DestType->isFunctionType() << DestType;
14911 return ExprError();
14914 // Otherwise, go ahead and set DestType as the call's result.
14915 E->setType(DestType.getNonLValueExprType(S.Context));
14916 E->setValueKind(Expr::getValueKindForType(DestType));
14917 assert(E->getObjectKind() == OK_Ordinary);
14919 // Rebuild the function type, replacing the result type with DestType.
14920 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14922 // __unknown_anytype(...) is a special case used by the debugger when
14923 // it has no idea what a function's signature is.
14925 // We want to build this call essentially under the K&R
14926 // unprototyped rules, but making a FunctionNoProtoType in C++
14927 // would foul up all sorts of assumptions. However, we cannot
14928 // simply pass all arguments as variadic arguments, nor can we
14929 // portably just call the function under a non-variadic type; see
14930 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14931 // However, it turns out that in practice it is generally safe to
14932 // call a function declared as "A foo(B,C,D);" under the prototype
14933 // "A foo(B,C,D,...);". The only known exception is with the
14934 // Windows ABI, where any variadic function is implicitly cdecl
14935 // regardless of its normal CC. Therefore we change the parameter
14936 // types to match the types of the arguments.
14938 // This is a hack, but it is far superior to moving the
14939 // corresponding target-specific code from IR-gen to Sema/AST.
14941 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14942 SmallVector<QualType, 8> ArgTypes;
14943 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14944 ArgTypes.reserve(E->getNumArgs());
14945 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14946 Expr *Arg = E->getArg(i);
14947 QualType ArgType = Arg->getType();
14948 if (E->isLValue()) {
14949 ArgType = S.Context.getLValueReferenceType(ArgType);
14950 } else if (E->isXValue()) {
14951 ArgType = S.Context.getRValueReferenceType(ArgType);
14953 ArgTypes.push_back(ArgType);
14955 ParamTypes = ArgTypes;
14957 DestType = S.Context.getFunctionType(DestType, ParamTypes,
14958 Proto->getExtProtoInfo());
14960 DestType = S.Context.getFunctionNoProtoType(DestType,
14961 FnType->getExtInfo());
14964 // Rebuild the appropriate pointer-to-function type.
14966 case FK_MemberFunction:
14970 case FK_FunctionPointer:
14971 DestType = S.Context.getPointerType(DestType);
14974 case FK_BlockPointer:
14975 DestType = S.Context.getBlockPointerType(DestType);
14979 // Finally, we can recurse.
14980 ExprResult CalleeResult = Visit(CalleeExpr);
14981 if (!CalleeResult.isUsable()) return ExprError();
14982 E->setCallee(CalleeResult.get());
14984 // Bind a temporary if necessary.
14985 return S.MaybeBindToTemporary(E);
14988 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14989 // Verify that this is a legal result type of a call.
14990 if (DestType->isArrayType() || DestType->isFunctionType()) {
14991 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14992 << DestType->isFunctionType() << DestType;
14993 return ExprError();
14996 // Rewrite the method result type if available.
14997 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14998 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14999 Method->setReturnType(DestType);
15002 // Change the type of the message.
15003 E->setType(DestType.getNonReferenceType());
15004 E->setValueKind(Expr::getValueKindForType(DestType));
15006 return S.MaybeBindToTemporary(E);
15009 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15010 // The only case we should ever see here is a function-to-pointer decay.
15011 if (E->getCastKind() == CK_FunctionToPointerDecay) {
15012 assert(E->getValueKind() == VK_RValue);
15013 assert(E->getObjectKind() == OK_Ordinary);
15015 E->setType(DestType);
15017 // Rebuild the sub-expression as the pointee (function) type.
15018 DestType = DestType->castAs<PointerType>()->getPointeeType();
15020 ExprResult Result = Visit(E->getSubExpr());
15021 if (!Result.isUsable()) return ExprError();
15023 E->setSubExpr(Result.get());
15025 } else if (E->getCastKind() == CK_LValueToRValue) {
15026 assert(E->getValueKind() == VK_RValue);
15027 assert(E->getObjectKind() == OK_Ordinary);
15029 assert(isa<BlockPointerType>(E->getType()));
15031 E->setType(DestType);
15033 // The sub-expression has to be a lvalue reference, so rebuild it as such.
15034 DestType = S.Context.getLValueReferenceType(DestType);
15036 ExprResult Result = Visit(E->getSubExpr());
15037 if (!Result.isUsable()) return ExprError();
15039 E->setSubExpr(Result.get());
15042 llvm_unreachable("Unhandled cast type!");
15046 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15047 ExprValueKind ValueKind = VK_LValue;
15048 QualType Type = DestType;
15050 // We know how to make this work for certain kinds of decls:
15053 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15054 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15055 DestType = Ptr->getPointeeType();
15056 ExprResult Result = resolveDecl(E, VD);
15057 if (Result.isInvalid()) return ExprError();
15058 return S.ImpCastExprToType(Result.get(), Type,
15059 CK_FunctionToPointerDecay, VK_RValue);
15062 if (!Type->isFunctionType()) {
15063 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15064 << VD << E->getSourceRange();
15065 return ExprError();
15067 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15068 // We must match the FunctionDecl's type to the hack introduced in
15069 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15070 // type. See the lengthy commentary in that routine.
15071 QualType FDT = FD->getType();
15072 const FunctionType *FnType = FDT->castAs<FunctionType>();
15073 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15074 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15075 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15076 SourceLocation Loc = FD->getLocation();
15077 FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15078 FD->getDeclContext(),
15079 Loc, Loc, FD->getNameInfo().getName(),
15080 DestType, FD->getTypeSourceInfo(),
15081 SC_None, false/*isInlineSpecified*/,
15082 FD->hasPrototype(),
15083 false/*isConstexprSpecified*/);
15085 if (FD->getQualifier())
15086 NewFD->setQualifierInfo(FD->getQualifierLoc());
15088 SmallVector<ParmVarDecl*, 16> Params;
15089 for (const auto &AI : FT->param_types()) {
15090 ParmVarDecl *Param =
15091 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15092 Param->setScopeInfo(0, Params.size());
15093 Params.push_back(Param);
15095 NewFD->setParams(Params);
15096 DRE->setDecl(NewFD);
15097 VD = DRE->getDecl();
15101 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15102 if (MD->isInstance()) {
15103 ValueKind = VK_RValue;
15104 Type = S.Context.BoundMemberTy;
15107 // Function references aren't l-values in C.
15108 if (!S.getLangOpts().CPlusPlus)
15109 ValueKind = VK_RValue;
15112 } else if (isa<VarDecl>(VD)) {
15113 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15114 Type = RefTy->getPointeeType();
15115 } else if (Type->isFunctionType()) {
15116 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15117 << VD << E->getSourceRange();
15118 return ExprError();
15123 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15124 << VD << E->getSourceRange();
15125 return ExprError();
15128 // Modifying the declaration like this is friendly to IR-gen but
15129 // also really dangerous.
15130 VD->setType(DestType);
15132 E->setValueKind(ValueKind);
15136 /// Check a cast of an unknown-any type. We intentionally only
15137 /// trigger this for C-style casts.
15138 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15139 Expr *CastExpr, CastKind &CastKind,
15140 ExprValueKind &VK, CXXCastPath &Path) {
15141 // The type we're casting to must be either void or complete.
15142 if (!CastType->isVoidType() &&
15143 RequireCompleteType(TypeRange.getBegin(), CastType,
15144 diag::err_typecheck_cast_to_incomplete))
15145 return ExprError();
15147 // Rewrite the casted expression from scratch.
15148 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15149 if (!result.isUsable()) return ExprError();
15151 CastExpr = result.get();
15152 VK = CastExpr->getValueKind();
15153 CastKind = CK_NoOp;
15158 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15159 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15162 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15163 Expr *arg, QualType ¶mType) {
15164 // If the syntactic form of the argument is not an explicit cast of
15165 // any sort, just do default argument promotion.
15166 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15168 ExprResult result = DefaultArgumentPromotion(arg);
15169 if (result.isInvalid()) return ExprError();
15170 paramType = result.get()->getType();
15174 // Otherwise, use the type that was written in the explicit cast.
15175 assert(!arg->hasPlaceholderType());
15176 paramType = castArg->getTypeAsWritten();
15178 // Copy-initialize a parameter of that type.
15179 InitializedEntity entity =
15180 InitializedEntity::InitializeParameter(Context, paramType,
15181 /*consumed*/ false);
15182 return PerformCopyInitialization(entity, callLoc, arg);
15185 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15187 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15189 E = E->IgnoreParenImpCasts();
15190 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15191 E = call->getCallee();
15192 diagID = diag::err_uncasted_call_of_unknown_any;
15198 SourceLocation loc;
15200 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15201 loc = ref->getLocation();
15202 d = ref->getDecl();
15203 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15204 loc = mem->getMemberLoc();
15205 d = mem->getMemberDecl();
15206 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15207 diagID = diag::err_uncasted_call_of_unknown_any;
15208 loc = msg->getSelectorStartLoc();
15209 d = msg->getMethodDecl();
15211 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15212 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15213 << orig->getSourceRange();
15214 return ExprError();
15217 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15218 << E->getSourceRange();
15219 return ExprError();
15222 S.Diag(loc, diagID) << d << orig->getSourceRange();
15224 // Never recoverable.
15225 return ExprError();
15228 /// Check for operands with placeholder types and complain if found.
15229 /// Returns true if there was an error and no recovery was possible.
15230 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15231 if (!getLangOpts().CPlusPlus) {
15232 // C cannot handle TypoExpr nodes on either side of a binop because it
15233 // doesn't handle dependent types properly, so make sure any TypoExprs have
15234 // been dealt with before checking the operands.
15235 ExprResult Result = CorrectDelayedTyposInExpr(E);
15236 if (!Result.isUsable()) return ExprError();
15240 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15241 if (!placeholderType) return E;
15243 switch (placeholderType->getKind()) {
15245 // Overloaded expressions.
15246 case BuiltinType::Overload: {
15247 // Try to resolve a single function template specialization.
15248 // This is obligatory.
15249 ExprResult Result = E;
15250 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15253 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15254 // leaves Result unchanged on failure.
15256 if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15259 // If that failed, try to recover with a call.
15260 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15261 /*complain*/ true);
15265 // Bound member functions.
15266 case BuiltinType::BoundMember: {
15267 ExprResult result = E;
15268 const Expr *BME = E->IgnoreParens();
15269 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15270 // Try to give a nicer diagnostic if it is a bound member that we recognize.
15271 if (isa<CXXPseudoDestructorExpr>(BME)) {
15272 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15273 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15274 if (ME->getMemberNameInfo().getName().getNameKind() ==
15275 DeclarationName::CXXDestructorName)
15276 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15278 tryToRecoverWithCall(result, PD,
15279 /*complain*/ true);
15283 // ARC unbridged casts.
15284 case BuiltinType::ARCUnbridgedCast: {
15285 Expr *realCast = stripARCUnbridgedCast(E);
15286 diagnoseARCUnbridgedCast(realCast);
15290 // Expressions of unknown type.
15291 case BuiltinType::UnknownAny:
15292 return diagnoseUnknownAnyExpr(*this, E);
15295 case BuiltinType::PseudoObject:
15296 return checkPseudoObjectRValue(E);
15298 case BuiltinType::BuiltinFn: {
15299 // Accept __noop without parens by implicitly converting it to a call expr.
15300 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15302 auto *FD = cast<FunctionDecl>(DRE->getDecl());
15303 if (FD->getBuiltinID() == Builtin::BI__noop) {
15304 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15305 CK_BuiltinFnToFnPtr).get();
15306 return new (Context) CallExpr(Context, E, None, Context.IntTy,
15307 VK_RValue, SourceLocation());
15311 Diag(E->getLocStart(), diag::err_builtin_fn_use);
15312 return ExprError();
15315 // Expressions of unknown type.
15316 case BuiltinType::OMPArraySection:
15317 Diag(E->getLocStart(), diag::err_omp_array_section_use);
15318 return ExprError();
15320 // Everything else should be impossible.
15321 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15322 case BuiltinType::Id:
15323 #include "clang/Basic/OpenCLImageTypes.def"
15324 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15325 #define PLACEHOLDER_TYPE(Id, SingletonId)
15326 #include "clang/AST/BuiltinTypes.def"
15330 llvm_unreachable("invalid placeholder type!");
15333 bool Sema::CheckCaseExpression(Expr *E) {
15334 if (E->isTypeDependent())
15336 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15337 return E->getType()->isIntegralOrEnumerationType();
15341 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15343 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15344 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15345 "Unknown Objective-C Boolean value!");
15346 QualType BoolT = Context.ObjCBuiltinBoolTy;
15347 if (!Context.getBOOLDecl()) {
15348 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15349 Sema::LookupOrdinaryName);
15350 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15351 NamedDecl *ND = Result.getFoundDecl();
15352 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15353 Context.setBOOLDecl(TD);
15356 if (Context.getBOOLDecl())
15357 BoolT = Context.getBOOLType();
15358 return new (Context)
15359 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15362 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15363 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15364 SourceLocation RParen) {
15366 StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15368 auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15369 [&](const AvailabilitySpec &Spec) {
15370 return Spec.getPlatform() == Platform;
15373 VersionTuple Version;
15374 if (Spec != AvailSpecs.end())
15375 Version = Spec->getVersion();
15377 return new (Context)
15378 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);