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 "clang/Sema/SemaInternal.h"
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.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/RecursiveASTVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/AnalysisBasedWarnings.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/DelayedDiagnostic.h"
36 #include "clang/Sema/Designator.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Sema/ParsedTemplate.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "clang/Sema/SemaFixItUtils.h"
43 #include "clang/Sema/Template.h"
44 using namespace clang;
47 /// \brief Determine whether the use of this declaration is valid, without
48 /// emitting diagnostics.
49 bool Sema::CanUseDecl(NamedDecl *D) {
50 // See if this is an auto-typed variable whose initializer we are parsing.
51 if (ParsingInitForAutoVars.count(D))
54 // See if this is a deleted function.
55 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
60 // See if this function is unavailable.
61 if (D->getAvailability() == AR_Unavailable &&
62 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
68 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
69 // Warn if this is used but marked unused.
70 if (D->hasAttr<UnusedAttr>()) {
71 const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
72 if (!DC->hasAttr<UnusedAttr>())
73 S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
77 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
78 NamedDecl *D, SourceLocation Loc,
79 const ObjCInterfaceDecl *UnknownObjCClass) {
80 // See if this declaration is unavailable or deprecated.
82 AvailabilityResult Result = D->getAvailability(&Message);
83 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
84 if (Result == AR_Available) {
85 const DeclContext *DC = ECD->getDeclContext();
86 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
87 Result = TheEnumDecl->getAvailability(&Message);
90 const ObjCPropertyDecl *ObjCPDecl = 0;
91 if (Result == AR_Deprecated || Result == AR_Unavailable) {
92 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
93 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
94 AvailabilityResult PDeclResult = PD->getAvailability(0);
95 if (PDeclResult == Result)
103 case AR_NotYetIntroduced:
107 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
111 if (S.getCurContextAvailability() != AR_Unavailable) {
112 if (Message.empty()) {
113 if (!UnknownObjCClass) {
114 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
116 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
117 << ObjCPDecl->getDeclName() << 1;
120 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
124 S.Diag(Loc, diag::err_unavailable_message)
125 << D->getDeclName() << Message;
126 S.Diag(D->getLocation(), diag::note_unavailable_here)
127 << isa<FunctionDecl>(D) << false;
129 S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
130 << ObjCPDecl->getDeclName() << 1;
137 /// \brief Emit a note explaining that this function is deleted or unavailable.
138 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
139 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
141 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
142 // If the method was explicitly defaulted, point at that declaration.
143 if (!Method->isImplicit())
144 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
146 // Try to diagnose why this special member function was implicitly
147 // deleted. This might fail, if that reason no longer applies.
148 CXXSpecialMember CSM = getSpecialMember(Method);
149 if (CSM != CXXInvalid)
150 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
155 Diag(Decl->getLocation(), diag::note_unavailable_here)
156 << 1 << Decl->isDeleted();
159 /// \brief Determine whether a FunctionDecl was ever declared with an
160 /// explicit storage class.
161 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
162 for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
163 E = D->redecls_end();
165 if (I->getStorageClass() != SC_None)
171 /// \brief Check whether we're in an extern inline function and referring to a
172 /// variable or function with internal linkage (C11 6.7.4p3).
174 /// This is only a warning because we used to silently accept this code, but
175 /// in many cases it will not behave correctly. This is not enabled in C++ mode
176 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
177 /// and so while there may still be user mistakes, most of the time we can't
178 /// prove that there are errors.
179 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
181 SourceLocation Loc) {
182 // This is disabled under C++; there are too many ways for this to fire in
183 // contexts where the warning is a false positive, or where it is technically
184 // correct but benign.
185 if (S.getLangOpts().CPlusPlus)
188 // Check if this is an inlined function or method.
189 FunctionDecl *Current = S.getCurFunctionDecl();
192 if (!Current->isInlined())
194 if (Current->getLinkage() != ExternalLinkage)
197 // Check if the decl has internal linkage.
198 if (D->getLinkage() != InternalLinkage)
201 // Downgrade from ExtWarn to Extension if
202 // (1) the supposedly external inline function is in the main file,
203 // and probably won't be included anywhere else.
204 // (2) the thing we're referencing is a pure function.
205 // (3) the thing we're referencing is another inline function.
206 // This last can give us false negatives, but it's better than warning on
207 // wrappers for simple C library functions.
208 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
209 bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
210 if (!DowngradeWarning && UsedFn)
211 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
213 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
214 : diag::warn_internal_in_extern_inline)
215 << /*IsVar=*/!UsedFn << D;
217 S.MaybeSuggestAddingStaticToDecl(Current);
219 S.Diag(D->getCanonicalDecl()->getLocation(),
220 diag::note_internal_decl_declared_here)
224 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
225 const FunctionDecl *First = Cur->getFirstDeclaration();
227 // Suggest "static" on the function, if possible.
228 if (!hasAnyExplicitStorageClass(First)) {
229 SourceLocation DeclBegin = First->getSourceRange().getBegin();
230 Diag(DeclBegin, diag::note_convert_inline_to_static)
231 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
235 /// \brief Determine whether the use of this declaration is valid, and
236 /// emit any corresponding diagnostics.
238 /// This routine diagnoses various problems with referencing
239 /// declarations that can occur when using a declaration. For example,
240 /// it might warn if a deprecated or unavailable declaration is being
241 /// used, or produce an error (and return true) if a C++0x deleted
242 /// function is being used.
244 /// \returns true if there was an error (this declaration cannot be
245 /// referenced), false otherwise.
247 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
248 const ObjCInterfaceDecl *UnknownObjCClass) {
249 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
250 // If there were any diagnostics suppressed by template argument deduction,
252 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
253 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
254 if (Pos != SuppressedDiagnostics.end()) {
255 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
256 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
257 Diag(Suppressed[I].first, Suppressed[I].second);
259 // Clear out the list of suppressed diagnostics, so that we don't emit
260 // them again for this specialization. However, we don't obsolete this
261 // entry from the table, because we want to avoid ever emitting these
262 // diagnostics again.
267 // See if this is an auto-typed variable whose initializer we are parsing.
268 if (ParsingInitForAutoVars.count(D)) {
269 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
274 // See if this is a deleted function.
275 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
276 if (FD->isDeleted()) {
277 Diag(Loc, diag::err_deleted_function_use);
278 NoteDeletedFunction(FD);
282 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
284 DiagnoseUnusedOfDecl(*this, D, Loc);
286 diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
291 /// \brief Retrieve the message suffix that should be added to a
292 /// diagnostic complaining about the given function being deleted or
294 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
296 if (FD->getAvailability(&Message))
297 return ": " + Message;
299 return std::string();
302 /// DiagnoseSentinelCalls - This routine checks whether a call or
303 /// message-send is to a declaration with the sentinel attribute, and
304 /// if so, it checks that the requirements of the sentinel are
306 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
307 Expr **args, unsigned numArgs) {
308 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
312 // The number of formal parameters of the declaration.
313 unsigned numFormalParams;
315 // The kind of declaration. This is also an index into a %select in
317 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
319 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
320 numFormalParams = MD->param_size();
321 calleeType = CT_Method;
322 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
323 numFormalParams = FD->param_size();
324 calleeType = CT_Function;
325 } else if (isa<VarDecl>(D)) {
326 QualType type = cast<ValueDecl>(D)->getType();
327 const FunctionType *fn = 0;
328 if (const PointerType *ptr = type->getAs<PointerType>()) {
329 fn = ptr->getPointeeType()->getAs<FunctionType>();
331 calleeType = CT_Function;
332 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
333 fn = ptr->getPointeeType()->castAs<FunctionType>();
334 calleeType = CT_Block;
339 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
340 numFormalParams = proto->getNumArgs();
348 // "nullPos" is the number of formal parameters at the end which
349 // effectively count as part of the variadic arguments. This is
350 // useful if you would prefer to not have *any* formal parameters,
351 // but the language forces you to have at least one.
352 unsigned nullPos = attr->getNullPos();
353 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
354 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
356 // The number of arguments which should follow the sentinel.
357 unsigned numArgsAfterSentinel = attr->getSentinel();
359 // If there aren't enough arguments for all the formal parameters,
360 // the sentinel, and the args after the sentinel, complain.
361 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
362 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
363 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
367 // Otherwise, find the sentinel expression.
368 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
369 if (!sentinelExpr) return;
370 if (sentinelExpr->isValueDependent()) return;
371 if (Context.isSentinelNullExpr(sentinelExpr)) return;
373 // Pick a reasonable string to insert. Optimistically use 'nil' or
374 // 'NULL' if those are actually defined in the context. Only use
375 // 'nil' for ObjC methods, where it's much more likely that the
376 // variadic arguments form a list of object pointers.
377 SourceLocation MissingNilLoc
378 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
379 std::string NullValue;
380 if (calleeType == CT_Method &&
381 PP.getIdentifierInfo("nil")->hasMacroDefinition())
383 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
386 NullValue = "(void*) 0";
388 if (MissingNilLoc.isInvalid())
389 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
391 Diag(MissingNilLoc, diag::warn_missing_sentinel)
393 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
394 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
397 SourceRange Sema::getExprRange(Expr *E) const {
398 return E ? E->getSourceRange() : SourceRange();
401 //===----------------------------------------------------------------------===//
402 // Standard Promotions and Conversions
403 //===----------------------------------------------------------------------===//
405 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
406 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
407 // Handle any placeholder expressions which made it here.
408 if (E->getType()->isPlaceholderType()) {
409 ExprResult result = CheckPlaceholderExpr(E);
410 if (result.isInvalid()) return ExprError();
414 QualType Ty = E->getType();
415 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
417 if (Ty->isFunctionType())
418 E = ImpCastExprToType(E, Context.getPointerType(Ty),
419 CK_FunctionToPointerDecay).take();
420 else if (Ty->isArrayType()) {
421 // In C90 mode, arrays only promote to pointers if the array expression is
422 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
423 // type 'array of type' is converted to an expression that has type 'pointer
424 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
425 // that has type 'array of type' ...". The relevant change is "an lvalue"
426 // (C90) to "an expression" (C99).
429 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
430 // T" can be converted to an rvalue of type "pointer to T".
432 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
433 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
434 CK_ArrayToPointerDecay).take();
439 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
440 // Check to see if we are dereferencing a null pointer. If so,
441 // and if not volatile-qualified, this is undefined behavior that the
442 // optimizer will delete, so warn about it. People sometimes try to use this
443 // to get a deterministic trap and are surprised by clang's behavior. This
444 // only handles the pattern "*null", which is a very syntactic check.
445 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
446 if (UO->getOpcode() == UO_Deref &&
447 UO->getSubExpr()->IgnoreParenCasts()->
448 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
449 !UO->getType().isVolatileQualified()) {
450 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
451 S.PDiag(diag::warn_indirection_through_null)
452 << UO->getSubExpr()->getSourceRange());
453 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
454 S.PDiag(diag::note_indirection_through_null));
458 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
459 SourceLocation AssignLoc,
461 const ObjCIvarDecl *IV = OIRE->getDecl();
465 DeclarationName MemberName = IV->getDeclName();
466 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
467 if (!Member || !Member->isStr("isa"))
470 const Expr *Base = OIRE->getBase();
471 QualType BaseType = Base->getType();
473 BaseType = BaseType->getPointeeType();
474 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
475 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
476 ObjCInterfaceDecl *ClassDeclared = 0;
477 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
478 if (!ClassDeclared->getSuperClass()
479 && (*ClassDeclared->ivar_begin()) == IV) {
481 NamedDecl *ObjectSetClass =
482 S.LookupSingleName(S.TUScope,
483 &S.Context.Idents.get("object_setClass"),
484 SourceLocation(), S.LookupOrdinaryName);
485 if (ObjectSetClass) {
486 SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
487 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
488 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
489 FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
491 FixItHint::CreateInsertion(RHSLocEnd, ")");
494 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
496 NamedDecl *ObjectGetClass =
497 S.LookupSingleName(S.TUScope,
498 &S.Context.Idents.get("object_getClass"),
499 SourceLocation(), S.LookupOrdinaryName);
501 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
502 FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
503 FixItHint::CreateReplacement(
504 SourceRange(OIRE->getOpLoc(),
505 OIRE->getLocEnd()), ")");
507 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
509 S.Diag(IV->getLocation(), diag::note_ivar_decl);
514 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
515 // Handle any placeholder expressions which made it here.
516 if (E->getType()->isPlaceholderType()) {
517 ExprResult result = CheckPlaceholderExpr(E);
518 if (result.isInvalid()) return ExprError();
522 // C++ [conv.lval]p1:
523 // A glvalue of a non-function, non-array type T can be
524 // converted to a prvalue.
525 if (!E->isGLValue()) return Owned(E);
527 QualType T = E->getType();
528 assert(!T.isNull() && "r-value conversion on typeless expression?");
530 // We don't want to throw lvalue-to-rvalue casts on top of
531 // expressions of certain types in C++.
532 if (getLangOpts().CPlusPlus &&
533 (E->getType() == Context.OverloadTy ||
534 T->isDependentType() ||
538 // The C standard is actually really unclear on this point, and
539 // DR106 tells us what the result should be but not why. It's
540 // generally best to say that void types just doesn't undergo
541 // lvalue-to-rvalue at all. Note that expressions of unqualified
542 // 'void' type are never l-values, but qualified void can be.
546 // OpenCL usually rejects direct accesses to values of 'half' type.
547 if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
549 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
554 CheckForNullPointerDereference(*this, E);
555 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
556 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
557 &Context.Idents.get("object_getClass"),
558 SourceLocation(), LookupOrdinaryName);
560 Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
561 FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
562 FixItHint::CreateReplacement(
563 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
565 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
567 else if (const ObjCIvarRefExpr *OIRE =
568 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
569 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0);
571 // C++ [conv.lval]p1:
572 // [...] If T is a non-class type, the type of the prvalue is the
573 // cv-unqualified version of T. Otherwise, the type of the
577 // If the lvalue has qualified type, the value has the unqualified
578 // version of the type of the lvalue; otherwise, the value has the
579 // type of the lvalue.
580 if (T.hasQualifiers())
581 T = T.getUnqualifiedType();
583 UpdateMarkingForLValueToRValue(E);
585 // Loading a __weak object implicitly retains the value, so we need a cleanup to
587 if (getLangOpts().ObjCAutoRefCount &&
588 E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
589 ExprNeedsCleanups = true;
591 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
595 // ... if the lvalue has atomic type, the value has the non-atomic version
596 // of the type of the lvalue ...
597 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
598 T = Atomic->getValueType().getUnqualifiedType();
599 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
600 Res.get(), 0, VK_RValue));
606 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
607 ExprResult Res = DefaultFunctionArrayConversion(E);
610 Res = DefaultLvalueConversion(Res.take());
617 /// UsualUnaryConversions - Performs various conversions that are common to most
618 /// operators (C99 6.3). The conversions of array and function types are
619 /// sometimes suppressed. For example, the array->pointer conversion doesn't
620 /// apply if the array is an argument to the sizeof or address (&) operators.
621 /// In these instances, this routine should *not* be called.
622 ExprResult Sema::UsualUnaryConversions(Expr *E) {
623 // First, convert to an r-value.
624 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
629 QualType Ty = E->getType();
630 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
632 // Half FP have to be promoted to float unless it is natively supported
633 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
634 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
636 // Try to perform integral promotions if the object has a theoretically
638 if (Ty->isIntegralOrUnscopedEnumerationType()) {
641 // The following may be used in an expression wherever an int or
642 // unsigned int may be used:
643 // - an object or expression with an integer type whose integer
644 // conversion rank is less than or equal to the rank of int
646 // - A bit-field of type _Bool, int, signed int, or unsigned int.
648 // If an int can represent all values of the original type, the
649 // value is converted to an int; otherwise, it is converted to an
650 // unsigned int. These are called the integer promotions. All
651 // other types are unchanged by the integer promotions.
653 QualType PTy = Context.isPromotableBitField(E);
655 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
658 if (Ty->isPromotableIntegerType()) {
659 QualType PT = Context.getPromotedIntegerType(Ty);
660 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
667 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
668 /// do not have a prototype. Arguments that have type float or __fp16
669 /// are promoted to double. All other argument types are converted by
670 /// UsualUnaryConversions().
671 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
672 QualType Ty = E->getType();
673 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
675 ExprResult Res = UsualUnaryConversions(E);
680 // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
682 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
683 if (BTy && (BTy->getKind() == BuiltinType::Half ||
684 BTy->getKind() == BuiltinType::Float))
685 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
687 // C++ performs lvalue-to-rvalue conversion as a default argument
688 // promotion, even on class types, but note:
689 // C++11 [conv.lval]p2:
690 // When an lvalue-to-rvalue conversion occurs in an unevaluated
691 // operand or a subexpression thereof the value contained in the
692 // referenced object is not accessed. Otherwise, if the glvalue
693 // has a class type, the conversion copy-initializes a temporary
694 // of type T from the glvalue and the result of the conversion
695 // is a prvalue for the temporary.
696 // FIXME: add some way to gate this entire thing for correctness in
697 // potentially potentially evaluated contexts.
698 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
699 ExprResult Temp = PerformCopyInitialization(
700 InitializedEntity::InitializeTemporary(E->getType()),
703 if (Temp.isInvalid())
711 /// Determine the degree of POD-ness for an expression.
712 /// Incomplete types are considered POD, since this check can be performed
713 /// when we're in an unevaluated context.
714 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
715 if (Ty->isIncompleteType()) {
716 if (Ty->isObjCObjectType())
721 if (Ty.isCXX98PODType(Context))
724 // C++11 [expr.call]p7:
725 // Passing a potentially-evaluated argument of class type (Clause 9)
726 // having a non-trivial copy constructor, a non-trivial move constructor,
727 // or a non-trivial destructor, with no corresponding parameter,
728 // is conditionally-supported with implementation-defined semantics.
729 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
730 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
731 if (!Record->hasNonTrivialCopyConstructor() &&
732 !Record->hasNonTrivialMoveConstructor() &&
733 !Record->hasNonTrivialDestructor())
734 return VAK_ValidInCXX11;
736 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
741 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
742 // Don't allow one to pass an Objective-C interface to a vararg.
743 const QualType & Ty = E->getType();
745 // Complain about passing non-POD types through varargs.
746 switch (isValidVarArgType(Ty)) {
749 case VAK_ValidInCXX11:
750 DiagRuntimeBehavior(E->getLocStart(), 0,
751 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
752 << E->getType() << CT);
755 if (Ty->isObjCObjectType())
756 return DiagRuntimeBehavior(E->getLocStart(), 0,
757 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
760 return DiagRuntimeBehavior(E->getLocStart(), 0,
761 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
762 << getLangOpts().CPlusPlus11 << Ty << CT);
765 // c++ rules are enforced elsewhere.
769 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
770 /// will create a trap if the resulting type is not a POD type.
771 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
772 FunctionDecl *FDecl) {
773 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
774 // Strip the unbridged-cast placeholder expression off, if applicable.
775 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
776 (CT == VariadicMethod ||
777 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
778 E = stripARCUnbridgedCast(E);
780 // Otherwise, do normal placeholder checking.
782 ExprResult ExprRes = CheckPlaceholderExpr(E);
783 if (ExprRes.isInvalid())
789 ExprResult ExprRes = DefaultArgumentPromotion(E);
790 if (ExprRes.isInvalid())
794 // Diagnostics regarding non-POD argument types are
795 // emitted along with format string checking in Sema::CheckFunctionCall().
796 if (isValidVarArgType(E->getType()) == VAK_Invalid) {
797 // Turn this into a trap.
799 SourceLocation TemplateKWLoc;
801 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
803 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
805 if (TrapFn.isInvalid())
808 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
809 E->getLocStart(), MultiExprArg(),
811 if (Call.isInvalid())
814 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
816 if (Comma.isInvalid())
821 if (!getLangOpts().CPlusPlus &&
822 RequireCompleteType(E->getExprLoc(), E->getType(),
823 diag::err_call_incomplete_argument))
829 /// \brief Converts an integer to complex float type. Helper function of
830 /// UsualArithmeticConversions()
832 /// \return false if the integer expression is an integer type and is
833 /// successfully converted to the complex type.
834 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
835 ExprResult &ComplexExpr,
839 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
840 if (SkipCast) return false;
841 if (IntTy->isIntegerType()) {
842 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
843 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
844 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
845 CK_FloatingRealToComplex);
847 assert(IntTy->isComplexIntegerType());
848 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
849 CK_IntegralComplexToFloatingComplex);
854 /// \brief Takes two complex float types and converts them to the same type.
855 /// Helper function of UsualArithmeticConversions()
857 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
858 ExprResult &RHS, QualType LHSType,
861 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
864 // _Complex float -> _Complex double
866 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
870 // _Complex float -> _Complex double
871 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
875 /// \brief Converts otherExpr to complex float and promotes complexExpr if
876 /// necessary. Helper function of UsualArithmeticConversions()
877 static QualType handleOtherComplexFloatConversion(Sema &S,
878 ExprResult &ComplexExpr,
879 ExprResult &OtherExpr,
882 bool ConvertComplexExpr,
883 bool ConvertOtherExpr) {
884 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
886 // If just the complexExpr is complex, the otherExpr needs to be converted,
887 // and the complexExpr might need to be promoted.
888 if (order > 0) { // complexExpr is wider
889 // float -> _Complex double
890 if (ConvertOtherExpr) {
891 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
892 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
893 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
894 CK_FloatingRealToComplex);
899 // otherTy is at least as wide. Find its corresponding complex type.
900 QualType result = (order == 0 ? ComplexTy :
901 S.Context.getComplexType(OtherTy));
903 // double -> _Complex double
904 if (ConvertOtherExpr)
905 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
906 CK_FloatingRealToComplex);
908 // _Complex float -> _Complex double
909 if (ConvertComplexExpr && order < 0)
910 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
911 CK_FloatingComplexCast);
916 /// \brief Handle arithmetic conversion with complex types. Helper function of
917 /// UsualArithmeticConversions()
918 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
919 ExprResult &RHS, QualType LHSType,
922 // if we have an integer operand, the result is the complex type.
923 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
926 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
927 /*skipCast*/IsCompAssign))
930 // This handles complex/complex, complex/float, or float/complex.
931 // When both operands are complex, the shorter operand is converted to the
932 // type of the longer, and that is the type of the result. This corresponds
933 // to what is done when combining two real floating-point operands.
934 // The fun begins when size promotion occur across type domains.
935 // From H&S 6.3.4: When one operand is complex and the other is a real
936 // floating-point type, the less precise type is converted, within it's
937 // real or complex domain, to the precision of the other type. For example,
938 // when combining a "long double" with a "double _Complex", the
939 // "double _Complex" is promoted to "long double _Complex".
941 bool LHSComplexFloat = LHSType->isComplexType();
942 bool RHSComplexFloat = RHSType->isComplexType();
944 // If both are complex, just cast to the more precise type.
945 if (LHSComplexFloat && RHSComplexFloat)
946 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
950 // If only one operand is complex, promote it if necessary and convert the
951 // other operand to complex.
953 return handleOtherComplexFloatConversion(
954 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
955 /*convertOtherExpr*/ true);
957 assert(RHSComplexFloat);
958 return handleOtherComplexFloatConversion(
959 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
960 /*convertOtherExpr*/ !IsCompAssign);
963 /// \brief Hande arithmetic conversion from integer to float. Helper function
964 /// of UsualArithmeticConversions()
965 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
967 QualType FloatTy, QualType IntTy,
968 bool ConvertFloat, bool ConvertInt) {
969 if (IntTy->isIntegerType()) {
971 // Convert intExpr to the lhs floating point type.
972 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
973 CK_IntegralToFloating);
977 // Convert both sides to the appropriate complex float.
978 assert(IntTy->isComplexIntegerType());
979 QualType result = S.Context.getComplexType(FloatTy);
981 // _Complex int -> _Complex float
983 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
984 CK_IntegralComplexToFloatingComplex);
986 // float -> _Complex float
988 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
989 CK_FloatingRealToComplex);
994 /// \brief Handle arithmethic conversion with floating point types. Helper
995 /// function of UsualArithmeticConversions()
996 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
997 ExprResult &RHS, QualType LHSType,
998 QualType RHSType, bool IsCompAssign) {
999 bool LHSFloat = LHSType->isRealFloatingType();
1000 bool RHSFloat = RHSType->isRealFloatingType();
1002 // If we have two real floating types, convert the smaller operand
1003 // to the bigger result.
1004 if (LHSFloat && RHSFloat) {
1005 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1007 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
1011 assert(order < 0 && "illegal float comparison");
1013 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
1018 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1019 /*convertFloat=*/!IsCompAssign,
1020 /*convertInt=*/ true);
1022 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1023 /*convertInt=*/ true,
1024 /*convertFloat=*/!IsCompAssign);
1027 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1030 /// These helper callbacks are placed in an anonymous namespace to
1031 /// permit their use as function template parameters.
1032 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1033 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1036 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1037 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1038 CK_IntegralComplexCast);
1042 /// \brief Handle integer arithmetic conversions. Helper function of
1043 /// UsualArithmeticConversions()
1044 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1045 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1046 ExprResult &RHS, QualType LHSType,
1047 QualType RHSType, bool IsCompAssign) {
1048 // The rules for this case are in C99 6.3.1.8
1049 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1050 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1051 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1052 if (LHSSigned == RHSSigned) {
1053 // Same signedness; use the higher-ranked type
1055 RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1057 } else if (!IsCompAssign)
1058 LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1060 } else if (order != (LHSSigned ? 1 : -1)) {
1061 // The unsigned type has greater than or equal rank to the
1062 // signed type, so use the unsigned type
1064 RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1066 } else if (!IsCompAssign)
1067 LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1069 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1070 // The two types are different widths; if we are here, that
1071 // means the signed type is larger than the unsigned type, so
1072 // use the signed type.
1074 RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1076 } else if (!IsCompAssign)
1077 LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1080 // The signed type is higher-ranked than the unsigned type,
1081 // but isn't actually any bigger (like unsigned int and long
1082 // on most 32-bit systems). Use the unsigned type corresponding
1083 // to the signed type.
1085 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1086 RHS = (*doRHSCast)(S, RHS.take(), result);
1088 LHS = (*doLHSCast)(S, LHS.take(), result);
1093 /// \brief Handle conversions with GCC complex int extension. Helper function
1094 /// of UsualArithmeticConversions()
1095 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1096 ExprResult &RHS, QualType LHSType,
1098 bool IsCompAssign) {
1099 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1100 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1102 if (LHSComplexInt && RHSComplexInt) {
1103 QualType LHSEltType = LHSComplexInt->getElementType();
1104 QualType RHSEltType = RHSComplexInt->getElementType();
1105 QualType ScalarType =
1106 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1107 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1109 return S.Context.getComplexType(ScalarType);
1112 if (LHSComplexInt) {
1113 QualType LHSEltType = LHSComplexInt->getElementType();
1114 QualType ScalarType =
1115 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1116 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1117 QualType ComplexType = S.Context.getComplexType(ScalarType);
1118 RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1119 CK_IntegralRealToComplex);
1124 assert(RHSComplexInt);
1126 QualType RHSEltType = RHSComplexInt->getElementType();
1127 QualType ScalarType =
1128 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1129 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1130 QualType ComplexType = S.Context.getComplexType(ScalarType);
1133 LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1134 CK_IntegralRealToComplex);
1138 /// UsualArithmeticConversions - Performs various conversions that are common to
1139 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1140 /// routine returns the first non-arithmetic type found. The client is
1141 /// responsible for emitting appropriate error diagnostics.
1142 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1143 bool IsCompAssign) {
1144 if (!IsCompAssign) {
1145 LHS = UsualUnaryConversions(LHS.take());
1146 if (LHS.isInvalid())
1150 RHS = UsualUnaryConversions(RHS.take());
1151 if (RHS.isInvalid())
1154 // For conversion purposes, we ignore any qualifiers.
1155 // For example, "const float" and "float" are equivalent.
1157 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1159 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1161 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1162 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1163 LHSType = AtomicLHS->getValueType();
1165 // If both types are identical, no conversion is needed.
1166 if (LHSType == RHSType)
1169 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1170 // The caller can deal with this (e.g. pointer + int).
1171 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1174 // Apply unary and bitfield promotions to the LHS's type.
1175 QualType LHSUnpromotedType = LHSType;
1176 if (LHSType->isPromotableIntegerType())
1177 LHSType = Context.getPromotedIntegerType(LHSType);
1178 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1179 if (!LHSBitfieldPromoteTy.isNull())
1180 LHSType = LHSBitfieldPromoteTy;
1181 if (LHSType != LHSUnpromotedType && !IsCompAssign)
1182 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1184 // If both types are identical, no conversion is needed.
1185 if (LHSType == RHSType)
1188 // At this point, we have two different arithmetic types.
1190 // Handle complex types first (C99 6.3.1.8p1).
1191 if (LHSType->isComplexType() || RHSType->isComplexType())
1192 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1195 // Now handle "real" floating types (i.e. float, double, long double).
1196 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1197 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1200 // Handle GCC complex int extension.
1201 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1202 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1205 // Finally, we have two differing integer types.
1206 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1207 (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1211 //===----------------------------------------------------------------------===//
1212 // Semantic Analysis for various Expression Types
1213 //===----------------------------------------------------------------------===//
1217 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1218 SourceLocation DefaultLoc,
1219 SourceLocation RParenLoc,
1220 Expr *ControllingExpr,
1221 MultiTypeArg ArgTypes,
1222 MultiExprArg ArgExprs) {
1223 unsigned NumAssocs = ArgTypes.size();
1224 assert(NumAssocs == ArgExprs.size());
1226 ParsedType *ParsedTypes = ArgTypes.data();
1227 Expr **Exprs = ArgExprs.data();
1229 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1230 for (unsigned i = 0; i < NumAssocs; ++i) {
1232 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1237 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1238 ControllingExpr, Types, Exprs,
1245 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1246 SourceLocation DefaultLoc,
1247 SourceLocation RParenLoc,
1248 Expr *ControllingExpr,
1249 TypeSourceInfo **Types,
1251 unsigned NumAssocs) {
1252 if (ControllingExpr->getType()->isPlaceholderType()) {
1253 ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1254 if (result.isInvalid()) return ExprError();
1255 ControllingExpr = result.take();
1258 bool TypeErrorFound = false,
1259 IsResultDependent = ControllingExpr->isTypeDependent(),
1260 ContainsUnexpandedParameterPack
1261 = ControllingExpr->containsUnexpandedParameterPack();
1263 for (unsigned i = 0; i < NumAssocs; ++i) {
1264 if (Exprs[i]->containsUnexpandedParameterPack())
1265 ContainsUnexpandedParameterPack = true;
1268 if (Types[i]->getType()->containsUnexpandedParameterPack())
1269 ContainsUnexpandedParameterPack = true;
1271 if (Types[i]->getType()->isDependentType()) {
1272 IsResultDependent = true;
1274 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1275 // complete object type other than a variably modified type."
1277 if (Types[i]->getType()->isIncompleteType())
1278 D = diag::err_assoc_type_incomplete;
1279 else if (!Types[i]->getType()->isObjectType())
1280 D = diag::err_assoc_type_nonobject;
1281 else if (Types[i]->getType()->isVariablyModifiedType())
1282 D = diag::err_assoc_type_variably_modified;
1285 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1286 << Types[i]->getTypeLoc().getSourceRange()
1287 << Types[i]->getType();
1288 TypeErrorFound = true;
1291 // C11 6.5.1.1p2 "No two generic associations in the same generic
1292 // selection shall specify compatible types."
1293 for (unsigned j = i+1; j < NumAssocs; ++j)
1294 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1295 Context.typesAreCompatible(Types[i]->getType(),
1296 Types[j]->getType())) {
1297 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1298 diag::err_assoc_compatible_types)
1299 << Types[j]->getTypeLoc().getSourceRange()
1300 << Types[j]->getType()
1301 << Types[i]->getType();
1302 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1303 diag::note_compat_assoc)
1304 << Types[i]->getTypeLoc().getSourceRange()
1305 << Types[i]->getType();
1306 TypeErrorFound = true;
1314 // If we determined that the generic selection is result-dependent, don't
1315 // try to compute the result expression.
1316 if (IsResultDependent)
1317 return Owned(new (Context) GenericSelectionExpr(
1318 Context, KeyLoc, ControllingExpr,
1319 llvm::makeArrayRef(Types, NumAssocs),
1320 llvm::makeArrayRef(Exprs, NumAssocs),
1321 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1323 SmallVector<unsigned, 1> CompatIndices;
1324 unsigned DefaultIndex = -1U;
1325 for (unsigned i = 0; i < NumAssocs; ++i) {
1328 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1329 Types[i]->getType()))
1330 CompatIndices.push_back(i);
1333 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1334 // type compatible with at most one of the types named in its generic
1335 // association list."
1336 if (CompatIndices.size() > 1) {
1337 // We strip parens here because the controlling expression is typically
1338 // parenthesized in macro definitions.
1339 ControllingExpr = ControllingExpr->IgnoreParens();
1340 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1341 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1342 << (unsigned) CompatIndices.size();
1343 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
1344 E = CompatIndices.end(); I != E; ++I) {
1345 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1346 diag::note_compat_assoc)
1347 << Types[*I]->getTypeLoc().getSourceRange()
1348 << Types[*I]->getType();
1353 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1354 // its controlling expression shall have type compatible with exactly one of
1355 // the types named in its generic association list."
1356 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1357 // We strip parens here because the controlling expression is typically
1358 // parenthesized in macro definitions.
1359 ControllingExpr = ControllingExpr->IgnoreParens();
1360 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1361 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1365 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1366 // type name that is compatible with the type of the controlling expression,
1367 // then the result expression of the generic selection is the expression
1368 // in that generic association. Otherwise, the result expression of the
1369 // generic selection is the expression in the default generic association."
1370 unsigned ResultIndex =
1371 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1373 return Owned(new (Context) GenericSelectionExpr(
1374 Context, KeyLoc, ControllingExpr,
1375 llvm::makeArrayRef(Types, NumAssocs),
1376 llvm::makeArrayRef(Exprs, NumAssocs),
1377 DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1381 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1382 /// location of the token and the offset of the ud-suffix within it.
1383 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1385 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1389 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1390 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1391 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1392 IdentifierInfo *UDSuffix,
1393 SourceLocation UDSuffixLoc,
1394 ArrayRef<Expr*> Args,
1395 SourceLocation LitEndLoc) {
1396 assert(Args.size() <= 2 && "too many arguments for literal operator");
1399 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1400 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1401 if (ArgTy[ArgIdx]->isArrayType())
1402 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1405 DeclarationName OpName =
1406 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1407 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1408 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1410 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1411 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1412 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1415 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1418 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1419 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1420 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1421 /// multiple tokens. However, the common case is that StringToks points to one
1425 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1427 assert(NumStringToks && "Must have at least one string!");
1429 StringLiteralParser Literal(StringToks, NumStringToks, PP);
1430 if (Literal.hadError)
1433 SmallVector<SourceLocation, 4> StringTokLocs;
1434 for (unsigned i = 0; i != NumStringToks; ++i)
1435 StringTokLocs.push_back(StringToks[i].getLocation());
1437 QualType StrTy = Context.CharTy;
1438 if (Literal.isWide())
1439 StrTy = Context.getWCharType();
1440 else if (Literal.isUTF16())
1441 StrTy = Context.Char16Ty;
1442 else if (Literal.isUTF32())
1443 StrTy = Context.Char32Ty;
1444 else if (Literal.isPascal())
1445 StrTy = Context.UnsignedCharTy;
1447 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1448 if (Literal.isWide())
1449 Kind = StringLiteral::Wide;
1450 else if (Literal.isUTF8())
1451 Kind = StringLiteral::UTF8;
1452 else if (Literal.isUTF16())
1453 Kind = StringLiteral::UTF16;
1454 else if (Literal.isUTF32())
1455 Kind = StringLiteral::UTF32;
1457 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1458 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1461 // Get an array type for the string, according to C99 6.4.5. This includes
1462 // the nul terminator character as well as the string length for pascal
1464 StrTy = Context.getConstantArrayType(StrTy,
1465 llvm::APInt(32, Literal.GetNumStringChars()+1),
1466 ArrayType::Normal, 0);
1468 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1469 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1470 Kind, Literal.Pascal, StrTy,
1472 StringTokLocs.size());
1473 if (Literal.getUDSuffix().empty())
1476 // We're building a user-defined literal.
1477 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1478 SourceLocation UDSuffixLoc =
1479 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1480 Literal.getUDSuffixOffset());
1482 // Make sure we're allowed user-defined literals here.
1484 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1486 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1487 // operator "" X (str, len)
1488 QualType SizeType = Context.getSizeType();
1489 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1490 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1492 Expr *Args[] = { Lit, LenArg };
1493 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1494 Args, StringTokLocs.back());
1498 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1500 const CXXScopeSpec *SS) {
1501 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1502 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1505 /// BuildDeclRefExpr - Build an expression that references a
1506 /// declaration that does not require a closure capture.
1508 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1509 const DeclarationNameInfo &NameInfo,
1510 const CXXScopeSpec *SS, NamedDecl *FoundD) {
1511 if (getLangOpts().CUDA)
1512 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1513 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1514 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1515 CalleeTarget = IdentifyCUDATarget(Callee);
1516 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1517 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1518 << CalleeTarget << D->getIdentifier() << CallerTarget;
1519 Diag(D->getLocation(), diag::note_previous_decl)
1520 << D->getIdentifier();
1525 bool refersToEnclosingScope =
1526 (CurContext != D->getDeclContext() &&
1527 D->getDeclContext()->isFunctionOrMethod());
1529 DeclRefExpr *E = DeclRefExpr::Create(Context,
1530 SS ? SS->getWithLocInContext(Context)
1531 : NestedNameSpecifierLoc(),
1533 D, refersToEnclosingScope,
1534 NameInfo, Ty, VK, FoundD);
1536 MarkDeclRefReferenced(E);
1538 if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1539 Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1540 DiagnosticsEngine::Level Level =
1541 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1543 if (Level != DiagnosticsEngine::Ignored)
1544 getCurFunction()->recordUseOfWeak(E);
1547 // Just in case we're building an illegal pointer-to-member.
1548 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1549 if (FD && FD->isBitField())
1550 E->setObjectKind(OK_BitField);
1555 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1556 /// possibly a list of template arguments.
1558 /// If this produces template arguments, it is permitted to call
1559 /// DecomposeTemplateName.
1561 /// This actually loses a lot of source location information for
1562 /// non-standard name kinds; we should consider preserving that in
1565 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1566 TemplateArgumentListInfo &Buffer,
1567 DeclarationNameInfo &NameInfo,
1568 const TemplateArgumentListInfo *&TemplateArgs) {
1569 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1570 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1571 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1573 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1574 Id.TemplateId->NumArgs);
1575 translateTemplateArguments(TemplateArgsPtr, Buffer);
1577 TemplateName TName = Id.TemplateId->Template.get();
1578 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1579 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1580 TemplateArgs = &Buffer;
1582 NameInfo = GetNameFromUnqualifiedId(Id);
1587 /// Diagnose an empty lookup.
1589 /// \return false if new lookup candidates were found
1590 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1591 CorrectionCandidateCallback &CCC,
1592 TemplateArgumentListInfo *ExplicitTemplateArgs,
1593 llvm::ArrayRef<Expr *> Args) {
1594 DeclarationName Name = R.getLookupName();
1596 unsigned diagnostic = diag::err_undeclared_var_use;
1597 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1598 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1599 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1600 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1601 diagnostic = diag::err_undeclared_use;
1602 diagnostic_suggest = diag::err_undeclared_use_suggest;
1605 // If the original lookup was an unqualified lookup, fake an
1606 // unqualified lookup. This is useful when (for example) the
1607 // original lookup would not have found something because it was a
1609 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1612 if (isa<CXXRecordDecl>(DC)) {
1613 LookupQualifiedName(R, DC);
1616 // Don't give errors about ambiguities in this lookup.
1617 R.suppressDiagnostics();
1619 // During a default argument instantiation the CurContext points
1620 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1621 // function parameter list, hence add an explicit check.
1622 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1623 ActiveTemplateInstantiations.back().Kind ==
1624 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1625 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1626 bool isInstance = CurMethod &&
1627 CurMethod->isInstance() &&
1628 DC == CurMethod->getParent() && !isDefaultArgument;
1631 // Give a code modification hint to insert 'this->'.
1632 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1633 // Actually quite difficult!
1634 if (getLangOpts().MicrosoftMode)
1635 diagnostic = diag::warn_found_via_dependent_bases_lookup;
1637 Diag(R.getNameLoc(), diagnostic) << Name
1638 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1639 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1640 CallsUndergoingInstantiation.back()->getCallee());
1642 CXXMethodDecl *DepMethod;
1643 if (CurMethod->isDependentContext())
1644 DepMethod = CurMethod;
1645 else if (CurMethod->getTemplatedKind() ==
1646 FunctionDecl::TK_FunctionTemplateSpecialization)
1647 DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1648 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1650 DepMethod = cast<CXXMethodDecl>(
1651 CurMethod->getInstantiatedFromMemberFunction());
1652 assert(DepMethod && "No template pattern found");
1654 QualType DepThisType = DepMethod->getThisType(Context);
1655 CheckCXXThisCapture(R.getNameLoc());
1656 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1657 R.getNameLoc(), DepThisType, false);
1658 TemplateArgumentListInfo TList;
1659 if (ULE->hasExplicitTemplateArgs())
1660 ULE->copyTemplateArgumentsInto(TList);
1663 SS.Adopt(ULE->getQualifierLoc());
1664 CXXDependentScopeMemberExpr *DepExpr =
1665 CXXDependentScopeMemberExpr::Create(
1666 Context, DepThis, DepThisType, true, SourceLocation(),
1667 SS.getWithLocInContext(Context),
1668 ULE->getTemplateKeywordLoc(), 0,
1669 R.getLookupNameInfo(),
1670 ULE->hasExplicitTemplateArgs() ? &TList : 0);
1671 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1673 Diag(R.getNameLoc(), diagnostic) << Name;
1676 // Do we really want to note all of these?
1677 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1678 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1680 // Return true if we are inside a default argument instantiation
1681 // and the found name refers to an instance member function, otherwise
1682 // the function calling DiagnoseEmptyLookup will try to create an
1683 // implicit member call and this is wrong for default argument.
1684 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1685 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1689 // Tell the callee to try to recover.
1696 // In Microsoft mode, if we are performing lookup from within a friend
1697 // function definition declared at class scope then we must set
1698 // DC to the lexical parent to be able to search into the parent
1700 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1701 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1702 DC->getLexicalParent()->isRecord())
1703 DC = DC->getLexicalParent();
1705 DC = DC->getParent();
1708 // We didn't find anything, so try to correct for a typo.
1709 TypoCorrection Corrected;
1710 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1712 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1713 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
1714 R.setLookupName(Corrected.getCorrection());
1716 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1717 if (Corrected.isOverloaded()) {
1718 OverloadCandidateSet OCS(R.getNameLoc());
1719 OverloadCandidateSet::iterator Best;
1720 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1721 CDEnd = Corrected.end();
1722 CD != CDEnd; ++CD) {
1723 if (FunctionTemplateDecl *FTD =
1724 dyn_cast<FunctionTemplateDecl>(*CD))
1725 AddTemplateOverloadCandidate(
1726 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1728 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1729 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1730 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1733 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1735 ND = Best->Function;
1742 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1744 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1745 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1747 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1748 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1750 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
1753 unsigned diag = isa<ImplicitParamDecl>(ND)
1754 ? diag::note_implicit_param_decl
1755 : diag::note_previous_decl;
1757 Diag(ND->getLocation(), diag)
1758 << CorrectedQuotedStr;
1760 // Tell the callee to try to recover.
1764 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1765 // FIXME: If we ended up with a typo for a type name or
1766 // Objective-C class name, we're in trouble because the parser
1767 // is in the wrong place to recover. Suggest the typo
1768 // correction, but don't make it a fix-it since we're not going
1769 // to recover well anyway.
1771 Diag(R.getNameLoc(), diagnostic_suggest)
1772 << Name << CorrectedQuotedStr;
1774 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1775 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1778 // Don't try to recover; it won't work.
1782 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1783 // because we aren't able to recover.
1785 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1787 Diag(R.getNameLoc(), diag::err_no_member_suggest)
1788 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1795 // Emit a special diagnostic for failed member lookups.
1796 // FIXME: computing the declaration context might fail here (?)
1797 if (!SS.isEmpty()) {
1798 Diag(R.getNameLoc(), diag::err_no_member)
1799 << Name << computeDeclContext(SS, false)
1804 // Give up, we can't recover.
1805 Diag(R.getNameLoc(), diagnostic) << Name;
1809 ExprResult Sema::ActOnIdExpression(Scope *S,
1811 SourceLocation TemplateKWLoc,
1813 bool HasTrailingLParen,
1814 bool IsAddressOfOperand,
1815 CorrectionCandidateCallback *CCC) {
1816 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1817 "cannot be direct & operand and have a trailing lparen");
1822 TemplateArgumentListInfo TemplateArgsBuffer;
1824 // Decompose the UnqualifiedId into the following data.
1825 DeclarationNameInfo NameInfo;
1826 const TemplateArgumentListInfo *TemplateArgs;
1827 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1829 DeclarationName Name = NameInfo.getName();
1830 IdentifierInfo *II = Name.getAsIdentifierInfo();
1831 SourceLocation NameLoc = NameInfo.getLoc();
1833 // C++ [temp.dep.expr]p3:
1834 // An id-expression is type-dependent if it contains:
1835 // -- an identifier that was declared with a dependent type,
1836 // (note: handled after lookup)
1837 // -- a template-id that is dependent,
1838 // (note: handled in BuildTemplateIdExpr)
1839 // -- a conversion-function-id that specifies a dependent type,
1840 // -- a nested-name-specifier that contains a class-name that
1841 // names a dependent type.
1842 // Determine whether this is a member of an unknown specialization;
1843 // we need to handle these differently.
1844 bool DependentID = false;
1845 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1846 Name.getCXXNameType()->isDependentType()) {
1848 } else if (SS.isSet()) {
1849 if (DeclContext *DC = computeDeclContext(SS, false)) {
1850 if (RequireCompleteDeclContext(SS, DC))
1858 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1859 IsAddressOfOperand, TemplateArgs);
1861 // Perform the required lookup.
1862 LookupResult R(*this, NameInfo,
1863 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1864 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1866 // Lookup the template name again to correctly establish the context in
1867 // which it was found. This is really unfortunate as we already did the
1868 // lookup to determine that it was a template name in the first place. If
1869 // this becomes a performance hit, we can work harder to preserve those
1870 // results until we get here but it's likely not worth it.
1871 bool MemberOfUnknownSpecialization;
1872 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1873 MemberOfUnknownSpecialization);
1875 if (MemberOfUnknownSpecialization ||
1876 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1877 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1878 IsAddressOfOperand, TemplateArgs);
1880 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1881 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1883 // If the result might be in a dependent base class, this is a dependent
1885 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1886 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1887 IsAddressOfOperand, TemplateArgs);
1889 // If this reference is in an Objective-C method, then we need to do
1890 // some special Objective-C lookup, too.
1891 if (IvarLookupFollowUp) {
1892 ExprResult E(LookupInObjCMethod(R, S, II, true));
1896 if (Expr *Ex = E.takeAs<Expr>())
1901 if (R.isAmbiguous())
1904 // Determine whether this name might be a candidate for
1905 // argument-dependent lookup.
1906 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1908 if (R.empty() && !ADL) {
1909 // Otherwise, this could be an implicitly declared function reference (legal
1910 // in C90, extension in C99, forbidden in C++).
1911 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
1912 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1913 if (D) R.addDecl(D);
1916 // If this name wasn't predeclared and if this is not a function
1917 // call, diagnose the problem.
1920 // In Microsoft mode, if we are inside a template class member function
1921 // and we can't resolve an identifier then assume the identifier is type
1922 // dependent. The goal is to postpone name lookup to instantiation time
1923 // to be able to search into type dependent base classes.
1924 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
1925 isa<CXXMethodDecl>(CurContext))
1926 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1927 IsAddressOfOperand, TemplateArgs);
1929 CorrectionCandidateCallback DefaultValidator;
1930 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
1933 assert(!R.empty() &&
1934 "DiagnoseEmptyLookup returned false but added no results");
1936 // If we found an Objective-C instance variable, let
1937 // LookupInObjCMethod build the appropriate expression to
1938 // reference the ivar.
1939 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1941 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1942 // In a hopelessly buggy code, Objective-C instance variable
1943 // lookup fails and no expression will be built to reference it.
1944 if (!E.isInvalid() && !E.get())
1951 // This is guaranteed from this point on.
1952 assert(!R.empty() || ADL);
1954 // Check whether this might be a C++ implicit instance member access.
1955 // C++ [class.mfct.non-static]p3:
1956 // When an id-expression that is not part of a class member access
1957 // syntax and not used to form a pointer to member is used in the
1958 // body of a non-static member function of class X, if name lookup
1959 // resolves the name in the id-expression to a non-static non-type
1960 // member of some class C, the id-expression is transformed into a
1961 // class member access expression using (*this) as the
1962 // postfix-expression to the left of the . operator.
1964 // But we don't actually need to do this for '&' operands if R
1965 // resolved to a function or overloaded function set, because the
1966 // expression is ill-formed if it actually works out to be a
1967 // non-static member function:
1969 // C++ [expr.ref]p4:
1970 // Otherwise, if E1.E2 refers to a non-static member function. . .
1971 // [t]he expression can be used only as the left-hand operand of a
1972 // member function call.
1974 // There are other safeguards against such uses, but it's important
1975 // to get this right here so that we don't end up making a
1976 // spuriously dependent expression if we're inside a dependent
1978 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1979 bool MightBeImplicitMember;
1980 if (!IsAddressOfOperand)
1981 MightBeImplicitMember = true;
1982 else if (!SS.isEmpty())
1983 MightBeImplicitMember = false;
1984 else if (R.isOverloadedResult())
1985 MightBeImplicitMember = false;
1986 else if (R.isUnresolvableResult())
1987 MightBeImplicitMember = true;
1989 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1990 isa<IndirectFieldDecl>(R.getFoundDecl());
1992 if (MightBeImplicitMember)
1993 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1997 if (TemplateArgs || TemplateKWLoc.isValid())
1998 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2000 return BuildDeclarationNameExpr(SS, R, ADL);
2003 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2004 /// declaration name, generally during template instantiation.
2005 /// There's a large number of things which don't need to be done along
2008 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2009 const DeclarationNameInfo &NameInfo,
2010 bool IsAddressOfOperand) {
2011 DeclContext *DC = computeDeclContext(SS, false);
2013 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2014 NameInfo, /*TemplateArgs=*/0);
2016 if (RequireCompleteDeclContext(SS, DC))
2019 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2020 LookupQualifiedName(R, DC);
2022 if (R.isAmbiguous())
2025 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2026 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2027 NameInfo, /*TemplateArgs=*/0);
2030 Diag(NameInfo.getLoc(), diag::err_no_member)
2031 << NameInfo.getName() << DC << SS.getRange();
2035 // Defend against this resolving to an implicit member access. We usually
2036 // won't get here if this might be a legitimate a class member (we end up in
2037 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2038 // a pointer-to-member or in an unevaluated context in C++11.
2039 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2040 return BuildPossibleImplicitMemberExpr(SS,
2041 /*TemplateKWLoc=*/SourceLocation(),
2042 R, /*TemplateArgs=*/0);
2044 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2047 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2048 /// detected that we're currently inside an ObjC method. Perform some
2049 /// additional lookup.
2051 /// Ideally, most of this would be done by lookup, but there's
2052 /// actually quite a lot of extra work involved.
2054 /// Returns a null sentinel to indicate trivial success.
2056 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2057 IdentifierInfo *II, bool AllowBuiltinCreation) {
2058 SourceLocation Loc = Lookup.getNameLoc();
2059 ObjCMethodDecl *CurMethod = getCurMethodDecl();
2061 // Check for error condition which is already reported.
2065 // There are two cases to handle here. 1) scoped lookup could have failed,
2066 // in which case we should look for an ivar. 2) scoped lookup could have
2067 // found a decl, but that decl is outside the current instance method (i.e.
2068 // a global variable). In these two cases, we do a lookup for an ivar with
2069 // this name, if the lookup sucedes, we replace it our current decl.
2071 // If we're in a class method, we don't normally want to look for
2072 // ivars. But if we don't find anything else, and there's an
2073 // ivar, that's an error.
2074 bool IsClassMethod = CurMethod->isClassMethod();
2078 LookForIvars = true;
2079 else if (IsClassMethod)
2080 LookForIvars = false;
2082 LookForIvars = (Lookup.isSingleResult() &&
2083 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2084 ObjCInterfaceDecl *IFace = 0;
2086 IFace = CurMethod->getClassInterface();
2087 ObjCInterfaceDecl *ClassDeclared;
2088 ObjCIvarDecl *IV = 0;
2089 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2090 // Diagnose using an ivar in a class method.
2092 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2093 << IV->getDeclName());
2095 // If we're referencing an invalid decl, just return this as a silent
2096 // error node. The error diagnostic was already emitted on the decl.
2097 if (IV->isInvalidDecl())
2100 // Check if referencing a field with __attribute__((deprecated)).
2101 if (DiagnoseUseOfDecl(IV, Loc))
2104 // Diagnose the use of an ivar outside of the declaring class.
2105 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2106 !declaresSameEntity(ClassDeclared, IFace) &&
2107 !getLangOpts().DebuggerSupport)
2108 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2110 // FIXME: This should use a new expr for a direct reference, don't
2111 // turn this into Self->ivar, just return a BareIVarExpr or something.
2112 IdentifierInfo &II = Context.Idents.get("self");
2113 UnqualifiedId SelfName;
2114 SelfName.setIdentifier(&II, SourceLocation());
2115 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2116 CXXScopeSpec SelfScopeSpec;
2117 SourceLocation TemplateKWLoc;
2118 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2119 SelfName, false, false);
2120 if (SelfExpr.isInvalid())
2123 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2124 if (SelfExpr.isInvalid())
2127 MarkAnyDeclReferenced(Loc, IV, true);
2129 ObjCMethodFamily MF = CurMethod->getMethodFamily();
2130 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2131 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2132 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2134 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2135 Loc, IV->getLocation(),
2139 if (getLangOpts().ObjCAutoRefCount) {
2140 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2141 DiagnosticsEngine::Level Level =
2142 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2143 if (Level != DiagnosticsEngine::Ignored)
2144 getCurFunction()->recordUseOfWeak(Result);
2146 if (CurContext->isClosure())
2147 Diag(Loc, diag::warn_implicitly_retains_self)
2148 << FixItHint::CreateInsertion(Loc, "self->");
2151 return Owned(Result);
2153 } else if (CurMethod->isInstanceMethod()) {
2154 // We should warn if a local variable hides an ivar.
2155 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2156 ObjCInterfaceDecl *ClassDeclared;
2157 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2158 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2159 declaresSameEntity(IFace, ClassDeclared))
2160 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2163 } else if (Lookup.isSingleResult() &&
2164 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2165 // If accessing a stand-alone ivar in a class method, this is an error.
2166 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2167 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2168 << IV->getDeclName());
2171 if (Lookup.empty() && II && AllowBuiltinCreation) {
2172 // FIXME. Consolidate this with similar code in LookupName.
2173 if (unsigned BuiltinID = II->getBuiltinID()) {
2174 if (!(getLangOpts().CPlusPlus &&
2175 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2176 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2177 S, Lookup.isForRedeclaration(),
2178 Lookup.getNameLoc());
2179 if (D) Lookup.addDecl(D);
2183 // Sentinel value saying that we didn't do anything special.
2184 return Owned((Expr*) 0);
2187 /// \brief Cast a base object to a member's actual type.
2189 /// Logically this happens in three phases:
2191 /// * First we cast from the base type to the naming class.
2192 /// The naming class is the class into which we were looking
2193 /// when we found the member; it's the qualifier type if a
2194 /// qualifier was provided, and otherwise it's the base type.
2196 /// * Next we cast from the naming class to the declaring class.
2197 /// If the member we found was brought into a class's scope by
2198 /// a using declaration, this is that class; otherwise it's
2199 /// the class declaring the member.
2201 /// * Finally we cast from the declaring class to the "true"
2202 /// declaring class of the member. This conversion does not
2203 /// obey access control.
2205 Sema::PerformObjectMemberConversion(Expr *From,
2206 NestedNameSpecifier *Qualifier,
2207 NamedDecl *FoundDecl,
2208 NamedDecl *Member) {
2209 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2213 QualType DestRecordType;
2215 QualType FromRecordType;
2216 QualType FromType = From->getType();
2217 bool PointerConversions = false;
2218 if (isa<FieldDecl>(Member)) {
2219 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2221 if (FromType->getAs<PointerType>()) {
2222 DestType = Context.getPointerType(DestRecordType);
2223 FromRecordType = FromType->getPointeeType();
2224 PointerConversions = true;
2226 DestType = DestRecordType;
2227 FromRecordType = FromType;
2229 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2230 if (Method->isStatic())
2233 DestType = Method->getThisType(Context);
2234 DestRecordType = DestType->getPointeeType();
2236 if (FromType->getAs<PointerType>()) {
2237 FromRecordType = FromType->getPointeeType();
2238 PointerConversions = true;
2240 FromRecordType = FromType;
2241 DestType = DestRecordType;
2244 // No conversion necessary.
2248 if (DestType->isDependentType() || FromType->isDependentType())
2251 // If the unqualified types are the same, no conversion is necessary.
2252 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2255 SourceRange FromRange = From->getSourceRange();
2256 SourceLocation FromLoc = FromRange.getBegin();
2258 ExprValueKind VK = From->getValueKind();
2260 // C++ [class.member.lookup]p8:
2261 // [...] Ambiguities can often be resolved by qualifying a name with its
2264 // If the member was a qualified name and the qualified referred to a
2265 // specific base subobject type, we'll cast to that intermediate type
2266 // first and then to the object in which the member is declared. That allows
2267 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2269 // class Base { public: int x; };
2270 // class Derived1 : public Base { };
2271 // class Derived2 : public Base { };
2272 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2274 // void VeryDerived::f() {
2275 // x = 17; // error: ambiguous base subobjects
2276 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2279 QualType QType = QualType(Qualifier->getAsType(), 0);
2280 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2281 assert(QType->isRecordType() && "lookup done with non-record type");
2283 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2285 // In C++98, the qualifier type doesn't actually have to be a base
2286 // type of the object type, in which case we just ignore it.
2287 // Otherwise build the appropriate casts.
2288 if (IsDerivedFrom(FromRecordType, QRecordType)) {
2289 CXXCastPath BasePath;
2290 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2291 FromLoc, FromRange, &BasePath))
2294 if (PointerConversions)
2295 QType = Context.getPointerType(QType);
2296 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2297 VK, &BasePath).take();
2300 FromRecordType = QRecordType;
2302 // If the qualifier type was the same as the destination type,
2304 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2309 bool IgnoreAccess = false;
2311 // If we actually found the member through a using declaration, cast
2312 // down to the using declaration's type.
2314 // Pointer equality is fine here because only one declaration of a
2315 // class ever has member declarations.
2316 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2317 assert(isa<UsingShadowDecl>(FoundDecl));
2318 QualType URecordType = Context.getTypeDeclType(
2319 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2321 // We only need to do this if the naming-class to declaring-class
2322 // conversion is non-trivial.
2323 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2324 assert(IsDerivedFrom(FromRecordType, URecordType));
2325 CXXCastPath BasePath;
2326 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2327 FromLoc, FromRange, &BasePath))
2330 QualType UType = URecordType;
2331 if (PointerConversions)
2332 UType = Context.getPointerType(UType);
2333 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2334 VK, &BasePath).take();
2336 FromRecordType = URecordType;
2339 // We don't do access control for the conversion from the
2340 // declaring class to the true declaring class.
2341 IgnoreAccess = true;
2344 CXXCastPath BasePath;
2345 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2346 FromLoc, FromRange, &BasePath,
2350 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2354 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2355 const LookupResult &R,
2356 bool HasTrailingLParen) {
2357 // Only when used directly as the postfix-expression of a call.
2358 if (!HasTrailingLParen)
2361 // Never if a scope specifier was provided.
2365 // Only in C++ or ObjC++.
2366 if (!getLangOpts().CPlusPlus)
2369 // Turn off ADL when we find certain kinds of declarations during
2371 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2374 // C++0x [basic.lookup.argdep]p3:
2375 // -- a declaration of a class member
2376 // Since using decls preserve this property, we check this on the
2378 if (D->isCXXClassMember())
2381 // C++0x [basic.lookup.argdep]p3:
2382 // -- a block-scope function declaration that is not a
2383 // using-declaration
2384 // NOTE: we also trigger this for function templates (in fact, we
2385 // don't check the decl type at all, since all other decl types
2386 // turn off ADL anyway).
2387 if (isa<UsingShadowDecl>(D))
2388 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2389 else if (D->getDeclContext()->isFunctionOrMethod())
2392 // C++0x [basic.lookup.argdep]p3:
2393 // -- a declaration that is neither a function or a function
2395 // And also for builtin functions.
2396 if (isa<FunctionDecl>(D)) {
2397 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2399 // But also builtin functions.
2400 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2402 } else if (!isa<FunctionTemplateDecl>(D))
2410 /// Diagnoses obvious problems with the use of the given declaration
2411 /// as an expression. This is only actually called for lookups that
2412 /// were not overloaded, and it doesn't promise that the declaration
2413 /// will in fact be used.
2414 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2415 if (isa<TypedefNameDecl>(D)) {
2416 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2420 if (isa<ObjCInterfaceDecl>(D)) {
2421 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2425 if (isa<NamespaceDecl>(D)) {
2426 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2434 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2437 // If this is a single, fully-resolved result and we don't need ADL,
2438 // just build an ordinary singleton decl ref.
2439 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2440 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2441 R.getRepresentativeDecl());
2443 // We only need to check the declaration if there's exactly one
2444 // result, because in the overloaded case the results can only be
2445 // functions and function templates.
2446 if (R.isSingleResult() &&
2447 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2450 // Otherwise, just build an unresolved lookup expression. Suppress
2451 // any lookup-related diagnostics; we'll hash these out later, when
2452 // we've picked a target.
2453 R.suppressDiagnostics();
2455 UnresolvedLookupExpr *ULE
2456 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2457 SS.getWithLocInContext(Context),
2458 R.getLookupNameInfo(),
2459 NeedsADL, R.isOverloadedResult(),
2460 R.begin(), R.end());
2465 /// \brief Complete semantic analysis for a reference to the given declaration.
2467 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2468 const DeclarationNameInfo &NameInfo,
2469 NamedDecl *D, NamedDecl *FoundD) {
2470 assert(D && "Cannot refer to a NULL declaration");
2471 assert(!isa<FunctionTemplateDecl>(D) &&
2472 "Cannot refer unambiguously to a function template");
2474 SourceLocation Loc = NameInfo.getLoc();
2475 if (CheckDeclInExpr(*this, Loc, D))
2478 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2479 // Specifically diagnose references to class templates that are missing
2480 // a template argument list.
2481 Diag(Loc, diag::err_template_decl_ref)
2482 << Template << SS.getRange();
2483 Diag(Template->getLocation(), diag::note_template_decl_here);
2487 // Make sure that we're referring to a value.
2488 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2490 Diag(Loc, diag::err_ref_non_value)
2491 << D << SS.getRange();
2492 Diag(D->getLocation(), diag::note_declared_at);
2496 // Check whether this declaration can be used. Note that we suppress
2497 // this check when we're going to perform argument-dependent lookup
2498 // on this function name, because this might not be the function
2499 // that overload resolution actually selects.
2500 if (DiagnoseUseOfDecl(VD, Loc))
2503 // Only create DeclRefExpr's for valid Decl's.
2504 if (VD->isInvalidDecl())
2507 // Handle members of anonymous structs and unions. If we got here,
2508 // and the reference is to a class member indirect field, then this
2509 // must be the subject of a pointer-to-member expression.
2510 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2511 if (!indirectField->isCXXClassMember())
2512 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2516 QualType type = VD->getType();
2517 ExprValueKind valueKind = VK_RValue;
2519 switch (D->getKind()) {
2520 // Ignore all the non-ValueDecl kinds.
2521 #define ABSTRACT_DECL(kind)
2522 #define VALUE(type, base)
2523 #define DECL(type, base) \
2525 #include "clang/AST/DeclNodes.inc"
2526 llvm_unreachable("invalid value decl kind");
2528 // These shouldn't make it here.
2529 case Decl::ObjCAtDefsField:
2530 case Decl::ObjCIvar:
2531 llvm_unreachable("forming non-member reference to ivar?");
2533 // Enum constants are always r-values and never references.
2534 // Unresolved using declarations are dependent.
2535 case Decl::EnumConstant:
2536 case Decl::UnresolvedUsingValue:
2537 valueKind = VK_RValue;
2540 // Fields and indirect fields that got here must be for
2541 // pointer-to-member expressions; we just call them l-values for
2542 // internal consistency, because this subexpression doesn't really
2543 // exist in the high-level semantics.
2545 case Decl::IndirectField:
2546 assert(getLangOpts().CPlusPlus &&
2547 "building reference to field in C?");
2549 // These can't have reference type in well-formed programs, but
2550 // for internal consistency we do this anyway.
2551 type = type.getNonReferenceType();
2552 valueKind = VK_LValue;
2555 // Non-type template parameters are either l-values or r-values
2556 // depending on the type.
2557 case Decl::NonTypeTemplateParm: {
2558 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2559 type = reftype->getPointeeType();
2560 valueKind = VK_LValue; // even if the parameter is an r-value reference
2564 // For non-references, we need to strip qualifiers just in case
2565 // the template parameter was declared as 'const int' or whatever.
2566 valueKind = VK_RValue;
2567 type = type.getUnqualifiedType();
2572 // In C, "extern void blah;" is valid and is an r-value.
2573 if (!getLangOpts().CPlusPlus &&
2574 !type.hasQualifiers() &&
2575 type->isVoidType()) {
2576 valueKind = VK_RValue;
2581 case Decl::ImplicitParam:
2582 case Decl::ParmVar: {
2583 // These are always l-values.
2584 valueKind = VK_LValue;
2585 type = type.getNonReferenceType();
2587 // FIXME: Does the addition of const really only apply in
2588 // potentially-evaluated contexts? Since the variable isn't actually
2589 // captured in an unevaluated context, it seems that the answer is no.
2590 if (!isUnevaluatedContext()) {
2591 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2592 if (!CapturedType.isNull())
2593 type = CapturedType;
2599 case Decl::Function: {
2600 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2601 if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2602 type = Context.BuiltinFnTy;
2603 valueKind = VK_RValue;
2608 const FunctionType *fty = type->castAs<FunctionType>();
2610 // If we're referring to a function with an __unknown_anytype
2611 // result type, make the entire expression __unknown_anytype.
2612 if (fty->getResultType() == Context.UnknownAnyTy) {
2613 type = Context.UnknownAnyTy;
2614 valueKind = VK_RValue;
2618 // Functions are l-values in C++.
2619 if (getLangOpts().CPlusPlus) {
2620 valueKind = VK_LValue;
2624 // C99 DR 316 says that, if a function type comes from a
2625 // function definition (without a prototype), that type is only
2626 // used for checking compatibility. Therefore, when referencing
2627 // the function, we pretend that we don't have the full function
2629 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2630 isa<FunctionProtoType>(fty))
2631 type = Context.getFunctionNoProtoType(fty->getResultType(),
2634 // Functions are r-values in C.
2635 valueKind = VK_RValue;
2639 case Decl::CXXMethod:
2640 // If we're referring to a method with an __unknown_anytype
2641 // result type, make the entire expression __unknown_anytype.
2642 // This should only be possible with a type written directly.
2643 if (const FunctionProtoType *proto
2644 = dyn_cast<FunctionProtoType>(VD->getType()))
2645 if (proto->getResultType() == Context.UnknownAnyTy) {
2646 type = Context.UnknownAnyTy;
2647 valueKind = VK_RValue;
2651 // C++ methods are l-values if static, r-values if non-static.
2652 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2653 valueKind = VK_LValue;
2658 case Decl::CXXConversion:
2659 case Decl::CXXDestructor:
2660 case Decl::CXXConstructor:
2661 valueKind = VK_RValue;
2665 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD);
2669 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2670 PredefinedExpr::IdentType IT;
2673 default: llvm_unreachable("Unknown simple primary expr!");
2674 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2675 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2676 case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2677 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2680 // Pre-defined identifiers are of type char[x], where x is the length of the
2683 Decl *currentDecl = getCurFunctionOrMethodDecl();
2684 // Blocks and lambdas can occur at global scope. Don't emit a warning.
2686 if (const BlockScopeInfo *BSI = getCurBlock())
2687 currentDecl = BSI->TheDecl;
2688 else if (const LambdaScopeInfo *LSI = getCurLambda())
2689 currentDecl = LSI->CallOperator;
2693 Diag(Loc, diag::ext_predef_outside_function);
2694 currentDecl = Context.getTranslationUnitDecl();
2698 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2699 ResTy = Context.DependentTy;
2701 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2703 llvm::APInt LengthI(32, Length + 1);
2704 if (IT == PredefinedExpr::LFunction)
2705 ResTy = Context.WCharTy.withConst();
2707 ResTy = Context.CharTy.withConst();
2708 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2710 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2713 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2714 SmallString<16> CharBuffer;
2715 bool Invalid = false;
2716 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2720 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2722 if (Literal.hadError())
2726 if (Literal.isWide())
2727 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
2728 else if (Literal.isUTF16())
2729 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2730 else if (Literal.isUTF32())
2731 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2732 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2733 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
2735 Ty = Context.CharTy; // 'x' -> char in C++
2737 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2738 if (Literal.isWide())
2739 Kind = CharacterLiteral::Wide;
2740 else if (Literal.isUTF16())
2741 Kind = CharacterLiteral::UTF16;
2742 else if (Literal.isUTF32())
2743 Kind = CharacterLiteral::UTF32;
2745 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2748 if (Literal.getUDSuffix().empty())
2751 // We're building a user-defined literal.
2752 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2753 SourceLocation UDSuffixLoc =
2754 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2756 // Make sure we're allowed user-defined literals here.
2758 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2760 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2761 // operator "" X (ch)
2762 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2763 llvm::makeArrayRef(&Lit, 1),
2767 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2768 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2769 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2770 Context.IntTy, Loc));
2773 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2774 QualType Ty, SourceLocation Loc) {
2775 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2777 using llvm::APFloat;
2778 APFloat Val(Format);
2780 APFloat::opStatus result = Literal.GetFloatValue(Val);
2782 // Overflow is always an error, but underflow is only an error if
2783 // we underflowed to zero (APFloat reports denormals as underflow).
2784 if ((result & APFloat::opOverflow) ||
2785 ((result & APFloat::opUnderflow) && Val.isZero())) {
2786 unsigned diagnostic;
2787 SmallString<20> buffer;
2788 if (result & APFloat::opOverflow) {
2789 diagnostic = diag::warn_float_overflow;
2790 APFloat::getLargest(Format).toString(buffer);
2792 diagnostic = diag::warn_float_underflow;
2793 APFloat::getSmallest(Format).toString(buffer);
2796 S.Diag(Loc, diagnostic)
2798 << StringRef(buffer.data(), buffer.size());
2801 bool isExact = (result == APFloat::opOK);
2802 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2805 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2806 // Fast path for a single digit (which is quite common). A single digit
2807 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2808 if (Tok.getLength() == 1) {
2809 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2810 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2813 SmallString<128> SpellingBuffer;
2814 // NumericLiteralParser wants to overread by one character. Add padding to
2815 // the buffer in case the token is copied to the buffer. If getSpelling()
2816 // returns a StringRef to the memory buffer, it should have a null char at
2817 // the EOF, so it is also safe.
2818 SpellingBuffer.resize(Tok.getLength() + 1);
2820 // Get the spelling of the token, which eliminates trigraphs, etc.
2821 bool Invalid = false;
2822 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2826 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2827 if (Literal.hadError)
2830 if (Literal.hasUDSuffix()) {
2831 // We're building a user-defined literal.
2832 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2833 SourceLocation UDSuffixLoc =
2834 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2836 // Make sure we're allowed user-defined literals here.
2838 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2841 if (Literal.isFloatingLiteral()) {
2842 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2843 // long double, the literal is treated as a call of the form
2844 // operator "" X (f L)
2845 CookedTy = Context.LongDoubleTy;
2847 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2848 // unsigned long long, the literal is treated as a call of the form
2849 // operator "" X (n ULL)
2850 CookedTy = Context.UnsignedLongLongTy;
2853 DeclarationName OpName =
2854 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2855 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2856 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2858 // Perform literal operator lookup to determine if we're building a raw
2859 // literal or a cooked one.
2860 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2861 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2862 /*AllowRawAndTemplate*/true)) {
2868 if (Literal.isFloatingLiteral()) {
2869 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2871 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2872 if (Literal.GetIntegerValue(ResultVal))
2873 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2874 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2877 return BuildLiteralOperatorCall(R, OpNameInfo,
2878 llvm::makeArrayRef(&Lit, 1),
2883 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2884 // literal is treated as a call of the form
2885 // operator "" X ("n")
2886 SourceLocation TokLoc = Tok.getLocation();
2887 unsigned Length = Literal.getUDSuffixOffset();
2888 QualType StrTy = Context.getConstantArrayType(
2889 Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
2890 ArrayType::Normal, 0);
2891 Expr *Lit = StringLiteral::Create(
2892 Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
2893 /*Pascal*/false, StrTy, &TokLoc, 1);
2894 return BuildLiteralOperatorCall(R, OpNameInfo,
2895 llvm::makeArrayRef(&Lit, 1), TokLoc);
2899 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2900 // template), L is treated as a call fo the form
2901 // operator "" X <'c1', 'c2', ... 'ck'>()
2902 // where n is the source character sequence c1 c2 ... ck.
2903 TemplateArgumentListInfo ExplicitArgs;
2904 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2905 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2906 llvm::APSInt Value(CharBits, CharIsUnsigned);
2907 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2908 Value = TokSpelling[I];
2909 TemplateArgument Arg(Context, Value, Context.CharTy);
2910 TemplateArgumentLocInfo ArgInfo;
2911 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2913 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2914 Tok.getLocation(), &ExplicitArgs);
2917 llvm_unreachable("unexpected literal operator lookup result");
2922 if (Literal.isFloatingLiteral()) {
2924 if (Literal.isFloat)
2925 Ty = Context.FloatTy;
2926 else if (!Literal.isLong)
2927 Ty = Context.DoubleTy;
2929 Ty = Context.LongDoubleTy;
2931 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
2933 if (Ty == Context.DoubleTy) {
2934 if (getLangOpts().SinglePrecisionConstants) {
2935 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2936 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2937 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2938 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2941 } else if (!Literal.isIntegerLiteral()) {
2946 // 'long long' is a C99 or C++11 feature.
2947 if (!getLangOpts().C99 && Literal.isLongLong) {
2948 if (getLangOpts().CPlusPlus)
2949 Diag(Tok.getLocation(),
2950 getLangOpts().CPlusPlus11 ?
2951 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2953 Diag(Tok.getLocation(), diag::ext_c99_longlong);
2956 // Get the value in the widest-possible width.
2957 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2958 // The microsoft literal suffix extensions support 128-bit literals, which
2959 // may be wider than [u]intmax_t.
2960 // FIXME: Actually, they don't. We seem to have accidentally invented the
2962 if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
2963 PP.getTargetInfo().hasInt128Type())
2965 llvm::APInt ResultVal(MaxWidth, 0);
2967 if (Literal.GetIntegerValue(ResultVal)) {
2968 // If this value didn't fit into uintmax_t, warn and force to ull.
2969 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2970 Ty = Context.UnsignedLongLongTy;
2971 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2972 "long long is not intmax_t?");
2974 // If this value fits into a ULL, try to figure out what else it fits into
2975 // according to the rules of C99 6.4.4.1p5.
2977 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2978 // be an unsigned int.
2979 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2981 // Check from smallest to largest, picking the smallest type we can.
2983 if (!Literal.isLong && !Literal.isLongLong) {
2984 // Are int/unsigned possibilities?
2985 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2987 // Does it fit in a unsigned int?
2988 if (ResultVal.isIntN(IntSize)) {
2989 // Does it fit in a signed int?
2990 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2992 else if (AllowUnsigned)
2993 Ty = Context.UnsignedIntTy;
2998 // Are long/unsigned long possibilities?
2999 if (Ty.isNull() && !Literal.isLongLong) {
3000 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3002 // Does it fit in a unsigned long?
3003 if (ResultVal.isIntN(LongSize)) {
3004 // Does it fit in a signed long?
3005 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3006 Ty = Context.LongTy;
3007 else if (AllowUnsigned)
3008 Ty = Context.UnsignedLongTy;
3013 // Check long long if needed.
3015 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3017 // Does it fit in a unsigned long long?
3018 if (ResultVal.isIntN(LongLongSize)) {
3019 // Does it fit in a signed long long?
3020 // To be compatible with MSVC, hex integer literals ending with the
3021 // LL or i64 suffix are always signed in Microsoft mode.
3022 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3023 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3024 Ty = Context.LongLongTy;
3025 else if (AllowUnsigned)
3026 Ty = Context.UnsignedLongLongTy;
3027 Width = LongLongSize;
3031 // If it doesn't fit in unsigned long long, and we're using Microsoft
3032 // extensions, then its a 128-bit integer literal.
3033 if (Ty.isNull() && Literal.isMicrosoftInteger &&
3034 PP.getTargetInfo().hasInt128Type()) {
3035 if (Literal.isUnsigned)
3036 Ty = Context.UnsignedInt128Ty;
3038 Ty = Context.Int128Ty;
3042 // If we still couldn't decide a type, we probably have something that
3043 // does not fit in a signed long long, but has no U suffix.
3045 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
3046 Ty = Context.UnsignedLongLongTy;
3047 Width = Context.getTargetInfo().getLongLongWidth();
3050 if (ResultVal.getBitWidth() != Width)
3051 ResultVal = ResultVal.trunc(Width);
3053 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3056 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3057 if (Literal.isImaginary)
3058 Res = new (Context) ImaginaryLiteral(Res,
3059 Context.getComplexType(Res->getType()));
3064 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3065 assert((E != 0) && "ActOnParenExpr() missing expr");
3066 return Owned(new (Context) ParenExpr(L, R, E));
3069 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3071 SourceRange ArgRange) {
3072 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3073 // scalar or vector data type argument..."
3074 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3075 // type (C99 6.2.5p18) or void.
3076 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3077 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3082 assert((T->isVoidType() || !T->isIncompleteType()) &&
3083 "Scalar types should always be complete");
3087 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3089 SourceRange ArgRange,
3090 UnaryExprOrTypeTrait TraitKind) {
3092 if (T->isFunctionType() &&
3093 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3094 // sizeof(function)/alignof(function) is allowed as an extension.
3095 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3096 << TraitKind << ArgRange;
3100 // Allow sizeof(void)/alignof(void) as an extension.
3101 if (T->isVoidType()) {
3102 S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange;
3109 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3111 SourceRange ArgRange,
3112 UnaryExprOrTypeTrait TraitKind) {
3113 // Reject sizeof(interface) and sizeof(interface<proto>) if the
3114 // runtime doesn't allow it.
3115 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3116 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3117 << T << (TraitKind == UETT_SizeOf)
3125 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3126 /// pointer type is equal to T) and emit a warning if it is.
3127 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3129 // Don't warn if the operation changed the type.
3130 if (T != E->getType())
3133 // Now look for array decays.
3134 ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3135 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3138 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3140 << ICE->getSubExpr()->getType();
3143 /// \brief Check the constrains on expression operands to unary type expression
3144 /// and type traits.
3146 /// Completes any types necessary and validates the constraints on the operand
3147 /// expression. The logic mostly mirrors the type-based overload, but may modify
3148 /// the expression as it completes the type for that expression through template
3149 /// instantiation, etc.
3150 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3151 UnaryExprOrTypeTrait ExprKind) {
3152 QualType ExprTy = E->getType();
3154 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3155 // the result is the size of the referenced type."
3156 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3157 // result shall be the alignment of the referenced type."
3158 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3159 ExprTy = Ref->getPointeeType();
3161 if (ExprKind == UETT_VecStep)
3162 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3163 E->getSourceRange());
3165 // Whitelist some types as extensions
3166 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3167 E->getSourceRange(), ExprKind))
3170 if (RequireCompleteExprType(E,
3171 diag::err_sizeof_alignof_incomplete_type,
3172 ExprKind, E->getSourceRange()))
3175 // Completeing the expression's type may have changed it.
3176 ExprTy = E->getType();
3177 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3178 ExprTy = Ref->getPointeeType();
3180 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3181 E->getSourceRange(), ExprKind))
3184 if (ExprKind == UETT_SizeOf) {
3185 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3186 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3187 QualType OType = PVD->getOriginalType();
3188 QualType Type = PVD->getType();
3189 if (Type->isPointerType() && OType->isArrayType()) {
3190 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3192 Diag(PVD->getLocation(), diag::note_declared_at);
3197 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3198 // decays into a pointer and returns an unintended result. This is most
3199 // likely a typo for "sizeof(array) op x".
3200 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3201 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3203 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3211 /// \brief Check the constraints on operands to unary expression and type
3214 /// This will complete any types necessary, and validate the various constraints
3215 /// on those operands.
3217 /// The UsualUnaryConversions() function is *not* called by this routine.
3218 /// C99 6.3.2.1p[2-4] all state:
3219 /// Except when it is the operand of the sizeof operator ...
3221 /// C++ [expr.sizeof]p4
3222 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3223 /// standard conversions are not applied to the operand of sizeof.
3225 /// This policy is followed for all of the unary trait expressions.
3226 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3227 SourceLocation OpLoc,
3228 SourceRange ExprRange,
3229 UnaryExprOrTypeTrait ExprKind) {
3230 if (ExprType->isDependentType())
3233 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3234 // the result is the size of the referenced type."
3235 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3236 // result shall be the alignment of the referenced type."
3237 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3238 ExprType = Ref->getPointeeType();
3240 if (ExprKind == UETT_VecStep)
3241 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3243 // Whitelist some types as extensions
3244 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3248 if (RequireCompleteType(OpLoc, ExprType,
3249 diag::err_sizeof_alignof_incomplete_type,
3250 ExprKind, ExprRange))
3253 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3260 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3261 E = E->IgnoreParens();
3263 // alignof decl is always ok.
3264 if (isa<DeclRefExpr>(E))
3267 // Cannot know anything else if the expression is dependent.
3268 if (E->isTypeDependent())
3271 if (E->getBitField()) {
3272 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3273 << 1 << E->getSourceRange();
3277 // Alignment of a field access is always okay, so long as it isn't a
3279 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
3280 if (isa<FieldDecl>(ME->getMemberDecl()))
3283 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3286 bool Sema::CheckVecStepExpr(Expr *E) {
3287 E = E->IgnoreParens();
3289 // Cannot know anything else if the expression is dependent.
3290 if (E->isTypeDependent())
3293 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3296 /// \brief Build a sizeof or alignof expression given a type operand.
3298 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3299 SourceLocation OpLoc,
3300 UnaryExprOrTypeTrait ExprKind,
3305 QualType T = TInfo->getType();
3307 if (!T->isDependentType() &&
3308 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3311 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3312 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3313 Context.getSizeType(),
3314 OpLoc, R.getEnd()));
3317 /// \brief Build a sizeof or alignof expression given an expression
3320 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3321 UnaryExprOrTypeTrait ExprKind) {
3322 ExprResult PE = CheckPlaceholderExpr(E);
3328 // Verify that the operand is valid.
3329 bool isInvalid = false;
3330 if (E->isTypeDependent()) {
3331 // Delay type-checking for type-dependent expressions.
3332 } else if (ExprKind == UETT_AlignOf) {
3333 isInvalid = CheckAlignOfExpr(*this, E);
3334 } else if (ExprKind == UETT_VecStep) {
3335 isInvalid = CheckVecStepExpr(E);
3336 } else if (E->getBitField()) { // C99 6.5.3.4p1.
3337 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3340 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3346 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3347 PE = TransformToPotentiallyEvaluated(E);
3348 if (PE.isInvalid()) return ExprError();
3352 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3353 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3354 ExprKind, E, Context.getSizeType(), OpLoc,
3355 E->getSourceRange().getEnd()));
3358 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3359 /// expr and the same for @c alignof and @c __alignof
3360 /// Note that the ArgRange is invalid if isType is false.
3362 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3363 UnaryExprOrTypeTrait ExprKind, bool IsType,
3364 void *TyOrEx, const SourceRange &ArgRange) {
3365 // If error parsing type, ignore.
3366 if (TyOrEx == 0) return ExprError();
3369 TypeSourceInfo *TInfo;
3370 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3371 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3374 Expr *ArgEx = (Expr *)TyOrEx;
3375 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3379 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3381 if (V.get()->isTypeDependent())
3382 return S.Context.DependentTy;
3384 // _Real and _Imag are only l-values for normal l-values.
3385 if (V.get()->getObjectKind() != OK_Ordinary) {
3386 V = S.DefaultLvalueConversion(V.take());
3391 // These operators return the element type of a complex type.
3392 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3393 return CT->getElementType();
3395 // Otherwise they pass through real integer and floating point types here.
3396 if (V.get()->getType()->isArithmeticType())
3397 return V.get()->getType();
3399 // Test for placeholders.
3400 ExprResult PR = S.CheckPlaceholderExpr(V.get());
3401 if (PR.isInvalid()) return QualType();
3402 if (PR.get() != V.get()) {
3404 return CheckRealImagOperand(S, V, Loc, IsReal);
3407 // Reject anything else.
3408 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3409 << (IsReal ? "__real" : "__imag");
3416 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3417 tok::TokenKind Kind, Expr *Input) {
3418 UnaryOperatorKind Opc;
3420 default: llvm_unreachable("Unknown unary op!");
3421 case tok::plusplus: Opc = UO_PostInc; break;
3422 case tok::minusminus: Opc = UO_PostDec; break;
3425 // Since this might is a postfix expression, get rid of ParenListExprs.
3426 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3427 if (Result.isInvalid()) return ExprError();
3428 Input = Result.take();
3430 return BuildUnaryOp(S, OpLoc, Opc, Input);
3433 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3435 /// \return true on error
3436 static bool checkArithmeticOnObjCPointer(Sema &S,
3437 SourceLocation opLoc,
3439 assert(op->getType()->isObjCObjectPointerType());
3440 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3443 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3444 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3445 << op->getSourceRange();
3450 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3451 Expr *idx, SourceLocation rbLoc) {
3452 // Since this might be a postfix expression, get rid of ParenListExprs.
3453 if (isa<ParenListExpr>(base)) {
3454 ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3455 if (result.isInvalid()) return ExprError();
3456 base = result.take();
3459 // Handle any non-overload placeholder types in the base and index
3460 // expressions. We can't handle overloads here because the other
3461 // operand might be an overloadable type, in which case the overload
3462 // resolution for the operator overload should get the first crack
3464 if (base->getType()->isNonOverloadPlaceholderType()) {
3465 ExprResult result = CheckPlaceholderExpr(base);
3466 if (result.isInvalid()) return ExprError();
3467 base = result.take();
3469 if (idx->getType()->isNonOverloadPlaceholderType()) {
3470 ExprResult result = CheckPlaceholderExpr(idx);
3471 if (result.isInvalid()) return ExprError();
3472 idx = result.take();
3475 // Build an unanalyzed expression if either operand is type-dependent.
3476 if (getLangOpts().CPlusPlus &&
3477 (base->isTypeDependent() || idx->isTypeDependent())) {
3478 return Owned(new (Context) ArraySubscriptExpr(base, idx,
3479 Context.DependentTy,
3480 VK_LValue, OK_Ordinary,
3484 // Use C++ overloaded-operator rules if either operand has record
3485 // type. The spec says to do this if either type is *overloadable*,
3486 // but enum types can't declare subscript operators or conversion
3487 // operators, so there's nothing interesting for overload resolution
3488 // to do if there aren't any record types involved.
3490 // ObjC pointers have their own subscripting logic that is not tied
3491 // to overload resolution and so should not take this path.
3492 if (getLangOpts().CPlusPlus &&
3493 (base->getType()->isRecordType() ||
3494 (!base->getType()->isObjCObjectPointerType() &&
3495 idx->getType()->isRecordType()))) {
3496 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3499 return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3503 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3504 Expr *Idx, SourceLocation RLoc) {
3505 Expr *LHSExp = Base;
3508 // Perform default conversions.
3509 if (!LHSExp->getType()->getAs<VectorType>()) {
3510 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3511 if (Result.isInvalid())
3513 LHSExp = Result.take();
3515 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3516 if (Result.isInvalid())
3518 RHSExp = Result.take();
3520 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3521 ExprValueKind VK = VK_LValue;
3522 ExprObjectKind OK = OK_Ordinary;
3524 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3525 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3526 // in the subscript position. As a result, we need to derive the array base
3527 // and index from the expression types.
3528 Expr *BaseExpr, *IndexExpr;
3529 QualType ResultType;
3530 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3533 ResultType = Context.DependentTy;
3534 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3537 ResultType = PTy->getPointeeType();
3538 } else if (const ObjCObjectPointerType *PTy =
3539 LHSTy->getAs<ObjCObjectPointerType>()) {
3543 // Use custom logic if this should be the pseudo-object subscript
3545 if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3546 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3548 ResultType = PTy->getPointeeType();
3549 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3550 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3551 << ResultType << BaseExpr->getSourceRange();
3554 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3555 // Handle the uncommon case of "123[Ptr]".
3558 ResultType = PTy->getPointeeType();
3559 } else if (const ObjCObjectPointerType *PTy =
3560 RHSTy->getAs<ObjCObjectPointerType>()) {
3561 // Handle the uncommon case of "123[Ptr]".
3564 ResultType = PTy->getPointeeType();
3565 if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3566 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3567 << ResultType << BaseExpr->getSourceRange();
3570 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3571 BaseExpr = LHSExp; // vectors: V[123]
3573 VK = LHSExp->getValueKind();
3574 if (VK != VK_RValue)
3575 OK = OK_VectorComponent;
3577 // FIXME: need to deal with const...
3578 ResultType = VTy->getElementType();
3579 } else if (LHSTy->isArrayType()) {
3580 // If we see an array that wasn't promoted by
3581 // DefaultFunctionArrayLvalueConversion, it must be an array that
3582 // wasn't promoted because of the C90 rule that doesn't
3583 // allow promoting non-lvalue arrays. Warn, then
3584 // force the promotion here.
3585 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3586 LHSExp->getSourceRange();
3587 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3588 CK_ArrayToPointerDecay).take();
3589 LHSTy = LHSExp->getType();
3593 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3594 } else if (RHSTy->isArrayType()) {
3595 // Same as previous, except for 123[f().a] case
3596 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3597 RHSExp->getSourceRange();
3598 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3599 CK_ArrayToPointerDecay).take();
3600 RHSTy = RHSExp->getType();
3604 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3606 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3607 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3610 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3611 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3612 << IndexExpr->getSourceRange());
3614 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3615 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3616 && !IndexExpr->isTypeDependent())
3617 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3619 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3620 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3621 // type. Note that Functions are not objects, and that (in C99 parlance)
3622 // incomplete types are not object types.
3623 if (ResultType->isFunctionType()) {
3624 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3625 << ResultType << BaseExpr->getSourceRange();
3629 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3630 // GNU extension: subscripting on pointer to void
3631 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3632 << BaseExpr->getSourceRange();
3634 // C forbids expressions of unqualified void type from being l-values.
3635 // See IsCForbiddenLValueType.
3636 if (!ResultType.hasQualifiers()) VK = VK_RValue;
3637 } else if (!ResultType->isDependentType() &&
3638 RequireCompleteType(LLoc, ResultType,
3639 diag::err_subscript_incomplete_type, BaseExpr))
3642 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3643 !ResultType.isCForbiddenLValueType());
3645 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3646 ResultType, VK, OK, RLoc));
3649 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3651 ParmVarDecl *Param) {
3652 if (Param->hasUnparsedDefaultArg()) {
3654 diag::err_use_of_default_argument_to_function_declared_later) <<
3655 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3656 Diag(UnparsedDefaultArgLocs[Param],
3657 diag::note_default_argument_declared_here);
3661 if (Param->hasUninstantiatedDefaultArg()) {
3662 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3664 EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3667 // Instantiate the expression.
3668 MultiLevelTemplateArgumentList ArgList
3669 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3671 std::pair<const TemplateArgument *, unsigned> Innermost
3672 = ArgList.getInnermost();
3673 InstantiatingTemplate Inst(*this, CallLoc, Param,
3674 ArrayRef<TemplateArgument>(Innermost.first,
3681 // C++ [dcl.fct.default]p5:
3682 // The names in the [default argument] expression are bound, and
3683 // the semantic constraints are checked, at the point where the
3684 // default argument expression appears.
3685 ContextRAII SavedContext(*this, FD);
3686 LocalInstantiationScope Local(*this);
3687 Result = SubstExpr(UninstExpr, ArgList);
3689 if (Result.isInvalid())
3692 // Check the expression as an initializer for the parameter.
3693 InitializedEntity Entity
3694 = InitializedEntity::InitializeParameter(Context, Param);
3695 InitializationKind Kind
3696 = InitializationKind::CreateCopy(Param->getLocation(),
3697 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3698 Expr *ResultE = Result.takeAs<Expr>();
3700 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3701 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3702 if (Result.isInvalid())
3705 Expr *Arg = Result.takeAs<Expr>();
3706 CheckCompletedExpr(Arg, Param->getOuterLocStart());
3707 // Build the default argument expression.
3708 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3711 // If the default expression creates temporaries, we need to
3712 // push them to the current stack of expression temporaries so they'll
3713 // be properly destroyed.
3714 // FIXME: We should really be rebuilding the default argument with new
3715 // bound temporaries; see the comment in PR5810.
3716 // We don't need to do that with block decls, though, because
3717 // blocks in default argument expression can never capture anything.
3718 if (isa<ExprWithCleanups>(Param->getInit())) {
3719 // Set the "needs cleanups" bit regardless of whether there are
3720 // any explicit objects.
3721 ExprNeedsCleanups = true;
3723 // Append all the objects to the cleanup list. Right now, this
3724 // should always be a no-op, because blocks in default argument
3725 // expressions should never be able to capture anything.
3726 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3727 "default argument expression has capturing blocks?");
3730 // We already type-checked the argument, so we know it works.
3731 // Just mark all of the declarations in this potentially-evaluated expression
3732 // as being "referenced".
3733 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3734 /*SkipLocalVariables=*/true);
3735 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3739 Sema::VariadicCallType
3740 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3742 if (Proto && Proto->isVariadic()) {
3743 if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3744 return VariadicConstructor;
3745 else if (Fn && Fn->getType()->isBlockPointerType())
3746 return VariadicBlock;
3748 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3749 if (Method->isInstance())
3750 return VariadicMethod;
3752 return VariadicFunction;
3754 return VariadicDoesNotApply;
3757 /// ConvertArgumentsForCall - Converts the arguments specified in
3758 /// Args/NumArgs to the parameter types of the function FDecl with
3759 /// function prototype Proto. Call is the call expression itself, and
3760 /// Fn is the function expression. For a C++ member function, this
3761 /// routine does not attempt to convert the object argument. Returns
3762 /// true if the call is ill-formed.
3764 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3765 FunctionDecl *FDecl,
3766 const FunctionProtoType *Proto,
3767 Expr **Args, unsigned NumArgs,
3768 SourceLocation RParenLoc,
3769 bool IsExecConfig) {
3770 // Bail out early if calling a builtin with custom typechecking.
3771 // We don't need to do this in the
3773 if (unsigned ID = FDecl->getBuiltinID())
3774 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3777 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3778 // assignment, to the types of the corresponding parameter, ...
3779 unsigned NumArgsInProto = Proto->getNumArgs();
3780 bool Invalid = false;
3781 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3782 unsigned FnKind = Fn->getType()->isBlockPointerType()
3784 : (IsExecConfig ? 3 /* kernel function (exec config) */
3785 : 0 /* function */);
3787 // If too few arguments are available (and we don't have default
3788 // arguments for the remaining parameters), don't make the call.
3789 if (NumArgs < NumArgsInProto) {
3790 if (NumArgs < MinArgs) {
3791 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3792 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3793 ? diag::err_typecheck_call_too_few_args_one
3794 : diag::err_typecheck_call_too_few_args_at_least_one)
3796 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3798 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3799 ? diag::err_typecheck_call_too_few_args
3800 : diag::err_typecheck_call_too_few_args_at_least)
3802 << MinArgs << NumArgs << Fn->getSourceRange();
3804 // Emit the location of the prototype.
3805 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3806 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3811 Call->setNumArgs(Context, NumArgsInProto);
3814 // If too many are passed and not variadic, error on the extras and drop
3816 if (NumArgs > NumArgsInProto) {
3817 if (!Proto->isVariadic()) {
3818 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3819 Diag(Args[NumArgsInProto]->getLocStart(),
3820 MinArgs == NumArgsInProto
3821 ? diag::err_typecheck_call_too_many_args_one
3822 : diag::err_typecheck_call_too_many_args_at_most_one)
3824 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3825 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3826 Args[NumArgs-1]->getLocEnd());
3828 Diag(Args[NumArgsInProto]->getLocStart(),
3829 MinArgs == NumArgsInProto
3830 ? diag::err_typecheck_call_too_many_args
3831 : diag::err_typecheck_call_too_many_args_at_most)
3833 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3834 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3835 Args[NumArgs-1]->getLocEnd());
3837 // Emit the location of the prototype.
3838 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3839 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3842 // This deletes the extra arguments.
3843 Call->setNumArgs(Context, NumArgsInProto);
3847 SmallVector<Expr *, 8> AllArgs;
3848 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3850 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
3851 Proto, 0, Args, NumArgs, AllArgs, CallType);
3854 unsigned TotalNumArgs = AllArgs.size();
3855 for (unsigned i = 0; i < TotalNumArgs; ++i)
3856 Call->setArg(i, AllArgs[i]);
3861 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3862 FunctionDecl *FDecl,
3863 const FunctionProtoType *Proto,
3864 unsigned FirstProtoArg,
3865 Expr **Args, unsigned NumArgs,
3866 SmallVector<Expr *, 8> &AllArgs,
3867 VariadicCallType CallType,
3869 bool IsListInitialization) {
3870 unsigned NumArgsInProto = Proto->getNumArgs();
3871 unsigned NumArgsToCheck = NumArgs;
3872 bool Invalid = false;
3873 if (NumArgs != NumArgsInProto)
3874 // Use default arguments for missing arguments
3875 NumArgsToCheck = NumArgsInProto;
3877 // Continue to check argument types (even if we have too few/many args).
3878 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3879 QualType ProtoArgType = Proto->getArgType(i);
3883 if (ArgIx < NumArgs) {
3884 Arg = Args[ArgIx++];
3886 if (RequireCompleteType(Arg->getLocStart(),
3888 diag::err_call_incomplete_argument, Arg))
3891 // Pass the argument
3893 if (FDecl && i < FDecl->getNumParams())
3894 Param = FDecl->getParamDecl(i);
3896 // Strip the unbridged-cast placeholder expression off, if applicable.
3897 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3898 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3899 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3900 Arg = stripARCUnbridgedCast(Arg);
3902 InitializedEntity Entity = Param ?
3903 InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
3904 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3905 Proto->isArgConsumed(i));
3906 ExprResult ArgE = PerformCopyInitialization(Entity,
3909 IsListInitialization,
3911 if (ArgE.isInvalid())
3914 Arg = ArgE.takeAs<Expr>();
3916 assert(FDecl && "can't use default arguments without a known callee");
3917 Param = FDecl->getParamDecl(i);
3919 ExprResult ArgExpr =
3920 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3921 if (ArgExpr.isInvalid())
3924 Arg = ArgExpr.takeAs<Expr>();
3927 // Check for array bounds violations for each argument to the call. This
3928 // check only triggers warnings when the argument isn't a more complex Expr
3929 // with its own checking, such as a BinaryOperator.
3930 CheckArrayAccess(Arg);
3932 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3933 CheckStaticArrayArgument(CallLoc, Param, Arg);
3935 AllArgs.push_back(Arg);
3938 // If this is a variadic call, handle args passed through "...".
3939 if (CallType != VariadicDoesNotApply) {
3940 // Assume that extern "C" functions with variadic arguments that
3941 // return __unknown_anytype aren't *really* variadic.
3942 if (Proto->getResultType() == Context.UnknownAnyTy &&
3943 FDecl && FDecl->isExternC()) {
3944 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3945 QualType paramType; // ignored
3946 ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
3947 Invalid |= arg.isInvalid();
3948 AllArgs.push_back(arg.take());
3951 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3953 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3954 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3956 Invalid |= Arg.isInvalid();
3957 AllArgs.push_back(Arg.take());
3961 // Check for array bounds violations.
3962 for (unsigned i = ArgIx; i != NumArgs; ++i)
3963 CheckArrayAccess(Args[i]);
3968 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3969 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3970 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
3971 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3972 << ATL.getLocalSourceRange();
3975 /// CheckStaticArrayArgument - If the given argument corresponds to a static
3976 /// array parameter, check that it is non-null, and that if it is formed by
3977 /// array-to-pointer decay, the underlying array is sufficiently large.
3979 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3980 /// array type derivation, then for each call to the function, the value of the
3981 /// corresponding actual argument shall provide access to the first element of
3982 /// an array with at least as many elements as specified by the size expression.
3984 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3986 const Expr *ArgExpr) {
3987 // Static array parameters are not supported in C++.
3988 if (!Param || getLangOpts().CPlusPlus)
3991 QualType OrigTy = Param->getOriginalType();
3993 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3994 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3997 if (ArgExpr->isNullPointerConstant(Context,
3998 Expr::NPC_NeverValueDependent)) {
3999 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4000 DiagnoseCalleeStaticArrayParam(*this, Param);
4004 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4008 const ConstantArrayType *ArgCAT =
4009 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4013 if (ArgCAT->getSize().ult(CAT->getSize())) {
4014 Diag(CallLoc, diag::warn_static_array_too_small)
4015 << ArgExpr->getSourceRange()
4016 << (unsigned) ArgCAT->getSize().getZExtValue()
4017 << (unsigned) CAT->getSize().getZExtValue();
4018 DiagnoseCalleeStaticArrayParam(*this, Param);
4022 /// Given a function expression of unknown-any type, try to rebuild it
4023 /// to have a function type.
4024 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4026 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4027 /// This provides the location of the left/right parens and a list of comma
4030 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4031 MultiExprArg ArgExprs, SourceLocation RParenLoc,
4032 Expr *ExecConfig, bool IsExecConfig) {
4033 // Since this might be a postfix expression, get rid of ParenListExprs.
4034 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4035 if (Result.isInvalid()) return ExprError();
4038 if (getLangOpts().CPlusPlus) {
4039 // If this is a pseudo-destructor expression, build the call immediately.
4040 if (isa<CXXPseudoDestructorExpr>(Fn)) {
4041 if (!ArgExprs.empty()) {
4042 // Pseudo-destructor calls should not have any arguments.
4043 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4044 << FixItHint::CreateRemoval(
4045 SourceRange(ArgExprs[0]->getLocStart(),
4046 ArgExprs.back()->getLocEnd()));
4049 return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
4050 Context.VoidTy, VK_RValue,
4054 // Determine whether this is a dependent call inside a C++ template,
4055 // in which case we won't do any semantic analysis now.
4056 // FIXME: Will need to cache the results of name lookup (including ADL) in
4058 bool Dependent = false;
4059 if (Fn->isTypeDependent())
4061 else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4066 return Owned(new (Context) CUDAKernelCallExpr(
4067 Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4068 Context.DependentTy, VK_RValue, RParenLoc));
4070 return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
4071 Context.DependentTy, VK_RValue,
4076 // Determine whether this is a call to an object (C++ [over.call.object]).
4077 if (Fn->getType()->isRecordType())
4078 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
4080 ArgExprs.size(), RParenLoc));
4082 if (Fn->getType() == Context.UnknownAnyTy) {
4083 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4084 if (result.isInvalid()) return ExprError();
4088 if (Fn->getType() == Context.BoundMemberTy) {
4089 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
4090 ArgExprs.size(), RParenLoc);
4094 // Check for overloaded calls. This can happen even in C due to extensions.
4095 if (Fn->getType() == Context.OverloadTy) {
4096 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4098 // We aren't supposed to apply this logic for if there's an '&' involved.
4099 if (!find.HasFormOfMemberPointer) {
4100 OverloadExpr *ovl = find.Expression;
4101 if (isa<UnresolvedLookupExpr>(ovl)) {
4102 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4103 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
4104 ArgExprs.size(), RParenLoc, ExecConfig);
4106 return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
4107 ArgExprs.size(), RParenLoc);
4112 // If we're directly calling a function, get the appropriate declaration.
4113 if (Fn->getType() == Context.UnknownAnyTy) {
4114 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4115 if (result.isInvalid()) return ExprError();
4119 Expr *NakedFn = Fn->IgnoreParens();
4121 NamedDecl *NDecl = 0;
4122 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4123 if (UnOp->getOpcode() == UO_AddrOf)
4124 NakedFn = UnOp->getSubExpr()->IgnoreParens();
4126 if (isa<DeclRefExpr>(NakedFn))
4127 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4128 else if (isa<MemberExpr>(NakedFn))
4129 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4131 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
4132 ArgExprs.size(), RParenLoc, ExecConfig,
4137 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4138 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4139 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4141 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4142 << "cudaConfigureCall");
4143 QualType ConfigQTy = ConfigDecl->getType();
4145 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4146 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4147 MarkFunctionReferenced(LLLLoc, ConfigDecl);
4149 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4150 /*IsExecConfig=*/true);
4153 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4155 /// __builtin_astype( value, dst type )
4157 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4158 SourceLocation BuiltinLoc,
4159 SourceLocation RParenLoc) {
4160 ExprValueKind VK = VK_RValue;
4161 ExprObjectKind OK = OK_Ordinary;
4162 QualType DstTy = GetTypeFromParser(ParsedDestTy);
4163 QualType SrcTy = E->getType();
4164 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4165 return ExprError(Diag(BuiltinLoc,
4166 diag::err_invalid_astype_of_different_size)
4169 << E->getSourceRange());
4170 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
4174 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4175 /// i.e. an expression not of \p OverloadTy. The expression should
4176 /// unary-convert to an expression of function-pointer or
4177 /// block-pointer type.
4179 /// \param NDecl the declaration being called, if available
4181 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4182 SourceLocation LParenLoc,
4183 Expr **Args, unsigned NumArgs,
4184 SourceLocation RParenLoc,
4185 Expr *Config, bool IsExecConfig) {
4186 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4187 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4189 // Promote the function operand.
4190 // We special-case function promotion here because we only allow promoting
4191 // builtin functions to function pointers in the callee of a call.
4194 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4195 Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4196 CK_BuiltinFnToFnPtr).take();
4198 Result = UsualUnaryConversions(Fn);
4200 if (Result.isInvalid())
4204 // Make the call expr early, before semantic checks. This guarantees cleanup
4205 // of arguments and function on error.
4208 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4209 cast<CallExpr>(Config),
4210 llvm::makeArrayRef(Args,NumArgs),
4215 TheCall = new (Context) CallExpr(Context, Fn,
4216 llvm::makeArrayRef(Args, NumArgs),
4221 // Bail out early if calling a builtin with custom typechecking.
4222 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4223 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4226 const FunctionType *FuncT;
4227 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4228 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4229 // have type pointer to function".
4230 FuncT = PT->getPointeeType()->getAs<FunctionType>();
4232 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4233 << Fn->getType() << Fn->getSourceRange());
4234 } else if (const BlockPointerType *BPT =
4235 Fn->getType()->getAs<BlockPointerType>()) {
4236 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4238 // Handle calls to expressions of unknown-any type.
4239 if (Fn->getType() == Context.UnknownAnyTy) {
4240 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4241 if (rewrite.isInvalid()) return ExprError();
4242 Fn = rewrite.take();
4243 TheCall->setCallee(Fn);
4247 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4248 << Fn->getType() << Fn->getSourceRange());
4251 if (getLangOpts().CUDA) {
4253 // CUDA: Kernel calls must be to global functions
4254 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4255 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4256 << FDecl->getName() << Fn->getSourceRange());
4258 // CUDA: Kernel function must have 'void' return type
4259 if (!FuncT->getResultType()->isVoidType())
4260 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4261 << Fn->getType() << Fn->getSourceRange());
4263 // CUDA: Calls to global functions must be configured
4264 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4265 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4266 << FDecl->getName() << Fn->getSourceRange());
4270 // Check for a valid return type
4271 if (CheckCallReturnType(FuncT->getResultType(),
4272 Fn->getLocStart(), TheCall,
4276 // We know the result type of the call, set it.
4277 TheCall->setType(FuncT->getCallResultType(Context));
4278 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4280 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4282 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
4283 RParenLoc, IsExecConfig))
4286 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4289 // Check if we have too few/too many template arguments, based
4290 // on our knowledge of the function definition.
4291 const FunctionDecl *Def = 0;
4292 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
4293 Proto = Def->getType()->getAs<FunctionProtoType>();
4294 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
4295 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4296 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
4299 // If the function we're calling isn't a function prototype, but we have
4300 // a function prototype from a prior declaratiom, use that prototype.
4301 if (!FDecl->hasPrototype())
4302 Proto = FDecl->getType()->getAs<FunctionProtoType>();
4305 // Promote the arguments (C99 6.5.2.2p6).
4306 for (unsigned i = 0; i != NumArgs; i++) {
4307 Expr *Arg = Args[i];
4309 if (Proto && i < Proto->getNumArgs()) {
4310 InitializedEntity Entity
4311 = InitializedEntity::InitializeParameter(Context,
4312 Proto->getArgType(i),
4313 Proto->isArgConsumed(i));
4314 ExprResult ArgE = PerformCopyInitialization(Entity,
4317 if (ArgE.isInvalid())
4320 Arg = ArgE.takeAs<Expr>();
4323 ExprResult ArgE = DefaultArgumentPromotion(Arg);
4325 if (ArgE.isInvalid())
4328 Arg = ArgE.takeAs<Expr>();
4331 if (RequireCompleteType(Arg->getLocStart(),
4333 diag::err_call_incomplete_argument, Arg))
4336 TheCall->setArg(i, Arg);
4340 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4341 if (!Method->isStatic())
4342 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4343 << Fn->getSourceRange());
4345 // Check for sentinels
4347 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
4349 // Do special checking on direct calls to functions.
4351 if (CheckFunctionCall(FDecl, TheCall, Proto))
4355 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4357 if (CheckBlockCall(NDecl, TheCall, Proto))
4361 return MaybeBindToTemporary(TheCall);
4365 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4366 SourceLocation RParenLoc, Expr *InitExpr) {
4367 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
4368 // FIXME: put back this assert when initializers are worked out.
4369 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4371 TypeSourceInfo *TInfo;
4372 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4374 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4376 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4380 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4381 SourceLocation RParenLoc, Expr *LiteralExpr) {
4382 QualType literalType = TInfo->getType();
4384 if (literalType->isArrayType()) {
4385 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4386 diag::err_illegal_decl_array_incomplete_type,
4387 SourceRange(LParenLoc,
4388 LiteralExpr->getSourceRange().getEnd())))
4390 if (literalType->isVariableArrayType())
4391 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4392 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4393 } else if (!literalType->isDependentType() &&
4394 RequireCompleteType(LParenLoc, literalType,
4395 diag::err_typecheck_decl_incomplete_type,
4396 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4399 InitializedEntity Entity
4400 = InitializedEntity::InitializeTemporary(literalType);
4401 InitializationKind Kind
4402 = InitializationKind::CreateCStyleCast(LParenLoc,
4403 SourceRange(LParenLoc, RParenLoc),
4405 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
4406 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4408 if (Result.isInvalid())
4410 LiteralExpr = Result.get();
4412 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4413 if (isFileScope) { // 6.5.2.5p3
4414 if (CheckForConstantInitializer(LiteralExpr, literalType))
4418 // In C, compound literals are l-values for some reason.
4419 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4421 return MaybeBindToTemporary(
4422 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4423 VK, LiteralExpr, isFileScope));
4427 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4428 SourceLocation RBraceLoc) {
4429 // Immediately handle non-overload placeholders. Overloads can be
4430 // resolved contextually, but everything else here can't.
4431 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4432 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4433 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4435 // Ignore failures; dropping the entire initializer list because
4436 // of one failure would be terrible for indexing/etc.
4437 if (result.isInvalid()) continue;
4439 InitArgList[I] = result.take();
4443 // Semantic analysis for initializers is done by ActOnDeclarator() and
4444 // CheckInitializer() - it requires knowledge of the object being intialized.
4446 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4448 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4452 /// Do an explicit extend of the given block pointer if we're in ARC.
4453 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4454 assert(E.get()->getType()->isBlockPointerType());
4455 assert(E.get()->isRValue());
4457 // Only do this in an r-value context.
4458 if (!S.getLangOpts().ObjCAutoRefCount) return;
4460 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4461 CK_ARCExtendBlockObject, E.get(),
4462 /*base path*/ 0, VK_RValue);
4463 S.ExprNeedsCleanups = true;
4466 /// Prepare a conversion of the given expression to an ObjC object
4468 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4469 QualType type = E.get()->getType();
4470 if (type->isObjCObjectPointerType()) {
4472 } else if (type->isBlockPointerType()) {
4473 maybeExtendBlockObject(*this, E);
4474 return CK_BlockPointerToObjCPointerCast;
4476 assert(type->isPointerType());
4477 return CK_CPointerToObjCPointerCast;
4481 /// Prepares for a scalar cast, performing all the necessary stages
4482 /// except the final cast and returning the kind required.
4483 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4484 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4485 // Also, callers should have filtered out the invalid cases with
4486 // pointers. Everything else should be possible.
4488 QualType SrcTy = Src.get()->getType();
4489 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4492 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4493 case Type::STK_MemberPointer:
4494 llvm_unreachable("member pointer type in C");
4496 case Type::STK_CPointer:
4497 case Type::STK_BlockPointer:
4498 case Type::STK_ObjCObjectPointer:
4499 switch (DestTy->getScalarTypeKind()) {
4500 case Type::STK_CPointer:
4502 case Type::STK_BlockPointer:
4503 return (SrcKind == Type::STK_BlockPointer
4504 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4505 case Type::STK_ObjCObjectPointer:
4506 if (SrcKind == Type::STK_ObjCObjectPointer)
4508 if (SrcKind == Type::STK_CPointer)
4509 return CK_CPointerToObjCPointerCast;
4510 maybeExtendBlockObject(*this, Src);
4511 return CK_BlockPointerToObjCPointerCast;
4512 case Type::STK_Bool:
4513 return CK_PointerToBoolean;
4514 case Type::STK_Integral:
4515 return CK_PointerToIntegral;
4516 case Type::STK_Floating:
4517 case Type::STK_FloatingComplex:
4518 case Type::STK_IntegralComplex:
4519 case Type::STK_MemberPointer:
4520 llvm_unreachable("illegal cast from pointer");
4522 llvm_unreachable("Should have returned before this");
4524 case Type::STK_Bool: // casting from bool is like casting from an integer
4525 case Type::STK_Integral:
4526 switch (DestTy->getScalarTypeKind()) {
4527 case Type::STK_CPointer:
4528 case Type::STK_ObjCObjectPointer:
4529 case Type::STK_BlockPointer:
4530 if (Src.get()->isNullPointerConstant(Context,
4531 Expr::NPC_ValueDependentIsNull))
4532 return CK_NullToPointer;
4533 return CK_IntegralToPointer;
4534 case Type::STK_Bool:
4535 return CK_IntegralToBoolean;
4536 case Type::STK_Integral:
4537 return CK_IntegralCast;
4538 case Type::STK_Floating:
4539 return CK_IntegralToFloating;
4540 case Type::STK_IntegralComplex:
4541 Src = ImpCastExprToType(Src.take(),
4542 DestTy->castAs<ComplexType>()->getElementType(),
4544 return CK_IntegralRealToComplex;
4545 case Type::STK_FloatingComplex:
4546 Src = ImpCastExprToType(Src.take(),
4547 DestTy->castAs<ComplexType>()->getElementType(),
4548 CK_IntegralToFloating);
4549 return CK_FloatingRealToComplex;
4550 case Type::STK_MemberPointer:
4551 llvm_unreachable("member pointer type in C");
4553 llvm_unreachable("Should have returned before this");
4555 case Type::STK_Floating:
4556 switch (DestTy->getScalarTypeKind()) {
4557 case Type::STK_Floating:
4558 return CK_FloatingCast;
4559 case Type::STK_Bool:
4560 return CK_FloatingToBoolean;
4561 case Type::STK_Integral:
4562 return CK_FloatingToIntegral;
4563 case Type::STK_FloatingComplex:
4564 Src = ImpCastExprToType(Src.take(),
4565 DestTy->castAs<ComplexType>()->getElementType(),
4567 return CK_FloatingRealToComplex;
4568 case Type::STK_IntegralComplex:
4569 Src = ImpCastExprToType(Src.take(),
4570 DestTy->castAs<ComplexType>()->getElementType(),
4571 CK_FloatingToIntegral);
4572 return CK_IntegralRealToComplex;
4573 case Type::STK_CPointer:
4574 case Type::STK_ObjCObjectPointer:
4575 case Type::STK_BlockPointer:
4576 llvm_unreachable("valid float->pointer cast?");
4577 case Type::STK_MemberPointer:
4578 llvm_unreachable("member pointer type in C");
4580 llvm_unreachable("Should have returned before this");
4582 case Type::STK_FloatingComplex:
4583 switch (DestTy->getScalarTypeKind()) {
4584 case Type::STK_FloatingComplex:
4585 return CK_FloatingComplexCast;
4586 case Type::STK_IntegralComplex:
4587 return CK_FloatingComplexToIntegralComplex;
4588 case Type::STK_Floating: {
4589 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4590 if (Context.hasSameType(ET, DestTy))
4591 return CK_FloatingComplexToReal;
4592 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4593 return CK_FloatingCast;
4595 case Type::STK_Bool:
4596 return CK_FloatingComplexToBoolean;
4597 case Type::STK_Integral:
4598 Src = ImpCastExprToType(Src.take(),
4599 SrcTy->castAs<ComplexType>()->getElementType(),
4600 CK_FloatingComplexToReal);
4601 return CK_FloatingToIntegral;
4602 case Type::STK_CPointer:
4603 case Type::STK_ObjCObjectPointer:
4604 case Type::STK_BlockPointer:
4605 llvm_unreachable("valid complex float->pointer cast?");
4606 case Type::STK_MemberPointer:
4607 llvm_unreachable("member pointer type in C");
4609 llvm_unreachable("Should have returned before this");
4611 case Type::STK_IntegralComplex:
4612 switch (DestTy->getScalarTypeKind()) {
4613 case Type::STK_FloatingComplex:
4614 return CK_IntegralComplexToFloatingComplex;
4615 case Type::STK_IntegralComplex:
4616 return CK_IntegralComplexCast;
4617 case Type::STK_Integral: {
4618 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4619 if (Context.hasSameType(ET, DestTy))
4620 return CK_IntegralComplexToReal;
4621 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4622 return CK_IntegralCast;
4624 case Type::STK_Bool:
4625 return CK_IntegralComplexToBoolean;
4626 case Type::STK_Floating:
4627 Src = ImpCastExprToType(Src.take(),
4628 SrcTy->castAs<ComplexType>()->getElementType(),
4629 CK_IntegralComplexToReal);
4630 return CK_IntegralToFloating;
4631 case Type::STK_CPointer:
4632 case Type::STK_ObjCObjectPointer:
4633 case Type::STK_BlockPointer:
4634 llvm_unreachable("valid complex int->pointer cast?");
4635 case Type::STK_MemberPointer:
4636 llvm_unreachable("member pointer type in C");
4638 llvm_unreachable("Should have returned before this");
4641 llvm_unreachable("Unhandled scalar cast");
4644 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4646 assert(VectorTy->isVectorType() && "Not a vector type!");
4648 if (Ty->isVectorType() || Ty->isIntegerType()) {
4649 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4650 return Diag(R.getBegin(),
4651 Ty->isVectorType() ?
4652 diag::err_invalid_conversion_between_vectors :
4653 diag::err_invalid_conversion_between_vector_and_integer)
4654 << VectorTy << Ty << R;
4656 return Diag(R.getBegin(),
4657 diag::err_invalid_conversion_between_vector_and_scalar)
4658 << VectorTy << Ty << R;
4664 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4665 Expr *CastExpr, CastKind &Kind) {
4666 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4668 QualType SrcTy = CastExpr->getType();
4670 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4671 // an ExtVectorType.
4672 // In OpenCL, casts between vectors of different types are not allowed.
4673 // (See OpenCL 6.2).
4674 if (SrcTy->isVectorType()) {
4675 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4676 || (getLangOpts().OpenCL &&
4677 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4678 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4679 << DestTy << SrcTy << R;
4683 return Owned(CastExpr);
4686 // All non-pointer scalars can be cast to ExtVector type. The appropriate
4687 // conversion will take place first from scalar to elt type, and then
4688 // splat from elt type to vector.
4689 if (SrcTy->isPointerType())
4690 return Diag(R.getBegin(),
4691 diag::err_invalid_conversion_between_vector_and_scalar)
4692 << DestTy << SrcTy << R;
4694 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4695 ExprResult CastExprRes = Owned(CastExpr);
4696 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4697 if (CastExprRes.isInvalid())
4699 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4701 Kind = CK_VectorSplat;
4702 return Owned(CastExpr);
4706 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4707 Declarator &D, ParsedType &Ty,
4708 SourceLocation RParenLoc, Expr *CastExpr) {
4709 assert(!D.isInvalidType() && (CastExpr != 0) &&
4710 "ActOnCastExpr(): missing type or expr");
4712 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
4713 if (D.isInvalidType())
4716 if (getLangOpts().CPlusPlus) {
4717 // Check that there are no default arguments (C++ only).
4718 CheckExtraCXXDefaultArguments(D);
4721 checkUnusedDeclAttributes(D);
4723 QualType castType = castTInfo->getType();
4724 Ty = CreateParsedType(castType, castTInfo);
4726 bool isVectorLiteral = false;
4728 // Check for an altivec or OpenCL literal,
4729 // i.e. all the elements are integer constants.
4730 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4731 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
4732 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
4733 && castType->isVectorType() && (PE || PLE)) {
4734 if (PLE && PLE->getNumExprs() == 0) {
4735 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4738 if (PE || PLE->getNumExprs() == 1) {
4739 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4740 if (!E->getType()->isVectorType())
4741 isVectorLiteral = true;
4744 isVectorLiteral = true;
4747 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4748 // then handle it as such.
4749 if (isVectorLiteral)
4750 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
4752 // If the Expr being casted is a ParenListExpr, handle it specially.
4753 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4754 // sequence of BinOp comma operators.
4755 if (isa<ParenListExpr>(CastExpr)) {
4756 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
4757 if (Result.isInvalid()) return ExprError();
4758 CastExpr = Result.take();
4761 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
4764 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4765 SourceLocation RParenLoc, Expr *E,
4766 TypeSourceInfo *TInfo) {
4767 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4768 "Expected paren or paren list expression");
4773 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
4774 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4775 LiteralLParenLoc = PE->getLParenLoc();
4776 LiteralRParenLoc = PE->getRParenLoc();
4777 exprs = PE->getExprs();
4778 numExprs = PE->getNumExprs();
4779 } else { // isa<ParenExpr> by assertion at function entrance
4780 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
4781 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
4782 subExpr = cast<ParenExpr>(E)->getSubExpr();
4787 QualType Ty = TInfo->getType();
4788 assert(Ty->isVectorType() && "Expected vector type");
4790 SmallVector<Expr *, 8> initExprs;
4791 const VectorType *VTy = Ty->getAs<VectorType>();
4792 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4794 // '(...)' form of vector initialization in AltiVec: the number of
4795 // initializers must be one or must match the size of the vector.
4796 // If a single value is specified in the initializer then it will be
4797 // replicated to all the components of the vector
4798 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
4799 // The number of initializers must be one or must match the size of the
4800 // vector. If a single value is specified in the initializer then it will
4801 // be replicated to all the components of the vector
4802 if (numExprs == 1) {
4803 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4804 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4805 if (Literal.isInvalid())
4807 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4808 PrepareScalarCast(Literal, ElemTy));
4809 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4811 else if (numExprs < numElems) {
4812 Diag(E->getExprLoc(),
4813 diag::err_incorrect_number_of_vector_initializers);
4817 initExprs.append(exprs, exprs + numExprs);
4820 // For OpenCL, when the number of initializers is a single value,
4821 // it will be replicated to all components of the vector.
4822 if (getLangOpts().OpenCL &&
4823 VTy->getVectorKind() == VectorType::GenericVector &&
4825 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4826 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4827 if (Literal.isInvalid())
4829 Literal = ImpCastExprToType(Literal.take(), ElemTy,
4830 PrepareScalarCast(Literal, ElemTy));
4831 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4834 initExprs.append(exprs, exprs + numExprs);
4836 // FIXME: This means that pretty-printing the final AST will produce curly
4837 // braces instead of the original commas.
4838 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
4839 initExprs, LiteralRParenLoc);
4841 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4844 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4845 /// the ParenListExpr into a sequence of comma binary operators.
4847 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4848 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
4850 return Owned(OrigExpr);
4852 ExprResult Result(E->getExpr(0));
4854 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4855 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4858 if (Result.isInvalid()) return ExprError();
4860 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4863 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4866 Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
4870 /// \brief Emit a specialized diagnostic when one expression is a null pointer
4871 /// constant and the other is not a pointer. Returns true if a diagnostic is
4873 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
4874 SourceLocation QuestionLoc) {
4875 Expr *NullExpr = LHSExpr;
4876 Expr *NonPointerExpr = RHSExpr;
4877 Expr::NullPointerConstantKind NullKind =
4878 NullExpr->isNullPointerConstant(Context,
4879 Expr::NPC_ValueDependentIsNotNull);
4881 if (NullKind == Expr::NPCK_NotNull) {
4883 NonPointerExpr = LHSExpr;
4885 NullExpr->isNullPointerConstant(Context,
4886 Expr::NPC_ValueDependentIsNotNull);
4889 if (NullKind == Expr::NPCK_NotNull)
4892 if (NullKind == Expr::NPCK_ZeroExpression)
4895 if (NullKind == Expr::NPCK_ZeroLiteral) {
4896 // In this case, check to make sure that we got here from a "NULL"
4897 // string in the source code.
4898 NullExpr = NullExpr->IgnoreParenImpCasts();
4899 SourceLocation loc = NullExpr->getExprLoc();
4900 if (!findMacroSpelling(loc, "NULL"))
4904 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
4905 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4906 << NonPointerExpr->getType() << DiagType
4907 << NonPointerExpr->getSourceRange();
4911 /// \brief Return false if the condition expression is valid, true otherwise.
4912 static bool checkCondition(Sema &S, Expr *Cond) {
4913 QualType CondTy = Cond->getType();
4916 if (CondTy->isScalarType()) return false;
4918 // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
4919 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
4922 // Emit the proper error message.
4923 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
4924 diag::err_typecheck_cond_expect_scalar :
4925 diag::err_typecheck_cond_expect_scalar_or_vector)
4930 /// \brief Return false if the two expressions can be converted to a vector,
4932 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4935 // Both operands should be of scalar type.
4936 if (!LHS.get()->getType()->isScalarType()) {
4937 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4941 if (!RHS.get()->getType()->isScalarType()) {
4942 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4947 // Implicity convert these scalars to the type of the condition.
4948 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4949 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4953 /// \brief Handle when one or both operands are void type.
4954 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4956 Expr *LHSExpr = LHS.get();
4957 Expr *RHSExpr = RHS.get();
4959 if (!LHSExpr->getType()->isVoidType())
4960 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4961 << RHSExpr->getSourceRange();
4962 if (!RHSExpr->getType()->isVoidType())
4963 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4964 << LHSExpr->getSourceRange();
4965 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4966 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4967 return S.Context.VoidTy;
4970 /// \brief Return false if the NullExpr can be promoted to PointerTy,
4972 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4973 QualType PointerTy) {
4974 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4975 !NullExpr.get()->isNullPointerConstant(S.Context,
4976 Expr::NPC_ValueDependentIsNull))
4979 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4983 /// \brief Checks compatibility between two pointers and return the resulting
4985 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4987 SourceLocation Loc) {
4988 QualType LHSTy = LHS.get()->getType();
4989 QualType RHSTy = RHS.get()->getType();
4991 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4992 // Two identical pointers types are always compatible.
4996 QualType lhptee, rhptee;
4998 // Get the pointee types.
4999 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5000 lhptee = LHSBTy->getPointeeType();
5001 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5003 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5004 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5007 // C99 6.5.15p6: If both operands are pointers to compatible types or to
5008 // differently qualified versions of compatible types, the result type is
5009 // a pointer to an appropriately qualified version of the composite
5012 // Only CVR-qualifiers exist in the standard, and the differently-qualified
5013 // clause doesn't make sense for our extensions. E.g. address space 2 should
5014 // be incompatible with address space 3: they may live on different devices or
5016 Qualifiers lhQual = lhptee.getQualifiers();
5017 Qualifiers rhQual = rhptee.getQualifiers();
5019 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5020 lhQual.removeCVRQualifiers();
5021 rhQual.removeCVRQualifiers();
5023 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5024 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5026 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5028 if (CompositeTy.isNull()) {
5029 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5030 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5031 << RHS.get()->getSourceRange();
5032 // In this situation, we assume void* type. No especially good
5033 // reason, but this is what gcc does, and we do have to pick
5034 // to get a consistent AST.
5035 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5036 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5037 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5041 // The pointer types are compatible.
5042 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5043 ResultTy = S.Context.getPointerType(ResultTy);
5045 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
5046 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
5050 /// \brief Return the resulting type when the operands are both block pointers.
5051 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5054 SourceLocation Loc) {
5055 QualType LHSTy = LHS.get()->getType();
5056 QualType RHSTy = RHS.get()->getType();
5058 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5059 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5060 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5061 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5062 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5065 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5066 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5067 << RHS.get()->getSourceRange();
5071 // We have 2 block pointer types.
5072 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5075 /// \brief Return the resulting type when the operands are both pointers.
5077 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5079 SourceLocation Loc) {
5080 // get the pointer types
5081 QualType LHSTy = LHS.get()->getType();
5082 QualType RHSTy = RHS.get()->getType();
5084 // get the "pointed to" types
5085 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5086 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5088 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5089 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5090 // Figure out necessary qualifiers (C99 6.5.15p6)
5091 QualType destPointee
5092 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5093 QualType destType = S.Context.getPointerType(destPointee);
5094 // Add qualifiers if necessary.
5095 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5096 // Promote to void*.
5097 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5100 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5101 QualType destPointee
5102 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5103 QualType destType = S.Context.getPointerType(destPointee);
5104 // Add qualifiers if necessary.
5105 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5106 // Promote to void*.
5107 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5111 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5114 /// \brief Return false if the first expression is not an integer and the second
5115 /// expression is not a pointer, true otherwise.
5116 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5117 Expr* PointerExpr, SourceLocation Loc,
5118 bool IsIntFirstExpr) {
5119 if (!PointerExpr->getType()->isPointerType() ||
5120 !Int.get()->getType()->isIntegerType())
5123 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5124 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5126 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5127 << Expr1->getType() << Expr2->getType()
5128 << Expr1->getSourceRange() << Expr2->getSourceRange();
5129 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5130 CK_IntegralToPointer);
5134 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5135 /// In that case, LHS = cond.
5137 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5138 ExprResult &RHS, ExprValueKind &VK,
5140 SourceLocation QuestionLoc) {
5142 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5143 if (!LHSResult.isUsable()) return QualType();
5146 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5147 if (!RHSResult.isUsable()) return QualType();
5150 // C++ is sufficiently different to merit its own checker.
5151 if (getLangOpts().CPlusPlus)
5152 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5157 Cond = UsualUnaryConversions(Cond.take());
5158 if (Cond.isInvalid())
5160 LHS = UsualUnaryConversions(LHS.take());
5161 if (LHS.isInvalid())
5163 RHS = UsualUnaryConversions(RHS.take());
5164 if (RHS.isInvalid())
5167 QualType CondTy = Cond.get()->getType();
5168 QualType LHSTy = LHS.get()->getType();
5169 QualType RHSTy = RHS.get()->getType();
5171 // first, check the condition.
5172 if (checkCondition(*this, Cond.get()))
5175 // Now check the two expressions.
5176 if (LHSTy->isVectorType() || RHSTy->isVectorType())
5177 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5179 // If the condition is a vector, and both operands are scalar,
5180 // attempt to implicity convert them to the vector type to act like the
5181 // built in select. (OpenCL v1.1 s6.3.i)
5182 if (getLangOpts().OpenCL && CondTy->isVectorType())
5183 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5186 // If both operands have arithmetic type, do the usual arithmetic conversions
5187 // to find a common type: C99 6.5.15p3,5.
5188 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5189 UsualArithmeticConversions(LHS, RHS);
5190 if (LHS.isInvalid() || RHS.isInvalid())
5192 return LHS.get()->getType();
5195 // If both operands are the same structure or union type, the result is that
5197 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
5198 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5199 if (LHSRT->getDecl() == RHSRT->getDecl())
5200 // "If both the operands have structure or union type, the result has
5201 // that type." This implies that CV qualifiers are dropped.
5202 return LHSTy.getUnqualifiedType();
5203 // FIXME: Type of conditional expression must be complete in C mode.
5206 // C99 6.5.15p5: "If both operands have void type, the result has void type."
5207 // The following || allows only one side to be void (a GCC-ism).
5208 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5209 return checkConditionalVoidType(*this, LHS, RHS);
5212 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5213 // the type of the other operand."
5214 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5215 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5217 // All objective-c pointer type analysis is done here.
5218 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5220 if (LHS.isInvalid() || RHS.isInvalid())
5222 if (!compositeType.isNull())
5223 return compositeType;
5226 // Handle block pointer types.
5227 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5228 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5231 // Check constraints for C object pointers types (C99 6.5.15p3,6).
5232 if (LHSTy->isPointerType() && RHSTy->isPointerType())
5233 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5236 // GCC compatibility: soften pointer/integer mismatch. Note that
5237 // null pointers have been filtered out by this point.
5238 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5239 /*isIntFirstExpr=*/true))
5241 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5242 /*isIntFirstExpr=*/false))
5245 // Emit a better diagnostic if one of the expressions is a null pointer
5246 // constant and the other is not a pointer type. In this case, the user most
5247 // likely forgot to take the address of the other expression.
5248 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5251 // Otherwise, the operands are not compatible.
5252 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5253 << LHSTy << RHSTy << LHS.get()->getSourceRange()
5254 << RHS.get()->getSourceRange();
5258 /// FindCompositeObjCPointerType - Helper method to find composite type of
5259 /// two objective-c pointer types of the two input expressions.
5260 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5261 SourceLocation QuestionLoc) {
5262 QualType LHSTy = LHS.get()->getType();
5263 QualType RHSTy = RHS.get()->getType();
5265 // Handle things like Class and struct objc_class*. Here we case the result
5266 // to the pseudo-builtin, because that will be implicitly cast back to the
5267 // redefinition type if an attempt is made to access its fields.
5268 if (LHSTy->isObjCClassType() &&
5269 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5270 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5273 if (RHSTy->isObjCClassType() &&
5274 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5275 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5278 // And the same for struct objc_object* / id
5279 if (LHSTy->isObjCIdType() &&
5280 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5281 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5284 if (RHSTy->isObjCIdType() &&
5285 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5286 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5289 // And the same for struct objc_selector* / SEL
5290 if (Context.isObjCSelType(LHSTy) &&
5291 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5292 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5295 if (Context.isObjCSelType(RHSTy) &&
5296 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5297 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5300 // Check constraints for Objective-C object pointers types.
5301 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5303 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5304 // Two identical object pointer types are always compatible.
5307 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5308 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5309 QualType compositeType = LHSTy;
5311 // If both operands are interfaces and either operand can be
5312 // assigned to the other, use that type as the composite
5313 // type. This allows
5314 // xxx ? (A*) a : (B*) b
5315 // where B is a subclass of A.
5317 // Additionally, as for assignment, if either type is 'id'
5318 // allow silent coercion. Finally, if the types are
5319 // incompatible then make sure to use 'id' as the composite
5320 // type so the result is acceptable for sending messages to.
5322 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5323 // It could return the composite type.
5324 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5325 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5326 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5327 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5328 } else if ((LHSTy->isObjCQualifiedIdType() ||
5329 RHSTy->isObjCQualifiedIdType()) &&
5330 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5331 // Need to handle "id<xx>" explicitly.
5332 // GCC allows qualified id and any Objective-C type to devolve to
5333 // id. Currently localizing to here until clear this should be
5334 // part of ObjCQualifiedIdTypesAreCompatible.
5335 compositeType = Context.getObjCIdType();
5336 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5337 compositeType = Context.getObjCIdType();
5338 } else if (!(compositeType =
5339 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5342 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5344 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5345 QualType incompatTy = Context.getObjCIdType();
5346 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5347 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5350 // The object pointer types are compatible.
5351 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5352 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5353 return compositeType;
5355 // Check Objective-C object pointer types and 'void *'
5356 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5357 if (getLangOpts().ObjCAutoRefCount) {
5358 // ARC forbids the implicit conversion of object pointers to 'void *',
5359 // so these types are not compatible.
5360 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5361 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5365 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5366 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5367 QualType destPointee
5368 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5369 QualType destType = Context.getPointerType(destPointee);
5370 // Add qualifiers if necessary.
5371 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5372 // Promote to void*.
5373 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5376 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5377 if (getLangOpts().ObjCAutoRefCount) {
5378 // ARC forbids the implicit conversion of object pointers to 'void *',
5379 // so these types are not compatible.
5380 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5381 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5385 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5386 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5387 QualType destPointee
5388 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5389 QualType destType = Context.getPointerType(destPointee);
5390 // Add qualifiers if necessary.
5391 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5392 // Promote to void*.
5393 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5399 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5400 /// ParenRange in parentheses.
5401 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5402 const PartialDiagnostic &Note,
5403 SourceRange ParenRange) {
5404 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5405 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5407 Self.Diag(Loc, Note)
5408 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5409 << FixItHint::CreateInsertion(EndLoc, ")");
5411 // We can't display the parentheses, so just show the bare note.
5412 Self.Diag(Loc, Note) << ParenRange;
5416 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5417 return Opc >= BO_Mul && Opc <= BO_Shr;
5420 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5421 /// expression, either using a built-in or overloaded operator,
5422 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5424 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5426 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5427 E = E->IgnoreImpCasts();
5428 E = E->IgnoreConversionOperator();
5429 E = E->IgnoreImpCasts();
5431 // Built-in binary operator.
5432 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5433 if (IsArithmeticOp(OP->getOpcode())) {
5434 *Opcode = OP->getOpcode();
5435 *RHSExprs = OP->getRHS();
5440 // Overloaded operator.
5441 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5442 if (Call->getNumArgs() != 2)
5445 // Make sure this is really a binary operator that is safe to pass into
5446 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5447 OverloadedOperatorKind OO = Call->getOperator();
5448 if (OO < OO_Plus || OO > OO_Arrow ||
5449 OO == OO_PlusPlus || OO == OO_MinusMinus)
5452 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5453 if (IsArithmeticOp(OpKind)) {
5455 *RHSExprs = Call->getArg(1);
5463 static bool IsLogicOp(BinaryOperatorKind Opc) {
5464 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5467 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5468 /// or is a logical expression such as (x==y) which has int type, but is
5469 /// commonly interpreted as boolean.
5470 static bool ExprLooksBoolean(Expr *E) {
5471 E = E->IgnoreParenImpCasts();
5473 if (E->getType()->isBooleanType())
5475 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5476 return IsLogicOp(OP->getOpcode());
5477 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5478 return OP->getOpcode() == UO_LNot;
5483 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5484 /// and binary operator are mixed in a way that suggests the programmer assumed
5485 /// the conditional operator has higher precedence, for example:
5486 /// "int x = a + someBinaryCondition ? 1 : 2".
5487 static void DiagnoseConditionalPrecedence(Sema &Self,
5488 SourceLocation OpLoc,
5492 BinaryOperatorKind CondOpcode;
5495 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5497 if (!ExprLooksBoolean(CondRHS))
5500 // The condition is an arithmetic binary expression, with a right-
5501 // hand side that looks boolean, so warn.
5503 Self.Diag(OpLoc, diag::warn_precedence_conditional)
5504 << Condition->getSourceRange()
5505 << BinaryOperator::getOpcodeStr(CondOpcode);
5507 SuggestParentheses(Self, OpLoc,
5508 Self.PDiag(diag::note_precedence_silence)
5509 << BinaryOperator::getOpcodeStr(CondOpcode),
5510 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5512 SuggestParentheses(Self, OpLoc,
5513 Self.PDiag(diag::note_precedence_conditional_first),
5514 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5517 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
5518 /// in the case of a the GNU conditional expr extension.
5519 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5520 SourceLocation ColonLoc,
5521 Expr *CondExpr, Expr *LHSExpr,
5523 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5524 // was the condition.
5525 OpaqueValueExpr *opaqueValue = 0;
5526 Expr *commonExpr = 0;
5528 commonExpr = CondExpr;
5530 // We usually want to apply unary conversions *before* saving, except
5531 // in the special case of a C++ l-value conditional.
5532 if (!(getLangOpts().CPlusPlus
5533 && !commonExpr->isTypeDependent()
5534 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5535 && commonExpr->isGLValue()
5536 && commonExpr->isOrdinaryOrBitFieldObject()
5537 && RHSExpr->isOrdinaryOrBitFieldObject()
5538 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5539 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5540 if (commonRes.isInvalid())
5542 commonExpr = commonRes.take();
5545 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5546 commonExpr->getType(),
5547 commonExpr->getValueKind(),
5548 commonExpr->getObjectKind(),
5550 LHSExpr = CondExpr = opaqueValue;
5553 ExprValueKind VK = VK_RValue;
5554 ExprObjectKind OK = OK_Ordinary;
5555 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5556 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
5557 VK, OK, QuestionLoc);
5558 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5562 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5566 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5567 LHS.take(), ColonLoc,
5568 RHS.take(), result, VK, OK));
5570 return Owned(new (Context)
5571 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5572 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5576 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5577 // being closely modeled after the C99 spec:-). The odd characteristic of this
5578 // routine is it effectively iqnores the qualifiers on the top level pointee.
5579 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5580 // FIXME: add a couple examples in this comment.
5581 static Sema::AssignConvertType
5582 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5583 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5584 assert(RHSType.isCanonical() && "RHS not canonicalized!");
5586 // get the "pointed to" type (ignoring qualifiers at the top level)
5587 const Type *lhptee, *rhptee;
5588 Qualifiers lhq, rhq;
5589 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5590 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5592 Sema::AssignConvertType ConvTy = Sema::Compatible;
5594 // C99 6.5.16.1p1: This following citation is common to constraints
5595 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5596 // qualifiers of the type *pointed to* by the right;
5599 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5600 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5601 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5602 // Ignore lifetime for further calculation.
5603 lhq.removeObjCLifetime();
5604 rhq.removeObjCLifetime();
5607 if (!lhq.compatiblyIncludes(rhq)) {
5608 // Treat address-space mismatches as fatal. TODO: address subspaces
5609 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5610 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5612 // It's okay to add or remove GC or lifetime qualifiers when converting to
5614 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
5615 .compatiblyIncludes(
5616 rhq.withoutObjCGCAttr().withoutObjCLifetime())
5617 && (lhptee->isVoidType() || rhptee->isVoidType()))
5620 // Treat lifetime mismatches as fatal.
5621 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5622 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5624 // For GCC compatibility, other qualifier mismatches are treated
5625 // as still compatible in C.
5626 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5629 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5630 // incomplete type and the other is a pointer to a qualified or unqualified
5631 // version of void...
5632 if (lhptee->isVoidType()) {
5633 if (rhptee->isIncompleteOrObjectType())
5636 // As an extension, we allow cast to/from void* to function pointer.
5637 assert(rhptee->isFunctionType());
5638 return Sema::FunctionVoidPointer;
5641 if (rhptee->isVoidType()) {
5642 if (lhptee->isIncompleteOrObjectType())
5645 // As an extension, we allow cast to/from void* to function pointer.
5646 assert(lhptee->isFunctionType());
5647 return Sema::FunctionVoidPointer;
5650 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5651 // unqualified versions of compatible types, ...
5652 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5653 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5654 // Check if the pointee types are compatible ignoring the sign.
5655 // We explicitly check for char so that we catch "char" vs
5656 // "unsigned char" on systems where "char" is unsigned.
5657 if (lhptee->isCharType())
5658 ltrans = S.Context.UnsignedCharTy;
5659 else if (lhptee->hasSignedIntegerRepresentation())
5660 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5662 if (rhptee->isCharType())
5663 rtrans = S.Context.UnsignedCharTy;
5664 else if (rhptee->hasSignedIntegerRepresentation())
5665 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5667 if (ltrans == rtrans) {
5668 // Types are compatible ignoring the sign. Qualifier incompatibility
5669 // takes priority over sign incompatibility because the sign
5670 // warning can be disabled.
5671 if (ConvTy != Sema::Compatible)
5674 return Sema::IncompatiblePointerSign;
5677 // If we are a multi-level pointer, it's possible that our issue is simply
5678 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5679 // the eventual target type is the same and the pointers have the same
5680 // level of indirection, this must be the issue.
5681 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5683 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5684 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5685 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5687 if (lhptee == rhptee)
5688 return Sema::IncompatibleNestedPointerQualifiers;
5691 // General pointer incompatibility takes priority over qualifiers.
5692 return Sema::IncompatiblePointer;
5694 if (!S.getLangOpts().CPlusPlus &&
5695 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5696 return Sema::IncompatiblePointer;
5700 /// checkBlockPointerTypesForAssignment - This routine determines whether two
5701 /// block pointer types are compatible or whether a block and normal pointer
5702 /// are compatible. It is more restrict than comparing two function pointer
5704 static Sema::AssignConvertType
5705 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5707 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5708 assert(RHSType.isCanonical() && "RHS not canonicalized!");
5710 QualType lhptee, rhptee;
5712 // get the "pointed to" type (ignoring qualifiers at the top level)
5713 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5714 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
5716 // In C++, the types have to match exactly.
5717 if (S.getLangOpts().CPlusPlus)
5718 return Sema::IncompatibleBlockPointer;
5720 Sema::AssignConvertType ConvTy = Sema::Compatible;
5722 // For blocks we enforce that qualifiers are identical.
5723 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5724 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5726 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
5727 return Sema::IncompatibleBlockPointer;
5732 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5733 /// for assignment compatibility.
5734 static Sema::AssignConvertType
5735 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5737 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5738 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
5740 if (LHSType->isObjCBuiltinType()) {
5741 // Class is not compatible with ObjC object pointers.
5742 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5743 !RHSType->isObjCQualifiedClassType())
5744 return Sema::IncompatiblePointer;
5745 return Sema::Compatible;
5747 if (RHSType->isObjCBuiltinType()) {
5748 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5749 !LHSType->isObjCQualifiedClassType())
5750 return Sema::IncompatiblePointer;
5751 return Sema::Compatible;
5753 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5754 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5756 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5757 // make an exception for id<P>
5758 !LHSType->isObjCQualifiedIdType())
5759 return Sema::CompatiblePointerDiscardsQualifiers;
5761 if (S.Context.typesAreCompatible(LHSType, RHSType))
5762 return Sema::Compatible;
5763 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
5764 return Sema::IncompatibleObjCQualifiedId;
5765 return Sema::IncompatiblePointer;
5768 Sema::AssignConvertType
5769 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5770 QualType LHSType, QualType RHSType) {
5771 // Fake up an opaque expression. We don't actually care about what
5772 // cast operations are required, so if CheckAssignmentConstraints
5773 // adds casts to this they'll be wasted, but fortunately that doesn't
5774 // usually happen on valid code.
5775 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5776 ExprResult RHSPtr = &RHSExpr;
5777 CastKind K = CK_Invalid;
5779 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
5782 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5783 /// has code to accommodate several GCC extensions when type checking
5784 /// pointers. Here are some objectionable examples that GCC considers warnings:
5788 /// struct foo *pfoo;
5790 /// pint = pshort; // warning: assignment from incompatible pointer type
5791 /// a = pint; // warning: assignment makes integer from pointer without a cast
5792 /// pint = a; // warning: assignment makes pointer from integer without a cast
5793 /// pint = pfoo; // warning: assignment from incompatible pointer type
5795 /// As a result, the code for dealing with pointers is more complex than the
5796 /// C99 spec dictates.
5798 /// Sets 'Kind' for any result kind except Incompatible.
5799 Sema::AssignConvertType
5800 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5802 QualType RHSType = RHS.get()->getType();
5803 QualType OrigLHSType = LHSType;
5805 // Get canonical types. We're not formatting these types, just comparing
5807 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5808 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
5810 // Common case: no conversion required.
5811 if (LHSType == RHSType) {
5816 // If we have an atomic type, try a non-atomic assignment, then just add an
5817 // atomic qualification step.
5818 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5819 Sema::AssignConvertType result =
5820 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5821 if (result != Compatible)
5823 if (Kind != CK_NoOp)
5824 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5825 Kind = CK_NonAtomicToAtomic;
5829 // If the left-hand side is a reference type, then we are in a
5830 // (rare!) case where we've allowed the use of references in C,
5831 // e.g., as a parameter type in a built-in function. In this case,
5832 // just make sure that the type referenced is compatible with the
5833 // right-hand side type. The caller is responsible for adjusting
5834 // LHSType so that the resulting expression does not have reference
5836 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5837 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
5838 Kind = CK_LValueBitCast;
5841 return Incompatible;
5844 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5845 // to the same ExtVector type.
5846 if (LHSType->isExtVectorType()) {
5847 if (RHSType->isExtVectorType())
5848 return Incompatible;
5849 if (RHSType->isArithmeticType()) {
5850 // CK_VectorSplat does T -> vector T, so first cast to the
5852 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5853 if (elType != RHSType) {
5854 Kind = PrepareScalarCast(RHS, elType);
5855 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
5857 Kind = CK_VectorSplat;
5862 // Conversions to or from vector type.
5863 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5864 if (LHSType->isVectorType() && RHSType->isVectorType()) {
5865 // Allow assignments of an AltiVec vector type to an equivalent GCC
5866 // vector type and vice versa
5867 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5872 // If we are allowing lax vector conversions, and LHS and RHS are both
5873 // vectors, the total size only needs to be the same. This is a bitcast;
5874 // no bits are changed but the result type is different.
5875 if (getLangOpts().LaxVectorConversions &&
5876 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
5878 return IncompatibleVectors;
5881 return Incompatible;
5884 // Arithmetic conversions.
5885 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5886 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
5887 Kind = PrepareScalarCast(RHS, LHSType);
5891 // Conversions to normal pointers.
5892 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
5894 if (isa<PointerType>(RHSType)) {
5896 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
5900 if (RHSType->isIntegerType()) {
5901 Kind = CK_IntegralToPointer; // FIXME: null?
5902 return IntToPointer;
5905 // C pointers are not compatible with ObjC object pointers,
5906 // with two exceptions:
5907 if (isa<ObjCObjectPointerType>(RHSType)) {
5908 // - conversions to void*
5909 if (LHSPointer->getPointeeType()->isVoidType()) {
5914 // - conversions from 'Class' to the redefinition type
5915 if (RHSType->isObjCClassType() &&
5916 Context.hasSameType(LHSType,
5917 Context.getObjCClassRedefinitionType())) {
5923 return IncompatiblePointer;
5927 if (RHSType->getAs<BlockPointerType>()) {
5928 if (LHSPointer->getPointeeType()->isVoidType()) {
5934 return Incompatible;
5937 // Conversions to block pointers.
5938 if (isa<BlockPointerType>(LHSType)) {
5940 if (RHSType->isBlockPointerType()) {
5942 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
5945 // int or null -> T^
5946 if (RHSType->isIntegerType()) {
5947 Kind = CK_IntegralToPointer; // FIXME: null
5948 return IntToBlockPointer;
5952 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
5953 Kind = CK_AnyPointerToBlockPointerCast;
5958 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
5959 if (RHSPT->getPointeeType()->isVoidType()) {
5960 Kind = CK_AnyPointerToBlockPointerCast;
5964 return Incompatible;
5967 // Conversions to Objective-C pointers.
5968 if (isa<ObjCObjectPointerType>(LHSType)) {
5970 if (RHSType->isObjCObjectPointerType()) {
5972 Sema::AssignConvertType result =
5973 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
5974 if (getLangOpts().ObjCAutoRefCount &&
5975 result == Compatible &&
5976 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
5977 result = IncompatibleObjCWeakRef;
5981 // int or null -> A*
5982 if (RHSType->isIntegerType()) {
5983 Kind = CK_IntegralToPointer; // FIXME: null
5984 return IntToPointer;
5987 // In general, C pointers are not compatible with ObjC object pointers,
5988 // with two exceptions:
5989 if (isa<PointerType>(RHSType)) {
5990 Kind = CK_CPointerToObjCPointerCast;
5992 // - conversions from 'void*'
5993 if (RHSType->isVoidPointerType()) {
5997 // - conversions to 'Class' from its redefinition type
5998 if (LHSType->isObjCClassType() &&
5999 Context.hasSameType(RHSType,
6000 Context.getObjCClassRedefinitionType())) {
6004 return IncompatiblePointer;
6008 if (RHSType->isBlockPointerType()) {
6009 maybeExtendBlockObject(*this, RHS);
6010 Kind = CK_BlockPointerToObjCPointerCast;
6014 return Incompatible;
6017 // Conversions from pointers that are not covered by the above.
6018 if (isa<PointerType>(RHSType)) {
6020 if (LHSType == Context.BoolTy) {
6021 Kind = CK_PointerToBoolean;
6026 if (LHSType->isIntegerType()) {
6027 Kind = CK_PointerToIntegral;
6028 return PointerToInt;
6031 return Incompatible;
6034 // Conversions from Objective-C pointers that are not covered by the above.
6035 if (isa<ObjCObjectPointerType>(RHSType)) {
6037 if (LHSType == Context.BoolTy) {
6038 Kind = CK_PointerToBoolean;
6043 if (LHSType->isIntegerType()) {
6044 Kind = CK_PointerToIntegral;
6045 return PointerToInt;
6048 return Incompatible;
6051 // struct A -> struct B
6052 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6053 if (Context.typesAreCompatible(LHSType, RHSType)) {
6059 return Incompatible;
6062 /// \brief Constructs a transparent union from an expression that is
6063 /// used to initialize the transparent union.
6064 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6065 ExprResult &EResult, QualType UnionType,
6067 // Build an initializer list that designates the appropriate member
6068 // of the transparent union.
6069 Expr *E = EResult.take();
6070 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6071 E, SourceLocation());
6072 Initializer->setType(UnionType);
6073 Initializer->setInitializedFieldInUnion(Field);
6075 // Build a compound literal constructing a value of the transparent
6076 // union type from this initializer list.
6077 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6079 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6080 VK_RValue, Initializer, false));
6083 Sema::AssignConvertType
6084 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6086 QualType RHSType = RHS.get()->getType();
6088 // If the ArgType is a Union type, we want to handle a potential
6089 // transparent_union GCC extension.
6090 const RecordType *UT = ArgType->getAsUnionType();
6091 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6092 return Incompatible;
6094 // The field to initialize within the transparent union.
6095 RecordDecl *UD = UT->getDecl();
6096 FieldDecl *InitField = 0;
6097 // It's compatible if the expression matches any of the fields.
6098 for (RecordDecl::field_iterator it = UD->field_begin(),
6099 itend = UD->field_end();
6100 it != itend; ++it) {
6101 if (it->getType()->isPointerType()) {
6102 // If the transparent union contains a pointer type, we allow:
6104 // 2) null pointer constant
6105 if (RHSType->isPointerType())
6106 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6107 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
6112 if (RHS.get()->isNullPointerConstant(Context,
6113 Expr::NPC_ValueDependentIsNull)) {
6114 RHS = ImpCastExprToType(RHS.take(), it->getType(),
6121 CastKind Kind = CK_Invalid;
6122 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6124 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
6131 return Incompatible;
6133 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6137 Sema::AssignConvertType
6138 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6140 if (getLangOpts().CPlusPlus) {
6141 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6142 // C++ 5.17p3: If the left operand is not of class type, the
6143 // expression is implicitly converted (C++ 4) to the
6144 // cv-unqualified type of the left operand.
6147 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6150 ImplicitConversionSequence ICS =
6151 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6152 /*SuppressUserConversions=*/false,
6153 /*AllowExplicit=*/false,
6154 /*InOverloadResolution=*/false,
6156 /*AllowObjCWritebackConversion=*/false);
6157 if (ICS.isFailure())
6158 return Incompatible;
6159 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6162 if (Res.isInvalid())
6163 return Incompatible;
6164 Sema::AssignConvertType result = Compatible;
6165 if (getLangOpts().ObjCAutoRefCount &&
6166 !CheckObjCARCUnavailableWeakConversion(LHSType,
6167 RHS.get()->getType()))
6168 result = IncompatibleObjCWeakRef;
6173 // FIXME: Currently, we fall through and treat C++ classes like C
6175 // FIXME: We also fall through for atomics; not sure what should
6176 // happen there, though.
6179 // C99 6.5.16.1p1: the left operand is a pointer and the right is
6180 // a null pointer constant.
6181 if ((LHSType->isPointerType() ||
6182 LHSType->isObjCObjectPointerType() ||
6183 LHSType->isBlockPointerType())
6184 && RHS.get()->isNullPointerConstant(Context,
6185 Expr::NPC_ValueDependentIsNull)) {
6186 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
6190 // This check seems unnatural, however it is necessary to ensure the proper
6191 // conversion of functions/arrays. If the conversion were done for all
6192 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6193 // expressions that suppress this implicit conversion (&, sizeof).
6195 // Suppress this for references: C++ 8.5.3p5.
6196 if (!LHSType->isReferenceType()) {
6197 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6198 if (RHS.isInvalid())
6199 return Incompatible;
6202 CastKind Kind = CK_Invalid;
6203 Sema::AssignConvertType result =
6204 CheckAssignmentConstraints(LHSType, RHS, Kind);
6206 // C99 6.5.16.1p2: The value of the right operand is converted to the
6207 // type of the assignment expression.
6208 // CheckAssignmentConstraints allows the left-hand side to be a reference,
6209 // so that we can use references in built-in functions even in C.
6210 // The getNonReferenceType() call makes sure that the resulting expression
6211 // does not have reference type.
6212 if (result != Incompatible && RHS.get()->getType() != LHSType)
6213 RHS = ImpCastExprToType(RHS.take(),
6214 LHSType.getNonLValueExprType(Context), Kind);
6218 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6220 Diag(Loc, diag::err_typecheck_invalid_operands)
6221 << LHS.get()->getType() << RHS.get()->getType()
6222 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6226 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6227 SourceLocation Loc, bool IsCompAssign) {
6228 if (!IsCompAssign) {
6229 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6230 if (LHS.isInvalid())
6233 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6234 if (RHS.isInvalid())
6237 // For conversion purposes, we ignore any qualifiers.
6238 // For example, "const float" and "float" are equivalent.
6240 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6242 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6244 // If the vector types are identical, return.
6245 if (LHSType == RHSType)
6248 // Handle the case of equivalent AltiVec and GCC vector types
6249 if (LHSType->isVectorType() && RHSType->isVectorType() &&
6250 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6251 if (LHSType->isExtVectorType()) {
6252 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6257 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6261 if (getLangOpts().LaxVectorConversions &&
6262 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6263 // If we are allowing lax vector conversions, and LHS and RHS are both
6264 // vectors, the total size only needs to be the same. This is a
6265 // bitcast; no bits are changed but the result type is different.
6266 // FIXME: Should we really be allowing this?
6267 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6271 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6272 // swap back (so that we don't reverse the inputs to a subtract, for instance.
6273 bool swapped = false;
6274 if (RHSType->isExtVectorType() && !IsCompAssign) {
6276 std::swap(RHS, LHS);
6277 std::swap(RHSType, LHSType);
6280 // Handle the case of an ext vector and scalar.
6281 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6282 QualType EltTy = LV->getElementType();
6283 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6284 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6286 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6288 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6289 if (swapped) std::swap(RHS, LHS);
6293 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6294 RHSType->isRealFloatingType()) {
6295 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6297 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6299 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6300 if (swapped) std::swap(RHS, LHS);
6306 // Vectors of different size or scalar and non-ext-vector are errors.
6307 if (swapped) std::swap(RHS, LHS);
6308 Diag(Loc, diag::err_typecheck_vector_not_convertable)
6309 << LHS.get()->getType() << RHS.get()->getType()
6310 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6314 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6315 // expression. These are mainly cases where the null pointer is used as an
6316 // integer instead of a pointer.
6317 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6318 SourceLocation Loc, bool IsCompare) {
6319 // The canonical way to check for a GNU null is with isNullPointerConstant,
6320 // but we use a bit of a hack here for speed; this is a relatively
6321 // hot path, and isNullPointerConstant is slow.
6322 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6323 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6325 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6327 // Avoid analyzing cases where the result will either be invalid (and
6328 // diagnosed as such) or entirely valid and not something to warn about.
6329 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6330 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6333 // Comparison operations would not make sense with a null pointer no matter
6334 // what the other expression is.
6336 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6337 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6338 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6342 // The rest of the operations only make sense with a null pointer
6343 // if the other expression is a pointer.
6344 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6345 NonNullType->canDecayToPointerType())
6348 S.Diag(Loc, diag::warn_null_in_comparison_operation)
6349 << LHSNull /* LHS is NULL */ << NonNullType
6350 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6353 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6355 bool IsCompAssign, bool IsDiv) {
6356 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6358 if (LHS.get()->getType()->isVectorType() ||
6359 RHS.get()->getType()->isVectorType())
6360 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6362 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6363 if (LHS.isInvalid() || RHS.isInvalid())
6367 if (compType.isNull() || !compType->isArithmeticType())
6368 return InvalidOperands(Loc, LHS, RHS);
6370 // Check for division by zero.
6372 RHS.get()->isNullPointerConstant(Context,
6373 Expr::NPC_ValueDependentIsNotNull))
6374 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6375 << RHS.get()->getSourceRange());
6380 QualType Sema::CheckRemainderOperands(
6381 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6382 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6384 if (LHS.get()->getType()->isVectorType() ||
6385 RHS.get()->getType()->isVectorType()) {
6386 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6387 RHS.get()->getType()->hasIntegerRepresentation())
6388 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6389 return InvalidOperands(Loc, LHS, RHS);
6392 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6393 if (LHS.isInvalid() || RHS.isInvalid())
6396 if (compType.isNull() || !compType->isIntegerType())
6397 return InvalidOperands(Loc, LHS, RHS);
6399 // Check for remainder by zero.
6400 if (RHS.get()->isNullPointerConstant(Context,
6401 Expr::NPC_ValueDependentIsNotNull))
6402 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6403 << RHS.get()->getSourceRange());
6408 /// \brief Diagnose invalid arithmetic on two void pointers.
6409 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6410 Expr *LHSExpr, Expr *RHSExpr) {
6411 S.Diag(Loc, S.getLangOpts().CPlusPlus
6412 ? diag::err_typecheck_pointer_arith_void_type
6413 : diag::ext_gnu_void_ptr)
6414 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6415 << RHSExpr->getSourceRange();
6418 /// \brief Diagnose invalid arithmetic on a void pointer.
6419 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6421 S.Diag(Loc, S.getLangOpts().CPlusPlus
6422 ? diag::err_typecheck_pointer_arith_void_type
6423 : diag::ext_gnu_void_ptr)
6424 << 0 /* one pointer */ << Pointer->getSourceRange();
6427 /// \brief Diagnose invalid arithmetic on two function pointers.
6428 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6429 Expr *LHS, Expr *RHS) {
6430 assert(LHS->getType()->isAnyPointerType());
6431 assert(RHS->getType()->isAnyPointerType());
6432 S.Diag(Loc, S.getLangOpts().CPlusPlus
6433 ? diag::err_typecheck_pointer_arith_function_type
6434 : diag::ext_gnu_ptr_func_arith)
6435 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6436 // We only show the second type if it differs from the first.
6437 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6439 << RHS->getType()->getPointeeType()
6440 << LHS->getSourceRange() << RHS->getSourceRange();
6443 /// \brief Diagnose invalid arithmetic on a function pointer.
6444 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6446 assert(Pointer->getType()->isAnyPointerType());
6447 S.Diag(Loc, S.getLangOpts().CPlusPlus
6448 ? diag::err_typecheck_pointer_arith_function_type
6449 : diag::ext_gnu_ptr_func_arith)
6450 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6451 << 0 /* one pointer, so only one type */
6452 << Pointer->getSourceRange();
6455 /// \brief Emit error if Operand is incomplete pointer type
6457 /// \returns True if pointer has incomplete type
6458 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6460 assert(Operand->getType()->isAnyPointerType() &&
6461 !Operand->getType()->isDependentType());
6462 QualType PointeeTy = Operand->getType()->getPointeeType();
6463 return S.RequireCompleteType(Loc, PointeeTy,
6464 diag::err_typecheck_arithmetic_incomplete_type,
6465 PointeeTy, Operand->getSourceRange());
6468 /// \brief Check the validity of an arithmetic pointer operand.
6470 /// If the operand has pointer type, this code will check for pointer types
6471 /// which are invalid in arithmetic operations. These will be diagnosed
6472 /// appropriately, including whether or not the use is supported as an
6475 /// \returns True when the operand is valid to use (even if as an extension).
6476 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6478 if (!Operand->getType()->isAnyPointerType()) return true;
6480 QualType PointeeTy = Operand->getType()->getPointeeType();
6481 if (PointeeTy->isVoidType()) {
6482 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6483 return !S.getLangOpts().CPlusPlus;
6485 if (PointeeTy->isFunctionType()) {
6486 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6487 return !S.getLangOpts().CPlusPlus;
6490 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6495 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6498 /// This routine will diagnose any invalid arithmetic on pointer operands much
6499 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6500 /// for emitting a single diagnostic even for operations where both LHS and RHS
6501 /// are (potentially problematic) pointers.
6503 /// \returns True when the operand is valid to use (even if as an extension).
6504 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6505 Expr *LHSExpr, Expr *RHSExpr) {
6506 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6507 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6508 if (!isLHSPointer && !isRHSPointer) return true;
6510 QualType LHSPointeeTy, RHSPointeeTy;
6511 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6512 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6514 // Check for arithmetic on pointers to incomplete types.
6515 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6516 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6517 if (isLHSVoidPtr || isRHSVoidPtr) {
6518 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6519 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6520 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6522 return !S.getLangOpts().CPlusPlus;
6525 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6526 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6527 if (isLHSFuncPtr || isRHSFuncPtr) {
6528 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6529 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6531 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6533 return !S.getLangOpts().CPlusPlus;
6536 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6538 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6544 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6546 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6547 Expr *LHSExpr, Expr *RHSExpr) {
6548 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6549 Expr* IndexExpr = RHSExpr;
6551 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6552 IndexExpr = LHSExpr;
6555 bool IsStringPlusInt = StrExpr &&
6556 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6557 if (!IsStringPlusInt)
6561 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6562 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6563 if (index.isNonNegative() &&
6564 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6565 index.isUnsigned()))
6569 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6570 Self.Diag(OpLoc, diag::warn_string_plus_int)
6571 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6573 // Only print a fixit for "str" + int, not for int + "str".
6574 if (IndexExpr == RHSExpr) {
6575 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6576 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6577 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6578 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6579 << FixItHint::CreateInsertion(EndLoc, "]");
6581 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6584 /// \brief Emit error when two pointers are incompatible.
6585 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6586 Expr *LHSExpr, Expr *RHSExpr) {
6587 assert(LHSExpr->getType()->isAnyPointerType());
6588 assert(RHSExpr->getType()->isAnyPointerType());
6589 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6590 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6591 << RHSExpr->getSourceRange();
6594 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6595 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6596 QualType* CompLHSTy) {
6597 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6599 if (LHS.get()->getType()->isVectorType() ||
6600 RHS.get()->getType()->isVectorType()) {
6601 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6602 if (CompLHSTy) *CompLHSTy = compType;
6606 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6607 if (LHS.isInvalid() || RHS.isInvalid())
6610 // Diagnose "string literal" '+' int.
6612 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6614 // handle the common case first (both operands are arithmetic).
6615 if (!compType.isNull() && compType->isArithmeticType()) {
6616 if (CompLHSTy) *CompLHSTy = compType;
6620 // Type-checking. Ultimately the pointer's going to be in PExp;
6621 // note that we bias towards the LHS being the pointer.
6622 Expr *PExp = LHS.get(), *IExp = RHS.get();
6625 if (PExp->getType()->isPointerType()) {
6626 isObjCPointer = false;
6627 } else if (PExp->getType()->isObjCObjectPointerType()) {
6628 isObjCPointer = true;
6630 std::swap(PExp, IExp);
6631 if (PExp->getType()->isPointerType()) {
6632 isObjCPointer = false;
6633 } else if (PExp->getType()->isObjCObjectPointerType()) {
6634 isObjCPointer = true;
6636 return InvalidOperands(Loc, LHS, RHS);
6639 assert(PExp->getType()->isAnyPointerType());
6641 if (!IExp->getType()->isIntegerType())
6642 return InvalidOperands(Loc, LHS, RHS);
6644 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6647 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
6650 // Check array bounds for pointer arithemtic
6651 CheckArrayAccess(PExp, IExp);
6654 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6655 if (LHSTy.isNull()) {
6656 LHSTy = LHS.get()->getType();
6657 if (LHSTy->isPromotableIntegerType())
6658 LHSTy = Context.getPromotedIntegerType(LHSTy);
6663 return PExp->getType();
6667 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6669 QualType* CompLHSTy) {
6670 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6672 if (LHS.get()->getType()->isVectorType() ||
6673 RHS.get()->getType()->isVectorType()) {
6674 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6675 if (CompLHSTy) *CompLHSTy = compType;
6679 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6680 if (LHS.isInvalid() || RHS.isInvalid())
6683 // Enforce type constraints: C99 6.5.6p3.
6685 // Handle the common case first (both operands are arithmetic).
6686 if (!compType.isNull() && compType->isArithmeticType()) {
6687 if (CompLHSTy) *CompLHSTy = compType;
6691 // Either ptr - int or ptr - ptr.
6692 if (LHS.get()->getType()->isAnyPointerType()) {
6693 QualType lpointee = LHS.get()->getType()->getPointeeType();
6695 // Diagnose bad cases where we step over interface counts.
6696 if (LHS.get()->getType()->isObjCObjectPointerType() &&
6697 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
6700 // The result type of a pointer-int computation is the pointer type.
6701 if (RHS.get()->getType()->isIntegerType()) {
6702 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
6705 // Check array bounds for pointer arithemtic
6706 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6707 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
6709 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6710 return LHS.get()->getType();
6713 // Handle pointer-pointer subtractions.
6714 if (const PointerType *RHSPTy
6715 = RHS.get()->getType()->getAs<PointerType>()) {
6716 QualType rpointee = RHSPTy->getPointeeType();
6718 if (getLangOpts().CPlusPlus) {
6719 // Pointee types must be the same: C++ [expr.add]
6720 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6721 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6724 // Pointee types must be compatible C99 6.5.6p3
6725 if (!Context.typesAreCompatible(
6726 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6727 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6728 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6733 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6734 LHS.get(), RHS.get()))
6737 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6738 return Context.getPointerDiffType();
6742 return InvalidOperands(Loc, LHS, RHS);
6745 static bool isScopedEnumerationType(QualType T) {
6746 if (const EnumType *ET = dyn_cast<EnumType>(T))
6747 return ET->getDecl()->isScoped();
6751 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
6752 SourceLocation Loc, unsigned Opc,
6754 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
6755 // so skip remaining warnings as we don't want to modify values within Sema.
6756 if (S.getLangOpts().OpenCL)
6760 // Check right/shifter operand
6761 if (RHS.get()->isValueDependent() ||
6762 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
6765 if (Right.isNegative()) {
6766 S.DiagRuntimeBehavior(Loc, RHS.get(),
6767 S.PDiag(diag::warn_shift_negative)
6768 << RHS.get()->getSourceRange());
6771 llvm::APInt LeftBits(Right.getBitWidth(),
6772 S.Context.getTypeSize(LHS.get()->getType()));
6773 if (Right.uge(LeftBits)) {
6774 S.DiagRuntimeBehavior(Loc, RHS.get(),
6775 S.PDiag(diag::warn_shift_gt_typewidth)
6776 << RHS.get()->getSourceRange());
6782 // When left shifting an ICE which is signed, we can check for overflow which
6783 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6784 // integers have defined behavior modulo one more than the maximum value
6785 // representable in the result type, so never warn for those.
6787 if (LHS.get()->isValueDependent() ||
6788 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6789 LHSType->hasUnsignedIntegerRepresentation())
6791 llvm::APInt ResultBits =
6792 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6793 if (LeftBits.uge(ResultBits))
6795 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6796 Result = Result.shl(Right);
6798 // Print the bit representation of the signed integer as an unsigned
6799 // hexadecimal number.
6800 SmallString<40> HexResult;
6801 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6803 // If we are only missing a sign bit, this is less likely to result in actual
6804 // bugs -- if the result is cast back to an unsigned type, it will have the
6805 // expected value. Thus we place this behind a different warning that can be
6806 // turned off separately if needed.
6807 if (LeftBits == ResultBits - 1) {
6808 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6809 << HexResult.str() << LHSType
6810 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6814 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6815 << HexResult.str() << Result.getMinSignedBits() << LHSType
6816 << Left.getBitWidth() << LHS.get()->getSourceRange()
6817 << RHS.get()->getSourceRange();
6821 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
6822 SourceLocation Loc, unsigned Opc,
6823 bool IsCompAssign) {
6824 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6826 // C99 6.5.7p2: Each of the operands shall have integer type.
6827 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6828 !RHS.get()->getType()->hasIntegerRepresentation())
6829 return InvalidOperands(Loc, LHS, RHS);
6831 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6832 // hasIntegerRepresentation() above instead of this.
6833 if (isScopedEnumerationType(LHS.get()->getType()) ||
6834 isScopedEnumerationType(RHS.get()->getType())) {
6835 return InvalidOperands(Loc, LHS, RHS);
6838 // Vector shifts promote their scalar inputs to vector type.
6839 if (LHS.get()->getType()->isVectorType() ||
6840 RHS.get()->getType()->isVectorType())
6841 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6843 // Shifts don't perform usual arithmetic conversions, they just do integer
6844 // promotions on each operand. C99 6.5.7p3
6846 // For the LHS, do usual unary conversions, but then reset them away
6847 // if this is a compound assignment.
6848 ExprResult OldLHS = LHS;
6849 LHS = UsualUnaryConversions(LHS.take());
6850 if (LHS.isInvalid())
6852 QualType LHSType = LHS.get()->getType();
6853 if (IsCompAssign) LHS = OldLHS;
6855 // The RHS is simpler.
6856 RHS = UsualUnaryConversions(RHS.take());
6857 if (RHS.isInvalid())
6860 // Sanity-check shift operands
6861 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
6863 // "The type of the result is that of the promoted left operand."
6867 static bool IsWithinTemplateSpecialization(Decl *D) {
6868 if (DeclContext *DC = D->getDeclContext()) {
6869 if (isa<ClassTemplateSpecializationDecl>(DC))
6871 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6872 return FD->isFunctionTemplateSpecialization();
6877 /// If two different enums are compared, raise a warning.
6878 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
6880 QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
6881 QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
6883 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6886 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6890 // Ignore anonymous enums.
6891 if (!LHSEnumType->getDecl()->getIdentifier())
6893 if (!RHSEnumType->getDecl()->getIdentifier())
6896 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6899 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6900 << LHSStrippedType << RHSStrippedType
6901 << LHS->getSourceRange() << RHS->getSourceRange();
6904 /// \brief Diagnose bad pointer comparisons.
6905 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6906 ExprResult &LHS, ExprResult &RHS,
6908 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
6909 : diag::ext_typecheck_comparison_of_distinct_pointers)
6910 << LHS.get()->getType() << RHS.get()->getType()
6911 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6914 /// \brief Returns false if the pointers are converted to a composite type,
6916 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
6917 ExprResult &LHS, ExprResult &RHS) {
6918 // C++ [expr.rel]p2:
6919 // [...] Pointer conversions (4.10) and qualification
6920 // conversions (4.4) are performed on pointer operands (or on
6921 // a pointer operand and a null pointer constant) to bring
6922 // them to their composite pointer type. [...]
6924 // C++ [expr.eq]p1 uses the same notion for (in)equality
6925 // comparisons of pointers.
6928 // In addition, pointers to members can be compared, or a pointer to
6929 // member and a null pointer constant. Pointer to member conversions
6930 // (4.11) and qualification conversions (4.4) are performed to bring
6931 // them to a common type. If one operand is a null pointer constant,
6932 // the common type is the type of the other operand. Otherwise, the
6933 // common type is a pointer to member type similar (4.4) to the type
6934 // of one of the operands, with a cv-qualification signature (4.4)
6935 // that is the union of the cv-qualification signatures of the operand
6938 QualType LHSType = LHS.get()->getType();
6939 QualType RHSType = RHS.get()->getType();
6940 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6941 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
6943 bool NonStandardCompositeType = false;
6944 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6945 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
6947 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
6951 if (NonStandardCompositeType)
6952 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6953 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6954 << RHS.get()->getSourceRange();
6956 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6957 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
6961 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6965 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6966 : diag::ext_typecheck_comparison_of_fptr_to_void)
6967 << LHS.get()->getType() << RHS.get()->getType()
6968 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6971 static bool isObjCObjectLiteral(ExprResult &E) {
6972 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
6973 case Stmt::ObjCArrayLiteralClass:
6974 case Stmt::ObjCDictionaryLiteralClass:
6975 case Stmt::ObjCStringLiteralClass:
6976 case Stmt::ObjCBoxedExprClass:
6979 // Note that ObjCBoolLiteral is NOT an object literal!
6984 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6985 const ObjCObjectPointerType *Type =
6986 LHS->getType()->getAs<ObjCObjectPointerType>();
6988 // If this is not actually an Objective-C object, bail out.
6992 // Get the LHS object's interface type.
6993 QualType InterfaceType = Type->getPointeeType();
6994 if (const ObjCObjectType *iQFaceTy =
6995 InterfaceType->getAsObjCQualifiedInterfaceType())
6996 InterfaceType = iQFaceTy->getBaseType();
6998 // If the RHS isn't an Objective-C object, bail out.
6999 if (!RHS->getType()->isObjCObjectPointerType())
7002 // Try to find the -isEqual: method.
7003 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7004 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7008 if (Type->isObjCIdType()) {
7009 // For 'id', just check the global pool.
7010 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7011 /*receiverId=*/true,
7015 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7023 QualType T = Method->param_begin()[0]->getType();
7024 if (!T->isObjCObjectPointerType())
7027 QualType R = Method->getResultType();
7028 if (!R->isScalarType())
7034 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7035 FromE = FromE->IgnoreParenImpCasts();
7036 switch (FromE->getStmtClass()) {
7039 case Stmt::ObjCStringLiteralClass:
7042 case Stmt::ObjCArrayLiteralClass:
7045 case Stmt::ObjCDictionaryLiteralClass:
7046 // "dictionary literal"
7047 return LK_Dictionary;
7048 case Stmt::BlockExprClass:
7050 case Stmt::ObjCBoxedExprClass: {
7051 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7052 switch (Inner->getStmtClass()) {
7053 case Stmt::IntegerLiteralClass:
7054 case Stmt::FloatingLiteralClass:
7055 case Stmt::CharacterLiteralClass:
7056 case Stmt::ObjCBoolLiteralExprClass:
7057 case Stmt::CXXBoolLiteralExprClass:
7058 // "numeric literal"
7060 case Stmt::ImplicitCastExprClass: {
7061 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7062 // Boolean literals can be represented by implicit casts.
7063 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7076 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7077 ExprResult &LHS, ExprResult &RHS,
7078 BinaryOperator::Opcode Opc){
7081 if (isObjCObjectLiteral(LHS)) {
7082 Literal = LHS.get();
7085 Literal = RHS.get();
7089 // Don't warn on comparisons against nil.
7090 Other = Other->IgnoreParenCasts();
7091 if (Other->isNullPointerConstant(S.getASTContext(),
7092 Expr::NPC_ValueDependentIsNotNull))
7095 // This should be kept in sync with warn_objc_literal_comparison.
7096 // LK_String should always be after the other literals, since it has its own
7098 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7099 assert(LiteralKind != Sema::LK_Block);
7100 if (LiteralKind == Sema::LK_None) {
7101 llvm_unreachable("Unknown Objective-C object literal kind");
7104 if (LiteralKind == Sema::LK_String)
7105 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7106 << Literal->getSourceRange();
7108 S.Diag(Loc, diag::warn_objc_literal_comparison)
7109 << LiteralKind << Literal->getSourceRange();
7111 if (BinaryOperator::isEqualityOp(Opc) &&
7112 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7113 SourceLocation Start = LHS.get()->getLocStart();
7114 SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7115 CharSourceRange OpRange =
7116 CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7118 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7119 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7120 << FixItHint::CreateReplacement(OpRange, " isEqual:")
7121 << FixItHint::CreateInsertion(End, "]");
7125 // C99 6.5.8, C++ [expr.rel]
7126 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7127 SourceLocation Loc, unsigned OpaqueOpc,
7128 bool IsRelational) {
7129 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7131 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7133 // Handle vector comparisons separately.
7134 if (LHS.get()->getType()->isVectorType() ||
7135 RHS.get()->getType()->isVectorType())
7136 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7138 QualType LHSType = LHS.get()->getType();
7139 QualType RHSType = RHS.get()->getType();
7141 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7142 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7144 checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7146 if (!LHSType->hasFloatingRepresentation() &&
7147 !(LHSType->isBlockPointerType() && IsRelational) &&
7148 !LHS.get()->getLocStart().isMacroID() &&
7149 !RHS.get()->getLocStart().isMacroID()) {
7150 // For non-floating point types, check for self-comparisons of the form
7151 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7152 // often indicate logic errors in the program.
7154 // NOTE: Don't warn about comparison expressions resulting from macro
7155 // expansion. Also don't warn about comparisons which are only self
7156 // comparisons within a template specialization. The warnings should catch
7157 // obvious cases in the definition of the template anyways. The idea is to
7158 // warn when the typed comparison operator will always evaluate to the same
7160 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
7161 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
7162 if (DRL->getDecl() == DRR->getDecl() &&
7163 !IsWithinTemplateSpecialization(DRL->getDecl())) {
7164 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7169 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
7170 !DRL->getDecl()->getType()->isReferenceType() &&
7171 !DRR->getDecl()->getType()->isReferenceType()) {
7172 // what is it always going to eval to?
7173 char always_evals_to;
7175 case BO_EQ: // e.g. array1 == array2
7176 always_evals_to = 0; // false
7178 case BO_NE: // e.g. array1 != array2
7179 always_evals_to = 1; // true
7182 // best we can say is 'a constant'
7183 always_evals_to = 2; // e.g. array1 <= array2
7186 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7188 << always_evals_to);
7193 if (isa<CastExpr>(LHSStripped))
7194 LHSStripped = LHSStripped->IgnoreParenCasts();
7195 if (isa<CastExpr>(RHSStripped))
7196 RHSStripped = RHSStripped->IgnoreParenCasts();
7198 // Warn about comparisons against a string constant (unless the other
7199 // operand is null), the user probably wants strcmp.
7200 Expr *literalString = 0;
7201 Expr *literalStringStripped = 0;
7202 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7203 !RHSStripped->isNullPointerConstant(Context,
7204 Expr::NPC_ValueDependentIsNull)) {
7205 literalString = LHS.get();
7206 literalStringStripped = LHSStripped;
7207 } else if ((isa<StringLiteral>(RHSStripped) ||
7208 isa<ObjCEncodeExpr>(RHSStripped)) &&
7209 !LHSStripped->isNullPointerConstant(Context,
7210 Expr::NPC_ValueDependentIsNull)) {
7211 literalString = RHS.get();
7212 literalStringStripped = RHSStripped;
7215 if (literalString) {
7216 std::string resultComparison;
7218 case BO_LT: resultComparison = ") < 0"; break;
7219 case BO_GT: resultComparison = ") > 0"; break;
7220 case BO_LE: resultComparison = ") <= 0"; break;
7221 case BO_GE: resultComparison = ") >= 0"; break;
7222 case BO_EQ: resultComparison = ") == 0"; break;
7223 case BO_NE: resultComparison = ") != 0"; break;
7224 default: llvm_unreachable("Invalid comparison operator");
7227 DiagRuntimeBehavior(Loc, 0,
7228 PDiag(diag::warn_stringcompare)
7229 << isa<ObjCEncodeExpr>(literalStringStripped)
7230 << literalString->getSourceRange());
7234 // C99 6.5.8p3 / C99 6.5.9p4
7235 if (LHS.get()->getType()->isArithmeticType() &&
7236 RHS.get()->getType()->isArithmeticType()) {
7237 UsualArithmeticConversions(LHS, RHS);
7238 if (LHS.isInvalid() || RHS.isInvalid())
7242 LHS = UsualUnaryConversions(LHS.take());
7243 if (LHS.isInvalid())
7246 RHS = UsualUnaryConversions(RHS.take());
7247 if (RHS.isInvalid())
7251 LHSType = LHS.get()->getType();
7252 RHSType = RHS.get()->getType();
7254 // The result of comparisons is 'bool' in C++, 'int' in C.
7255 QualType ResultTy = Context.getLogicalOperationType();
7258 if (LHSType->isRealType() && RHSType->isRealType())
7261 // Check for comparisons of floating point operands using != and ==.
7262 if (LHSType->hasFloatingRepresentation())
7263 CheckFloatComparison(Loc, LHS.get(), RHS.get());
7265 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7269 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7270 Expr::NPC_ValueDependentIsNull);
7271 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7272 Expr::NPC_ValueDependentIsNull);
7274 // All of the following pointer-related warnings are GCC extensions, except
7275 // when handling null pointer constants.
7276 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7277 QualType LCanPointeeTy =
7278 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7279 QualType RCanPointeeTy =
7280 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7282 if (getLangOpts().CPlusPlus) {
7283 if (LCanPointeeTy == RCanPointeeTy)
7285 if (!IsRelational &&
7286 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7287 // Valid unless comparison between non-null pointer and function pointer
7288 // This is a gcc extension compatibility comparison.
7289 // In a SFINAE context, we treat this as a hard error to maintain
7290 // conformance with the C++ standard.
7291 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7292 && !LHSIsNull && !RHSIsNull) {
7293 diagnoseFunctionPointerToVoidComparison(
7294 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
7296 if (isSFINAEContext())
7299 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7304 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7309 // C99 6.5.9p2 and C99 6.5.8p2
7310 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7311 RCanPointeeTy.getUnqualifiedType())) {
7312 // Valid unless a relational comparison of function pointers
7313 if (IsRelational && LCanPointeeTy->isFunctionType()) {
7314 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7315 << LHSType << RHSType << LHS.get()->getSourceRange()
7316 << RHS.get()->getSourceRange();
7318 } else if (!IsRelational &&
7319 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7320 // Valid unless comparison between non-null pointer and function pointer
7321 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7322 && !LHSIsNull && !RHSIsNull)
7323 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7327 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7329 if (LCanPointeeTy != RCanPointeeTy) {
7330 if (LHSIsNull && !RHSIsNull)
7331 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7333 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7338 if (getLangOpts().CPlusPlus) {
7339 // Comparison of nullptr_t with itself.
7340 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7343 // Comparison of pointers with null pointer constants and equality
7344 // comparisons of member pointers to null pointer constants.
7346 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7348 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7349 RHS = ImpCastExprToType(RHS.take(), LHSType,
7350 LHSType->isMemberPointerType()
7351 ? CK_NullToMemberPointer
7352 : CK_NullToPointer);
7356 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7358 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7359 LHS = ImpCastExprToType(LHS.take(), RHSType,
7360 RHSType->isMemberPointerType()
7361 ? CK_NullToMemberPointer
7362 : CK_NullToPointer);
7366 // Comparison of member pointers.
7367 if (!IsRelational &&
7368 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7369 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7375 // Handle scoped enumeration types specifically, since they don't promote
7377 if (LHS.get()->getType()->isEnumeralType() &&
7378 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7379 RHS.get()->getType()))
7383 // Handle block pointer types.
7384 if (!IsRelational && LHSType->isBlockPointerType() &&
7385 RHSType->isBlockPointerType()) {
7386 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7387 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7389 if (!LHSIsNull && !RHSIsNull &&
7390 !Context.typesAreCompatible(lpointee, rpointee)) {
7391 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7392 << LHSType << RHSType << LHS.get()->getSourceRange()
7393 << RHS.get()->getSourceRange();
7395 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7399 // Allow block pointers to be compared with null pointer constants.
7401 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7402 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7403 if (!LHSIsNull && !RHSIsNull) {
7404 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7405 ->getPointeeType()->isVoidType())
7406 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7407 ->getPointeeType()->isVoidType())))
7408 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7409 << LHSType << RHSType << LHS.get()->getSourceRange()
7410 << RHS.get()->getSourceRange();
7412 if (LHSIsNull && !RHSIsNull)
7413 LHS = ImpCastExprToType(LHS.take(), RHSType,
7414 RHSType->isPointerType() ? CK_BitCast
7415 : CK_AnyPointerToBlockPointerCast);
7417 RHS = ImpCastExprToType(RHS.take(), LHSType,
7418 LHSType->isPointerType() ? CK_BitCast
7419 : CK_AnyPointerToBlockPointerCast);
7423 if (LHSType->isObjCObjectPointerType() ||
7424 RHSType->isObjCObjectPointerType()) {
7425 const PointerType *LPT = LHSType->getAs<PointerType>();
7426 const PointerType *RPT = RHSType->getAs<PointerType>();
7428 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7429 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7431 if (!LPtrToVoid && !RPtrToVoid &&
7432 !Context.typesAreCompatible(LHSType, RHSType)) {
7433 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7436 if (LHSIsNull && !RHSIsNull)
7437 LHS = ImpCastExprToType(LHS.take(), RHSType,
7438 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7440 RHS = ImpCastExprToType(RHS.take(), LHSType,
7441 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7444 if (LHSType->isObjCObjectPointerType() &&
7445 RHSType->isObjCObjectPointerType()) {
7446 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7447 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7449 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7450 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7452 if (LHSIsNull && !RHSIsNull)
7453 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7455 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7459 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7460 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7461 unsigned DiagID = 0;
7462 bool isError = false;
7463 if (LangOpts.DebuggerSupport) {
7464 // Under a debugger, allow the comparison of pointers to integers,
7465 // since users tend to want to compare addresses.
7466 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
7467 (RHSIsNull && RHSType->isIntegerType())) {
7468 if (IsRelational && !getLangOpts().CPlusPlus)
7469 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7470 } else if (IsRelational && !getLangOpts().CPlusPlus)
7471 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7472 else if (getLangOpts().CPlusPlus) {
7473 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7476 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7480 << LHSType << RHSType << LHS.get()->getSourceRange()
7481 << RHS.get()->getSourceRange();
7486 if (LHSType->isIntegerType())
7487 LHS = ImpCastExprToType(LHS.take(), RHSType,
7488 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7490 RHS = ImpCastExprToType(RHS.take(), LHSType,
7491 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7495 // Handle block pointers.
7496 if (!IsRelational && RHSIsNull
7497 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7498 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
7501 if (!IsRelational && LHSIsNull
7502 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7503 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
7507 return InvalidOperands(Loc, LHS, RHS);
7511 // Return a signed type that is of identical size and number of elements.
7512 // For floating point vectors, return an integer type of identical size
7513 // and number of elements.
7514 QualType Sema::GetSignedVectorType(QualType V) {
7515 const VectorType *VTy = V->getAs<VectorType>();
7516 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7517 if (TypeSize == Context.getTypeSize(Context.CharTy))
7518 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7519 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7520 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7521 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7522 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7523 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7524 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7525 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7526 "Unhandled vector element size in vector compare");
7527 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7530 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7531 /// operates on extended vector types. Instead of producing an IntTy result,
7532 /// like a scalar comparison, a vector comparison produces a vector of integer
7534 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7536 bool IsRelational) {
7537 // Check to make sure we're operating on vectors of the same type and width,
7538 // Allowing one side to be a scalar of element type.
7539 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
7543 QualType LHSType = LHS.get()->getType();
7545 // If AltiVec, the comparison results in a numeric type, i.e.
7546 // bool for C++, int for C
7547 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7548 return Context.getLogicalOperationType();
7550 // For non-floating point types, check for self-comparisons of the form
7551 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7552 // often indicate logic errors in the program.
7553 if (!LHSType->hasFloatingRepresentation()) {
7554 if (DeclRefExpr* DRL
7555 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7556 if (DeclRefExpr* DRR
7557 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
7558 if (DRL->getDecl() == DRR->getDecl())
7559 DiagRuntimeBehavior(Loc, 0,
7560 PDiag(diag::warn_comparison_always)
7562 << 2 // "a constant"
7566 // Check for comparisons of floating point operands using != and ==.
7567 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
7568 assert (RHS.get()->getType()->hasFloatingRepresentation());
7569 CheckFloatComparison(Loc, LHS.get(), RHS.get());
7572 // Return a signed type for the vector.
7573 return GetSignedVectorType(LHSType);
7576 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7577 SourceLocation Loc) {
7578 // Ensure that either both operands are of the same vector type, or
7579 // one operand is of a vector type and the other is of its element type.
7580 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7582 return InvalidOperands(Loc, LHS, RHS);
7583 if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
7584 vType->hasFloatingRepresentation())
7585 return InvalidOperands(Loc, LHS, RHS);
7587 return GetSignedVectorType(LHS.get()->getType());
7590 inline QualType Sema::CheckBitwiseOperands(
7591 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7592 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7594 if (LHS.get()->getType()->isVectorType() ||
7595 RHS.get()->getType()->isVectorType()) {
7596 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7597 RHS.get()->getType()->hasIntegerRepresentation())
7598 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7600 return InvalidOperands(Loc, LHS, RHS);
7603 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7604 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
7606 if (LHSResult.isInvalid() || RHSResult.isInvalid())
7608 LHS = LHSResult.take();
7609 RHS = RHSResult.take();
7611 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
7613 return InvalidOperands(Loc, LHS, RHS);
7616 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7617 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
7619 // Check vector operands differently.
7620 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7621 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7623 // Diagnose cases where the user write a logical and/or but probably meant a
7624 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7626 if (LHS.get()->getType()->isIntegerType() &&
7627 !LHS.get()->getType()->isBooleanType() &&
7628 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
7629 // Don't warn in macros or template instantiations.
7630 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
7631 // If the RHS can be constant folded, and if it constant folds to something
7632 // that isn't 0 or 1 (which indicate a potential logical operation that
7633 // happened to fold to true/false) then warn.
7634 // Parens on the RHS are ignored.
7635 llvm::APSInt Result;
7636 if (RHS.get()->EvaluateAsInt(Result, Context))
7637 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
7638 (Result != 0 && Result != 1)) {
7639 Diag(Loc, diag::warn_logical_instead_of_bitwise)
7640 << RHS.get()->getSourceRange()
7641 << (Opc == BO_LAnd ? "&&" : "||");
7642 // Suggest replacing the logical operator with the bitwise version
7643 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7644 << (Opc == BO_LAnd ? "&" : "|")
7645 << FixItHint::CreateReplacement(SourceRange(
7646 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
7648 Opc == BO_LAnd ? "&" : "|");
7650 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7651 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7652 << FixItHint::CreateRemoval(
7654 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
7655 0, getSourceManager(),
7657 RHS.get()->getLocEnd()));
7661 if (!Context.getLangOpts().CPlusPlus) {
7662 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
7663 // not operate on the built-in scalar and vector float types.
7664 if (Context.getLangOpts().OpenCL &&
7665 Context.getLangOpts().OpenCLVersion < 120) {
7666 if (LHS.get()->getType()->isFloatingType() ||
7667 RHS.get()->getType()->isFloatingType())
7668 return InvalidOperands(Loc, LHS, RHS);
7671 LHS = UsualUnaryConversions(LHS.take());
7672 if (LHS.isInvalid())
7675 RHS = UsualUnaryConversions(RHS.take());
7676 if (RHS.isInvalid())
7679 if (!LHS.get()->getType()->isScalarType() ||
7680 !RHS.get()->getType()->isScalarType())
7681 return InvalidOperands(Loc, LHS, RHS);
7683 return Context.IntTy;
7686 // The following is safe because we only use this method for
7687 // non-overloadable operands.
7689 // C++ [expr.log.and]p1
7690 // C++ [expr.log.or]p1
7691 // The operands are both contextually converted to type bool.
7692 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7693 if (LHSRes.isInvalid())
7694 return InvalidOperands(Loc, LHS, RHS);
7697 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7698 if (RHSRes.isInvalid())
7699 return InvalidOperands(Loc, LHS, RHS);
7702 // C++ [expr.log.and]p2
7703 // C++ [expr.log.or]p2
7704 // The result is a bool.
7705 return Context.BoolTy;
7708 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7709 /// is a read-only property; return true if so. A readonly property expression
7710 /// depends on various declarations and thus must be treated specially.
7712 static bool IsReadonlyProperty(Expr *E, Sema &S) {
7713 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7714 if (!PropExpr) return false;
7715 if (PropExpr->isImplicitProperty()) return false;
7717 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7718 QualType BaseType = PropExpr->isSuperReceiver() ?
7719 PropExpr->getSuperReceiverType() :
7720 PropExpr->getBase()->getType();
7722 if (const ObjCObjectPointerType *OPT =
7723 BaseType->getAsObjCInterfacePointerType())
7724 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7725 if (S.isPropertyReadonly(PDecl, IFace))
7730 static bool IsReadonlyMessage(Expr *E, Sema &S) {
7731 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7732 if (!ME) return false;
7733 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7734 ObjCMessageExpr *Base =
7735 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7736 if (!Base) return false;
7737 return Base->getMethodDecl() != 0;
7740 /// Is the given expression (which must be 'const') a reference to a
7741 /// variable which was originally non-const, but which has become
7742 /// 'const' due to being captured within a block?
7743 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7744 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7745 assert(E->isLValue() && E->getType().isConstQualified());
7746 E = E->IgnoreParens();
7748 // Must be a reference to a declaration from an enclosing scope.
7749 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7750 if (!DRE) return NCCK_None;
7751 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7753 // The declaration must be a variable which is not declared 'const'.
7754 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7755 if (!var) return NCCK_None;
7756 if (var->getType().isConstQualified()) return NCCK_None;
7757 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7759 // Decide whether the first capture was for a block or a lambda.
7760 DeclContext *DC = S.CurContext;
7761 while (DC->getParent() != var->getDeclContext())
7762 DC = DC->getParent();
7763 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7766 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7767 /// emit an error and return true. If so, return false.
7768 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7769 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
7770 SourceLocation OrigLoc = Loc;
7771 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7773 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7774 IsLV = Expr::MLV_ReadonlyProperty;
7775 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7776 IsLV = Expr::MLV_InvalidMessageExpression;
7777 if (IsLV == Expr::MLV_Valid)
7781 bool NeedType = false;
7782 switch (IsLV) { // C99 6.5.16p2
7783 case Expr::MLV_ConstQualified:
7784 Diag = diag::err_typecheck_assign_const;
7786 // Use a specialized diagnostic when we're assigning to an object
7787 // from an enclosing function or block.
7788 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7789 if (NCCK == NCCK_Block)
7790 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7792 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7796 // In ARC, use some specialized diagnostics for occasions where we
7797 // infer 'const'. These are always pseudo-strong variables.
7798 if (S.getLangOpts().ObjCAutoRefCount) {
7799 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7800 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7801 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7803 // Use the normal diagnostic if it's pseudo-__strong but the
7804 // user actually wrote 'const'.
7805 if (var->isARCPseudoStrong() &&
7806 (!var->getTypeSourceInfo() ||
7807 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7808 // There are two pseudo-strong cases:
7810 ObjCMethodDecl *method = S.getCurMethodDecl();
7811 if (method && var == method->getSelfDecl())
7812 Diag = method->isClassMethod()
7813 ? diag::err_typecheck_arc_assign_self_class_method
7814 : diag::err_typecheck_arc_assign_self;
7816 // - fast enumeration variables
7818 Diag = diag::err_typecheck_arr_assign_enumeration;
7822 Assign = SourceRange(OrigLoc, OrigLoc);
7823 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7824 // We need to preserve the AST regardless, so migration tool
7832 case Expr::MLV_ArrayType:
7833 case Expr::MLV_ArrayTemporary:
7834 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7837 case Expr::MLV_NotObjectType:
7838 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7841 case Expr::MLV_LValueCast:
7842 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7844 case Expr::MLV_Valid:
7845 llvm_unreachable("did not take early return for MLV_Valid");
7846 case Expr::MLV_InvalidExpression:
7847 case Expr::MLV_MemberFunction:
7848 case Expr::MLV_ClassTemporary:
7849 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7851 case Expr::MLV_IncompleteType:
7852 case Expr::MLV_IncompleteVoidType:
7853 return S.RequireCompleteType(Loc, E->getType(),
7854 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
7855 case Expr::MLV_DuplicateVectorComponents:
7856 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7858 case Expr::MLV_ReadonlyProperty:
7859 case Expr::MLV_NoSetterProperty:
7860 llvm_unreachable("readonly properties should be processed differently");
7861 case Expr::MLV_InvalidMessageExpression:
7862 Diag = diag::error_readonly_message_assignment;
7864 case Expr::MLV_SubObjCPropertySetting:
7865 Diag = diag::error_no_subobject_property_setting;
7871 Assign = SourceRange(OrigLoc, OrigLoc);
7873 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7875 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7879 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7883 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7884 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7885 if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7886 if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
7887 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
7890 // Objective-C instance variables
7891 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7892 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7893 if (OL && OR && OL->getDecl() == OR->getDecl()) {
7894 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7895 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7896 if (RL && RR && RL->getDecl() == RR->getDecl())
7897 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
7902 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
7904 QualType CompoundType) {
7905 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7907 // Verify that LHS is a modifiable lvalue, and emit error if not.
7908 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
7911 QualType LHSType = LHSExpr->getType();
7912 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7914 AssignConvertType ConvTy;
7915 if (CompoundType.isNull()) {
7916 Expr *RHSCheck = RHS.get();
7918 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
7920 QualType LHSTy(LHSType);
7921 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7922 if (RHS.isInvalid())
7924 // Special case of NSObject attributes on c-style pointer types.
7925 if (ConvTy == IncompatiblePointer &&
7926 ((Context.isObjCNSObjectType(LHSType) &&
7927 RHSType->isObjCObjectPointerType()) ||
7928 (Context.isObjCNSObjectType(RHSType) &&
7929 LHSType->isObjCObjectPointerType())))
7930 ConvTy = Compatible;
7932 if (ConvTy == Compatible &&
7933 LHSType->isObjCObjectType())
7934 Diag(Loc, diag::err_objc_object_assignment)
7937 // If the RHS is a unary plus or minus, check to see if they = and + are
7938 // right next to each other. If so, the user may have typo'd "x =+ 4"
7939 // instead of "x += 4".
7940 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7941 RHSCheck = ICE->getSubExpr();
7942 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7943 if ((UO->getOpcode() == UO_Plus ||
7944 UO->getOpcode() == UO_Minus) &&
7945 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7946 // Only if the two operators are exactly adjacent.
7947 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
7948 // And there is a space or other character before the subexpr of the
7949 // unary +/-. We don't want to warn on "x=-1".
7950 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7951 UO->getSubExpr()->getLocStart().isFileID()) {
7952 Diag(Loc, diag::warn_not_compound_assign)
7953 << (UO->getOpcode() == UO_Plus ? "+" : "-")
7954 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7958 if (ConvTy == Compatible) {
7959 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7960 // Warn about retain cycles where a block captures the LHS, but
7961 // not if the LHS is a simple variable into which the block is
7962 // being stored...unless that variable can be captured by reference!
7963 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7964 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7965 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7966 checkRetainCycles(LHSExpr, RHS.get());
7968 // It is safe to assign a weak reference into a strong variable.
7969 // Although this code can still have problems:
7970 // id x = self.weakProp;
7971 // id y = self.weakProp;
7972 // we do not warn to warn spuriously when 'x' and 'y' are on separate
7973 // paths through the function. This should be revisited if
7974 // -Wrepeated-use-of-weak is made flow-sensitive.
7975 DiagnosticsEngine::Level Level =
7976 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7977 RHS.get()->getLocStart());
7978 if (Level != DiagnosticsEngine::Ignored)
7979 getCurFunction()->markSafeWeakUse(RHS.get());
7981 } else if (getLangOpts().ObjCAutoRefCount) {
7982 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
7986 // Compound assignment "x += y"
7987 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7990 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7991 RHS.get(), AA_Assigning))
7994 CheckForNullPointerDereference(*this, LHSExpr);
7996 // C99 6.5.16p3: The type of an assignment expression is the type of the
7997 // left operand unless the left operand has qualified type, in which case
7998 // it is the unqualified version of the type of the left operand.
7999 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8000 // is converted to the type of the assignment expression (above).
8001 // C++ 5.17p1: the type of the assignment expression is that of its left
8003 return (getLangOpts().CPlusPlus
8004 ? LHSType : LHSType.getUnqualifiedType());
8008 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8009 SourceLocation Loc) {
8010 LHS = S.CheckPlaceholderExpr(LHS.take());
8011 RHS = S.CheckPlaceholderExpr(RHS.take());
8012 if (LHS.isInvalid() || RHS.isInvalid())
8015 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8016 // operands, but not unary promotions.
8017 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8019 // So we treat the LHS as a ignored value, and in C++ we allow the
8020 // containing site to determine what should be done with the RHS.
8021 LHS = S.IgnoredValueConversions(LHS.take());
8022 if (LHS.isInvalid())
8025 S.DiagnoseUnusedExprResult(LHS.get());
8027 if (!S.getLangOpts().CPlusPlus) {
8028 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8029 if (RHS.isInvalid())
8031 if (!RHS.get()->getType()->isVoidType())
8032 S.RequireCompleteType(Loc, RHS.get()->getType(),
8033 diag::err_incomplete_type);
8036 return RHS.get()->getType();
8039 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8040 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8041 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8043 SourceLocation OpLoc,
8044 bool IsInc, bool IsPrefix) {
8045 if (Op->isTypeDependent())
8046 return S.Context.DependentTy;
8048 QualType ResType = Op->getType();
8049 // Atomic types can be used for increment / decrement where the non-atomic
8050 // versions can, so ignore the _Atomic() specifier for the purpose of
8052 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8053 ResType = ResAtomicType->getValueType();
8055 assert(!ResType.isNull() && "no type for increment/decrement expression");
8057 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8058 // Decrement of bool is not allowed.
8060 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8063 // Increment of bool sets it to true, but is deprecated.
8064 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8065 } else if (ResType->isRealType()) {
8067 } else if (ResType->isPointerType()) {
8068 // C99 6.5.2.4p2, 6.5.6p2
8069 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8071 } else if (ResType->isObjCObjectPointerType()) {
8072 // On modern runtimes, ObjC pointer arithmetic is forbidden.
8073 // Otherwise, we just need a complete type.
8074 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8075 checkArithmeticOnObjCPointer(S, OpLoc, Op))
8077 } else if (ResType->isAnyComplexType()) {
8078 // C99 does not support ++/-- on complex types, we allow as an extension.
8079 S.Diag(OpLoc, diag::ext_integer_increment_complex)
8080 << ResType << Op->getSourceRange();
8081 } else if (ResType->isPlaceholderType()) {
8082 ExprResult PR = S.CheckPlaceholderExpr(Op);
8083 if (PR.isInvalid()) return QualType();
8084 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8086 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8087 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8089 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8090 << ResType << int(IsInc) << Op->getSourceRange();
8093 // At this point, we know we have a real, complex or pointer type.
8094 // Now make sure the operand is a modifiable lvalue.
8095 if (CheckForModifiableLvalue(Op, OpLoc, S))
8097 // In C++, a prefix increment is the same type as the operand. Otherwise
8098 // (in C or with postfix), the increment is the unqualified type of the
8100 if (IsPrefix && S.getLangOpts().CPlusPlus) {
8105 return ResType.getUnqualifiedType();
8110 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8111 /// This routine allows us to typecheck complex/recursive expressions
8112 /// where the declaration is needed for type checking. We only need to
8113 /// handle cases when the expression references a function designator
8114 /// or is an lvalue. Here are some examples:
8116 /// - &*****f => f for f a function designator.
8118 /// - &s.zz[1].yy -> s, if zz is an array
8119 /// - *(x + 1) -> x, if x is an array
8120 /// - &"123"[2] -> 0
8121 /// - & __real__ x -> x
8122 static ValueDecl *getPrimaryDecl(Expr *E) {
8123 switch (E->getStmtClass()) {
8124 case Stmt::DeclRefExprClass:
8125 return cast<DeclRefExpr>(E)->getDecl();
8126 case Stmt::MemberExprClass:
8127 // If this is an arrow operator, the address is an offset from
8128 // the base's value, so the object the base refers to is
8130 if (cast<MemberExpr>(E)->isArrow())
8132 // Otherwise, the expression refers to a part of the base
8133 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8134 case Stmt::ArraySubscriptExprClass: {
8135 // FIXME: This code shouldn't be necessary! We should catch the implicit
8136 // promotion of register arrays earlier.
8137 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8138 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8139 if (ICE->getSubExpr()->getType()->isArrayType())
8140 return getPrimaryDecl(ICE->getSubExpr());
8144 case Stmt::UnaryOperatorClass: {
8145 UnaryOperator *UO = cast<UnaryOperator>(E);
8147 switch(UO->getOpcode()) {
8151 return getPrimaryDecl(UO->getSubExpr());
8156 case Stmt::ParenExprClass:
8157 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8158 case Stmt::ImplicitCastExprClass:
8159 // If the result of an implicit cast is an l-value, we care about
8160 // the sub-expression; otherwise, the result here doesn't matter.
8161 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8170 AO_Vector_Element = 1,
8171 AO_Property_Expansion = 2,
8172 AO_Register_Variable = 3,
8176 /// \brief Diagnose invalid operand for address of operations.
8178 /// \param Type The type of operand which cannot have its address taken.
8179 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8180 Expr *E, unsigned Type) {
8181 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8184 /// CheckAddressOfOperand - The operand of & must be either a function
8185 /// designator or an lvalue designating an object. If it is an lvalue, the
8186 /// object cannot be declared with storage class register or be a bit field.
8187 /// Note: The usual conversions are *not* applied to the operand of the &
8188 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8189 /// In C++, the operand might be an overloaded function name, in which case
8190 /// we allow the '&' but retain the overloaded-function type.
8191 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
8192 SourceLocation OpLoc) {
8193 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8194 if (PTy->getKind() == BuiltinType::Overload) {
8195 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
8196 assert(cast<UnaryOperator>(OrigOp.get()->IgnoreParens())->getOpcode()
8198 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8199 << OrigOp.get()->getSourceRange();
8203 return S.Context.OverloadTy;
8206 if (PTy->getKind() == BuiltinType::UnknownAny)
8207 return S.Context.UnknownAnyTy;
8209 if (PTy->getKind() == BuiltinType::BoundMember) {
8210 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8211 << OrigOp.get()->getSourceRange();
8215 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8216 if (OrigOp.isInvalid()) return QualType();
8219 if (OrigOp.get()->isTypeDependent())
8220 return S.Context.DependentTy;
8222 assert(!OrigOp.get()->getType()->isPlaceholderType());
8224 // Make sure to ignore parentheses in subsequent checks
8225 Expr *op = OrigOp.get()->IgnoreParens();
8227 if (S.getLangOpts().C99) {
8228 // Implement C99-only parts of addressof rules.
8229 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8230 if (uOp->getOpcode() == UO_Deref)
8231 // Per C99 6.5.3.2, the address of a deref always returns a valid result
8232 // (assuming the deref expression is valid).
8233 return uOp->getSubExpr()->getType();
8235 // Technically, there should be a check for array subscript
8236 // expressions here, but the result of one is always an lvalue anyway.
8238 ValueDecl *dcl = getPrimaryDecl(op);
8239 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
8240 unsigned AddressOfError = AO_No_Error;
8242 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8243 bool sfinae = (bool)S.isSFINAEContext();
8244 S.Diag(OpLoc, S.isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8245 : diag::ext_typecheck_addrof_temporary)
8246 << op->getType() << op->getSourceRange();
8249 } else if (isa<ObjCSelectorExpr>(op)) {
8250 return S.Context.getPointerType(op->getType());
8251 } else if (lval == Expr::LV_MemberFunction) {
8252 // If it's an instance method, make a member pointer.
8253 // The expression must have exactly the form &A::foo.
8255 // If the underlying expression isn't a decl ref, give up.
8256 if (!isa<DeclRefExpr>(op)) {
8257 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8258 << OrigOp.get()->getSourceRange();
8261 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8262 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8264 // The id-expression was parenthesized.
8265 if (OrigOp.get() != DRE) {
8266 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
8267 << OrigOp.get()->getSourceRange();
8269 // The method was named without a qualifier.
8270 } else if (!DRE->getQualifier()) {
8271 if (MD->getParent()->getName().empty())
8272 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8273 << op->getSourceRange();
8275 SmallString<32> Str;
8276 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8277 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8278 << op->getSourceRange()
8279 << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8283 return S.Context.getMemberPointerType(op->getType(),
8284 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
8285 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8287 // The operand must be either an l-value or a function designator
8288 if (!op->getType()->isFunctionType()) {
8289 // Use a special diagnostic for loads from property references.
8290 if (isa<PseudoObjectExpr>(op)) {
8291 AddressOfError = AO_Property_Expansion;
8293 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8294 << op->getType() << op->getSourceRange();
8298 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8299 // The operand cannot be a bit-field
8300 AddressOfError = AO_Bit_Field;
8301 } else if (op->getObjectKind() == OK_VectorComponent) {
8302 // The operand cannot be an element of a vector
8303 AddressOfError = AO_Vector_Element;
8304 } else if (dcl) { // C99 6.5.3.2p1
8305 // We have an lvalue with a decl. Make sure the decl is not declared
8306 // with the register storage-class specifier.
8307 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8308 // in C++ it is not error to take address of a register
8309 // variable (c++03 7.1.1P3)
8310 if (vd->getStorageClass() == SC_Register &&
8311 !S.getLangOpts().CPlusPlus) {
8312 AddressOfError = AO_Register_Variable;
8314 } else if (isa<FunctionTemplateDecl>(dcl)) {
8315 return S.Context.OverloadTy;
8316 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8317 // Okay: we can take the address of a field.
8318 // Could be a pointer to member, though, if there is an explicit
8319 // scope qualifier for the class.
8320 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8321 DeclContext *Ctx = dcl->getDeclContext();
8322 if (Ctx && Ctx->isRecord()) {
8323 if (dcl->getType()->isReferenceType()) {
8325 diag::err_cannot_form_pointer_to_member_of_reference_type)
8326 << dcl->getDeclName() << dcl->getType();
8330 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8331 Ctx = Ctx->getParent();
8332 return S.Context.getMemberPointerType(op->getType(),
8333 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8336 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8337 llvm_unreachable("Unknown/unexpected decl type");
8340 if (AddressOfError != AO_No_Error) {
8341 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8345 if (lval == Expr::LV_IncompleteVoidType) {
8346 // Taking the address of a void variable is technically illegal, but we
8347 // allow it in cases which are otherwise valid.
8348 // Example: "extern void x; void* y = &x;".
8349 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8352 // If the operand has type "type", the result has type "pointer to type".
8353 if (op->getType()->isObjCObjectType())
8354 return S.Context.getObjCObjectPointerType(op->getType());
8355 return S.Context.getPointerType(op->getType());
8358 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8359 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8360 SourceLocation OpLoc) {
8361 if (Op->isTypeDependent())
8362 return S.Context.DependentTy;
8364 ExprResult ConvResult = S.UsualUnaryConversions(Op);
8365 if (ConvResult.isInvalid())
8367 Op = ConvResult.take();
8368 QualType OpTy = Op->getType();
8371 if (isa<CXXReinterpretCastExpr>(Op)) {
8372 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8373 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8374 Op->getSourceRange());
8377 // Note that per both C89 and C99, indirection is always legal, even if OpTy
8378 // is an incomplete type or void. It would be possible to warn about
8379 // dereferencing a void pointer, but it's completely well-defined, and such a
8380 // warning is unlikely to catch any mistakes.
8381 if (const PointerType *PT = OpTy->getAs<PointerType>())
8382 Result = PT->getPointeeType();
8383 else if (const ObjCObjectPointerType *OPT =
8384 OpTy->getAs<ObjCObjectPointerType>())
8385 Result = OPT->getPointeeType();
8387 ExprResult PR = S.CheckPlaceholderExpr(Op);
8388 if (PR.isInvalid()) return QualType();
8389 if (PR.take() != Op)
8390 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8393 if (Result.isNull()) {
8394 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8395 << OpTy << Op->getSourceRange();
8399 // Dereferences are usually l-values...
8402 // ...except that certain expressions are never l-values in C.
8403 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8409 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8410 tok::TokenKind Kind) {
8411 BinaryOperatorKind Opc;
8413 default: llvm_unreachable("Unknown binop!");
8414 case tok::periodstar: Opc = BO_PtrMemD; break;
8415 case tok::arrowstar: Opc = BO_PtrMemI; break;
8416 case tok::star: Opc = BO_Mul; break;
8417 case tok::slash: Opc = BO_Div; break;
8418 case tok::percent: Opc = BO_Rem; break;
8419 case tok::plus: Opc = BO_Add; break;
8420 case tok::minus: Opc = BO_Sub; break;
8421 case tok::lessless: Opc = BO_Shl; break;
8422 case tok::greatergreater: Opc = BO_Shr; break;
8423 case tok::lessequal: Opc = BO_LE; break;
8424 case tok::less: Opc = BO_LT; break;
8425 case tok::greaterequal: Opc = BO_GE; break;
8426 case tok::greater: Opc = BO_GT; break;
8427 case tok::exclaimequal: Opc = BO_NE; break;
8428 case tok::equalequal: Opc = BO_EQ; break;
8429 case tok::amp: Opc = BO_And; break;
8430 case tok::caret: Opc = BO_Xor; break;
8431 case tok::pipe: Opc = BO_Or; break;
8432 case tok::ampamp: Opc = BO_LAnd; break;
8433 case tok::pipepipe: Opc = BO_LOr; break;
8434 case tok::equal: Opc = BO_Assign; break;
8435 case tok::starequal: Opc = BO_MulAssign; break;
8436 case tok::slashequal: Opc = BO_DivAssign; break;
8437 case tok::percentequal: Opc = BO_RemAssign; break;
8438 case tok::plusequal: Opc = BO_AddAssign; break;
8439 case tok::minusequal: Opc = BO_SubAssign; break;
8440 case tok::lesslessequal: Opc = BO_ShlAssign; break;
8441 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8442 case tok::ampequal: Opc = BO_AndAssign; break;
8443 case tok::caretequal: Opc = BO_XorAssign; break;
8444 case tok::pipeequal: Opc = BO_OrAssign; break;
8445 case tok::comma: Opc = BO_Comma; break;
8450 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8451 tok::TokenKind Kind) {
8452 UnaryOperatorKind Opc;
8454 default: llvm_unreachable("Unknown unary op!");
8455 case tok::plusplus: Opc = UO_PreInc; break;
8456 case tok::minusminus: Opc = UO_PreDec; break;
8457 case tok::amp: Opc = UO_AddrOf; break;
8458 case tok::star: Opc = UO_Deref; break;
8459 case tok::plus: Opc = UO_Plus; break;
8460 case tok::minus: Opc = UO_Minus; break;
8461 case tok::tilde: Opc = UO_Not; break;
8462 case tok::exclaim: Opc = UO_LNot; break;
8463 case tok::kw___real: Opc = UO_Real; break;
8464 case tok::kw___imag: Opc = UO_Imag; break;
8465 case tok::kw___extension__: Opc = UO_Extension; break;
8470 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8471 /// This warning is only emitted for builtin assignment operations. It is also
8472 /// suppressed in the event of macro expansions.
8473 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8474 SourceLocation OpLoc) {
8475 if (!S.ActiveTemplateInstantiations.empty())
8477 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8479 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8480 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8481 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8482 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8483 if (!LHSDeclRef || !RHSDeclRef ||
8484 LHSDeclRef->getLocation().isMacroID() ||
8485 RHSDeclRef->getLocation().isMacroID())
8487 const ValueDecl *LHSDecl =
8488 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8489 const ValueDecl *RHSDecl =
8490 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8491 if (LHSDecl != RHSDecl)
8493 if (LHSDecl->getType().isVolatileQualified())
8495 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
8496 if (RefTy->getPointeeType().isVolatileQualified())
8499 S.Diag(OpLoc, diag::warn_self_assignment)
8500 << LHSDeclRef->getType()
8501 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8504 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
8505 /// operator @p Opc at location @c TokLoc. This routine only supports
8506 /// built-in operations; ActOnBinOp handles overloaded operators.
8507 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8508 BinaryOperatorKind Opc,
8509 Expr *LHSExpr, Expr *RHSExpr) {
8510 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
8511 // The syntax only allows initializer lists on the RHS of assignment,
8512 // so we don't need to worry about accepting invalid code for
8513 // non-assignment operators.
8515 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8516 // of x = {} is x = T().
8517 InitializationKind Kind =
8518 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8519 InitializedEntity Entity =
8520 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8521 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8522 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
8523 if (Init.isInvalid())
8525 RHSExpr = Init.take();
8528 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
8529 QualType ResultTy; // Result type of the binary operator.
8530 // The following two variables are used for compound assignment operators
8531 QualType CompLHSTy; // Type of LHS after promotions for computation
8532 QualType CompResultTy; // Type of computation result
8533 ExprValueKind VK = VK_RValue;
8534 ExprObjectKind OK = OK_Ordinary;
8538 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
8539 if (getLangOpts().CPlusPlus &&
8540 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8541 VK = LHS.get()->getValueKind();
8542 OK = LHS.get()->getObjectKind();
8544 if (!ResultTy.isNull())
8545 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
8549 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
8554 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
8558 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
8561 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
8564 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
8568 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
8574 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
8578 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
8583 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
8587 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
8591 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
8592 Opc == BO_DivAssign);
8593 CompLHSTy = CompResultTy;
8594 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8595 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8598 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
8599 CompLHSTy = CompResultTy;
8600 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8601 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8604 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
8605 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8606 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8609 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8610 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8611 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8615 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
8616 CompLHSTy = CompResultTy;
8617 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8618 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8623 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
8624 CompLHSTy = CompResultTy;
8625 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8626 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8629 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
8630 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
8631 VK = RHS.get()->getValueKind();
8632 OK = RHS.get()->getObjectKind();
8636 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
8639 // Check for array bounds violations for both sides of the BinaryOperator
8640 CheckArrayAccess(LHS.get());
8641 CheckArrayAccess(RHS.get());
8643 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
8644 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
8645 &Context.Idents.get("object_setClass"),
8646 SourceLocation(), LookupOrdinaryName);
8647 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
8648 SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
8649 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
8650 FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
8651 FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
8652 FixItHint::CreateInsertion(RHSLocEnd, ")");
8655 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
8657 else if (const ObjCIvarRefExpr *OIRE =
8658 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
8659 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
8661 if (CompResultTy.isNull())
8662 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
8663 ResultTy, VK, OK, OpLoc,
8664 FPFeatures.fp_contract));
8665 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
8668 OK = LHS.get()->getObjectKind();
8670 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
8671 ResultTy, VK, OK, CompLHSTy,
8672 CompResultTy, OpLoc,
8673 FPFeatures.fp_contract));
8676 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8677 /// operators are mixed in a way that suggests that the programmer forgot that
8678 /// comparison operators have higher precedence. The most typical example of
8679 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
8680 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
8681 SourceLocation OpLoc, Expr *LHSExpr,
8683 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
8684 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
8686 // Check that one of the sides is a comparison operator.
8687 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
8688 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
8689 if (!isLeftComp && !isRightComp)
8692 // Bitwise operations are sometimes used as eager logical ops.
8693 // Don't diagnose this.
8694 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
8695 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
8696 if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
8699 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8701 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8702 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
8703 SourceRange ParensRange = isLeftComp ?
8704 SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
8705 : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
8707 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8708 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
8709 SuggestParentheses(Self, OpLoc,
8710 Self.PDiag(diag::note_precedence_silence) << OpStr,
8711 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
8712 SuggestParentheses(Self, OpLoc,
8713 Self.PDiag(diag::note_precedence_bitwise_first)
8714 << BinaryOperator::getOpcodeStr(Opc),
8718 /// \brief It accepts a '&' expr that is inside a '|' one.
8719 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8722 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8723 BinaryOperator *Bop) {
8724 assert(Bop->getOpcode() == BO_And);
8725 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8726 << Bop->getSourceRange() << OpLoc;
8727 SuggestParentheses(Self, Bop->getOperatorLoc(),
8728 Self.PDiag(diag::note_precedence_silence)
8729 << Bop->getOpcodeStr(),
8730 Bop->getSourceRange());
8733 /// \brief It accepts a '&&' expr that is inside a '||' one.
8734 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8737 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8738 BinaryOperator *Bop) {
8739 assert(Bop->getOpcode() == BO_LAnd);
8740 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8741 << Bop->getSourceRange() << OpLoc;
8742 SuggestParentheses(Self, Bop->getOperatorLoc(),
8743 Self.PDiag(diag::note_precedence_silence)
8744 << Bop->getOpcodeStr(),
8745 Bop->getSourceRange());
8748 /// \brief Returns true if the given expression can be evaluated as a constant
8750 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8752 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8755 /// \brief Returns true if the given expression can be evaluated as a constant
8757 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8759 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8762 /// \brief Look for '&&' in the left hand of a '||' expr.
8763 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
8764 Expr *LHSExpr, Expr *RHSExpr) {
8765 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
8766 if (Bop->getOpcode() == BO_LAnd) {
8767 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8768 if (EvaluatesAsFalse(S, RHSExpr))
8770 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8771 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8772 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8773 } else if (Bop->getOpcode() == BO_LOr) {
8774 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8775 // If it's "a || b && 1 || c" we didn't warn earlier for
8776 // "a || b && 1", but warn now.
8777 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8778 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8784 /// \brief Look for '&&' in the right hand of a '||' expr.
8785 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
8786 Expr *LHSExpr, Expr *RHSExpr) {
8787 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
8788 if (Bop->getOpcode() == BO_LAnd) {
8789 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8790 if (EvaluatesAsFalse(S, LHSExpr))
8792 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8793 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8794 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8799 /// \brief Look for '&' in the left or right hand of a '|' expr.
8800 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8802 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8803 if (Bop->getOpcode() == BO_And)
8804 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8808 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
8809 Expr *SubExpr, StringRef Shift) {
8810 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
8811 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
8812 StringRef Op = Bop->getOpcodeStr();
8813 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
8814 << Bop->getSourceRange() << OpLoc << Shift << Op;
8815 SuggestParentheses(S, Bop->getOperatorLoc(),
8816 S.PDiag(diag::note_precedence_silence) << Op,
8817 Bop->getSourceRange());
8822 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
8824 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
8825 SourceLocation OpLoc, Expr *LHSExpr,
8827 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
8828 if (BinaryOperator::isBitwiseOp(Opc))
8829 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
8831 // Diagnose "arg1 & arg2 | arg3"
8832 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8833 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8834 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
8837 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8838 // We don't warn for 'assert(a || b && "bad")' since this is safe.
8839 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8840 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8841 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
8844 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
8846 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
8847 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
8848 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
8852 // Binary Operators. 'Tok' is the token for the operator.
8853 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
8854 tok::TokenKind Kind,
8855 Expr *LHSExpr, Expr *RHSExpr) {
8856 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
8857 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8858 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
8860 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8861 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
8863 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
8866 /// Build an overloaded binary operator expression in the given scope.
8867 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8868 BinaryOperatorKind Opc,
8869 Expr *LHS, Expr *RHS) {
8870 // Find all of the overloaded operators visible from this
8871 // point. We perform both an operator-name lookup from the local
8872 // scope and an argument-dependent lookup based on the types of
8874 UnresolvedSet<16> Functions;
8875 OverloadedOperatorKind OverOp
8876 = BinaryOperator::getOverloadedOperator(Opc);
8877 if (Sc && OverOp != OO_None)
8878 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8879 RHS->getType(), Functions);
8881 // Build the (potentially-overloaded, potentially-dependent)
8882 // binary operation.
8883 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8886 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
8887 BinaryOperatorKind Opc,
8888 Expr *LHSExpr, Expr *RHSExpr) {
8889 // We want to end up calling one of checkPseudoObjectAssignment
8890 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8891 // both expressions are overloadable or either is type-dependent),
8892 // or CreateBuiltinBinOp (in any other case). We also want to get
8893 // any placeholder types out of the way.
8895 // Handle pseudo-objects in the LHS.
8896 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8897 // Assignments with a pseudo-object l-value need special analysis.
8898 if (pty->getKind() == BuiltinType::PseudoObject &&
8899 BinaryOperator::isAssignmentOp(Opc))
8900 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8902 // Don't resolve overloads if the other type is overloadable.
8903 if (pty->getKind() == BuiltinType::Overload) {
8904 // We can't actually test that if we still have a placeholder,
8905 // though. Fortunately, none of the exceptions we see in that
8906 // code below are valid when the LHS is an overload set. Note
8907 // that an overload set can be dependently-typed, but it never
8908 // instantiates to having an overloadable type.
8909 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8910 if (resolvedRHS.isInvalid()) return ExprError();
8911 RHSExpr = resolvedRHS.take();
8913 if (RHSExpr->isTypeDependent() ||
8914 RHSExpr->getType()->isOverloadableType())
8915 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8918 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8919 if (LHS.isInvalid()) return ExprError();
8920 LHSExpr = LHS.take();
8923 // Handle pseudo-objects in the RHS.
8924 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8925 // An overload in the RHS can potentially be resolved by the type
8926 // being assigned to.
8927 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8928 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8929 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8931 if (LHSExpr->getType()->isOverloadableType())
8932 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8934 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8937 // Don't resolve overloads if the other type is overloadable.
8938 if (pty->getKind() == BuiltinType::Overload &&
8939 LHSExpr->getType()->isOverloadableType())
8940 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8942 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8943 if (!resolvedRHS.isUsable()) return ExprError();
8944 RHSExpr = resolvedRHS.take();
8947 if (getLangOpts().CPlusPlus) {
8948 // If either expression is type-dependent, always build an
8950 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8951 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8953 // Otherwise, build an overloaded op if either expression has an
8954 // overloadable type.
8955 if (LHSExpr->getType()->isOverloadableType() ||
8956 RHSExpr->getType()->isOverloadableType())
8957 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8960 // Build a built-in binary operation.
8961 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8964 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8965 UnaryOperatorKind Opc,
8967 ExprResult Input = Owned(InputExpr);
8968 ExprValueKind VK = VK_RValue;
8969 ExprObjectKind OK = OK_Ordinary;
8970 QualType resultType;
8976 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
8983 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
8986 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8987 if (Input.isInvalid()) return ExprError();
8988 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
8993 Input = UsualUnaryConversions(Input.take());
8994 if (Input.isInvalid()) return ExprError();
8995 resultType = Input.get()->getType();
8996 if (resultType->isDependentType())
8998 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8999 resultType->isVectorType())
9001 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
9002 resultType->isEnumeralType())
9004 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9006 resultType->isPointerType())
9009 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9010 << resultType << Input.get()->getSourceRange());
9012 case UO_Not: // bitwise complement
9013 Input = UsualUnaryConversions(Input.take());
9014 if (Input.isInvalid())
9016 resultType = Input.get()->getType();
9017 if (resultType->isDependentType())
9019 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9020 if (resultType->isComplexType() || resultType->isComplexIntegerType())
9021 // C99 does not support '~' for complex conjugation.
9022 Diag(OpLoc, diag::ext_integer_complement_complex)
9023 << resultType << Input.get()->getSourceRange();
9024 else if (resultType->hasIntegerRepresentation())
9026 else if (resultType->isExtVectorType()) {
9027 if (Context.getLangOpts().OpenCL) {
9028 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9029 // on vector float types.
9030 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9031 if (!T->isIntegerType())
9032 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9033 << resultType << Input.get()->getSourceRange());
9037 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9038 << resultType << Input.get()->getSourceRange());
9042 case UO_LNot: // logical negation
9043 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9044 Input = DefaultFunctionArrayLvalueConversion(Input.take());
9045 if (Input.isInvalid()) return ExprError();
9046 resultType = Input.get()->getType();
9048 // Though we still have to promote half FP to float...
9049 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9050 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
9051 resultType = Context.FloatTy;
9054 if (resultType->isDependentType())
9056 if (resultType->isScalarType()) {
9057 // C99 6.5.3.3p1: ok, fallthrough;
9058 if (Context.getLangOpts().CPlusPlus) {
9059 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9060 // operand contextually converted to bool.
9061 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9062 ScalarTypeToBooleanCastKind(resultType));
9063 } else if (Context.getLangOpts().OpenCL &&
9064 Context.getLangOpts().OpenCLVersion < 120) {
9065 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9066 // operate on scalar float types.
9067 if (!resultType->isIntegerType())
9068 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9069 << resultType << Input.get()->getSourceRange());
9071 } else if (resultType->isExtVectorType()) {
9072 if (Context.getLangOpts().OpenCL &&
9073 Context.getLangOpts().OpenCLVersion < 120) {
9074 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9075 // operate on vector float types.
9076 QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9077 if (!T->isIntegerType())
9078 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9079 << resultType << Input.get()->getSourceRange());
9081 // Vector logical not returns the signed variant of the operand type.
9082 resultType = GetSignedVectorType(resultType);
9085 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9086 << resultType << Input.get()->getSourceRange());
9089 // LNot always has type int. C99 6.5.3.3p5.
9090 // In C++, it's bool. C++ 5.3.1p8
9091 resultType = Context.getLogicalOperationType();
9095 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9096 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9097 // complex l-values to ordinary l-values and all other values to r-values.
9098 if (Input.isInvalid()) return ExprError();
9099 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9100 if (Input.get()->getValueKind() != VK_RValue &&
9101 Input.get()->getObjectKind() == OK_Ordinary)
9102 VK = Input.get()->getValueKind();
9103 } else if (!getLangOpts().CPlusPlus) {
9104 // In C, a volatile scalar is read by __imag. In C++, it is not.
9105 Input = DefaultLvalueConversion(Input.take());
9109 resultType = Input.get()->getType();
9110 VK = Input.get()->getValueKind();
9111 OK = Input.get()->getObjectKind();
9114 if (resultType.isNull() || Input.isInvalid())
9117 // Check for array bounds violations in the operand of the UnaryOperator,
9118 // except for the '*' and '&' operators that have to be handled specially
9119 // by CheckArrayAccess (as there are special cases like &array[arraysize]
9120 // that are explicitly defined as valid by the standard).
9121 if (Opc != UO_AddrOf && Opc != UO_Deref)
9122 CheckArrayAccess(Input.get());
9124 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
9128 /// \brief Determine whether the given expression is a qualified member
9129 /// access expression, of a form that could be turned into a pointer to member
9130 /// with the address-of operator.
9131 static bool isQualifiedMemberAccess(Expr *E) {
9132 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9133 if (!DRE->getQualifier())
9136 ValueDecl *VD = DRE->getDecl();
9137 if (!VD->isCXXClassMember())
9140 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9142 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9143 return Method->isInstance();
9148 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9149 if (!ULE->getQualifier())
9152 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9153 DEnd = ULE->decls_end();
9155 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9156 if (Method->isInstance())
9159 // Overload set does not contain methods.
9170 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9171 UnaryOperatorKind Opc, Expr *Input) {
9172 // First things first: handle placeholders so that the
9173 // overloaded-operator check considers the right type.
9174 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9175 // Increment and decrement of pseudo-object references.
9176 if (pty->getKind() == BuiltinType::PseudoObject &&
9177 UnaryOperator::isIncrementDecrementOp(Opc))
9178 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9180 // extension is always a builtin operator.
9181 if (Opc == UO_Extension)
9182 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9184 // & gets special logic for several kinds of placeholder.
9185 // The builtin code knows what to do.
9186 if (Opc == UO_AddrOf &&
9187 (pty->getKind() == BuiltinType::Overload ||
9188 pty->getKind() == BuiltinType::UnknownAny ||
9189 pty->getKind() == BuiltinType::BoundMember))
9190 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9192 // Anything else needs to be handled now.
9193 ExprResult Result = CheckPlaceholderExpr(Input);
9194 if (Result.isInvalid()) return ExprError();
9195 Input = Result.take();
9198 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
9199 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9200 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
9201 // Find all of the overloaded operators visible from this
9202 // point. We perform both an operator-name lookup from the local
9203 // scope and an argument-dependent lookup based on the types of
9205 UnresolvedSet<16> Functions;
9206 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9207 if (S && OverOp != OO_None)
9208 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9211 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9214 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9217 // Unary Operators. 'Tok' is the token for the operator.
9218 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9219 tok::TokenKind Op, Expr *Input) {
9220 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9223 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9224 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9225 LabelDecl *TheDecl) {
9227 // Create the AST node. The address of a label always has type 'void*'.
9228 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9229 Context.getPointerType(Context.VoidTy)));
9232 /// Given the last statement in a statement-expression, check whether
9233 /// the result is a producing expression (like a call to an
9234 /// ns_returns_retained function) and, if so, rebuild it to hoist the
9235 /// release out of the full-expression. Otherwise, return null.
9237 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9238 // Should always be wrapped with one of these.
9239 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9240 if (!cleanups) return 0;
9242 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9243 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9246 // Splice out the cast. This shouldn't modify any interesting
9247 // features of the statement.
9248 Expr *producer = cast->getSubExpr();
9249 assert(producer->getType() == cast->getType());
9250 assert(producer->getValueKind() == cast->getValueKind());
9251 cleanups->setSubExpr(producer);
9255 void Sema::ActOnStartStmtExpr() {
9256 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9259 void Sema::ActOnStmtExprError() {
9260 // Note that function is also called by TreeTransform when leaving a
9261 // StmtExpr scope without rebuilding anything.
9263 DiscardCleanupsInEvaluationContext();
9264 PopExpressionEvaluationContext();
9268 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9269 SourceLocation RPLoc) { // "({..})"
9270 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9271 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9273 if (hasAnyUnrecoverableErrorsInThisFunction())
9274 DiscardCleanupsInEvaluationContext();
9275 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9276 PopExpressionEvaluationContext();
9279 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
9281 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
9283 // FIXME: there are a variety of strange constraints to enforce here, for
9284 // example, it is not possible to goto into a stmt expression apparently.
9285 // More semantic analysis is needed.
9287 // If there are sub stmts in the compound stmt, take the type of the last one
9288 // as the type of the stmtexpr.
9289 QualType Ty = Context.VoidTy;
9290 bool StmtExprMayBindToTemp = false;
9291 if (!Compound->body_empty()) {
9292 Stmt *LastStmt = Compound->body_back();
9293 LabelStmt *LastLabelStmt = 0;
9294 // If LastStmt is a label, skip down through into the body.
9295 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9296 LastLabelStmt = Label;
9297 LastStmt = Label->getSubStmt();
9300 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9301 // Do function/array conversion on the last expression, but not
9302 // lvalue-to-rvalue. However, initialize an unqualified type.
9303 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9304 if (LastExpr.isInvalid())
9306 Ty = LastExpr.get()->getType().getUnqualifiedType();
9308 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9309 // In ARC, if the final expression ends in a consume, splice
9310 // the consume out and bind it later. In the alternate case
9311 // (when dealing with a retainable type), the result
9312 // initialization will create a produce. In both cases the
9313 // result will be +1, and we'll need to balance that out with
9315 if (Expr *rebuiltLastStmt
9316 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9317 LastExpr = rebuiltLastStmt;
9319 LastExpr = PerformCopyInitialization(
9320 InitializedEntity::InitializeResult(LPLoc,
9327 if (LastExpr.isInvalid())
9329 if (LastExpr.get() != 0) {
9331 Compound->setLastStmt(LastExpr.take());
9333 LastLabelStmt->setSubStmt(LastExpr.take());
9334 StmtExprMayBindToTemp = true;
9340 // FIXME: Check that expression type is complete/non-abstract; statement
9341 // expressions are not lvalues.
9342 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9343 if (StmtExprMayBindToTemp)
9344 return MaybeBindToTemporary(ResStmtExpr);
9345 return Owned(ResStmtExpr);
9348 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
9349 TypeSourceInfo *TInfo,
9350 OffsetOfComponent *CompPtr,
9351 unsigned NumComponents,
9352 SourceLocation RParenLoc) {
9353 QualType ArgTy = TInfo->getType();
9354 bool Dependent = ArgTy->isDependentType();
9355 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9357 // We must have at least one component that refers to the type, and the first
9358 // one is known to be a field designator. Verify that the ArgTy represents
9359 // a struct/union/class.
9360 if (!Dependent && !ArgTy->isRecordType())
9361 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
9362 << ArgTy << TypeRange);
9364 // Type must be complete per C99 7.17p3 because a declaring a variable
9365 // with an incomplete type would be ill-formed.
9367 && RequireCompleteType(BuiltinLoc, ArgTy,
9368 diag::err_offsetof_incomplete_type, TypeRange))
9371 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9372 // GCC extension, diagnose them.
9373 // FIXME: This diagnostic isn't actually visible because the location is in
9375 if (NumComponents != 1)
9376 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9377 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9379 bool DidWarnAboutNonPOD = false;
9380 QualType CurrentType = ArgTy;
9381 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9382 SmallVector<OffsetOfNode, 4> Comps;
9383 SmallVector<Expr*, 4> Exprs;
9384 for (unsigned i = 0; i != NumComponents; ++i) {
9385 const OffsetOfComponent &OC = CompPtr[i];
9386 if (OC.isBrackets) {
9387 // Offset of an array sub-field. TODO: Should we allow vector elements?
9388 if (!CurrentType->isDependentType()) {
9389 const ArrayType *AT = Context.getAsArrayType(CurrentType);
9391 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9393 CurrentType = AT->getElementType();
9395 CurrentType = Context.DependentTy;
9397 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9398 if (IdxRval.isInvalid())
9400 Expr *Idx = IdxRval.take();
9402 // The expression must be an integral expression.
9403 // FIXME: An integral constant expression?
9404 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9405 !Idx->getType()->isIntegerType())
9406 return ExprError(Diag(Idx->getLocStart(),
9407 diag::err_typecheck_subscript_not_integer)
9408 << Idx->getSourceRange());
9410 // Record this array index.
9411 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9412 Exprs.push_back(Idx);
9416 // Offset of a field.
9417 if (CurrentType->isDependentType()) {
9418 // We have the offset of a field, but we can't look into the dependent
9419 // type. Just record the identifier of the field.
9420 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9421 CurrentType = Context.DependentTy;
9425 // We need to have a complete type to look into.
9426 if (RequireCompleteType(OC.LocStart, CurrentType,
9427 diag::err_offsetof_incomplete_type))
9430 // Look for the designated field.
9431 const RecordType *RC = CurrentType->getAs<RecordType>();
9433 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9435 RecordDecl *RD = RC->getDecl();
9437 // C++ [lib.support.types]p5:
9438 // The macro offsetof accepts a restricted set of type arguments in this
9439 // International Standard. type shall be a POD structure or a POD union
9441 // C++11 [support.types]p4:
9442 // If type is not a standard-layout class (Clause 9), the results are
9444 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9445 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
9447 LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
9448 : diag::warn_offsetof_non_pod_type;
9450 if (!IsSafe && !DidWarnAboutNonPOD &&
9451 DiagRuntimeBehavior(BuiltinLoc, 0,
9453 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9455 DidWarnAboutNonPOD = true;
9458 // Look for the field.
9459 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9460 LookupQualifiedName(R, RD);
9461 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9462 IndirectFieldDecl *IndirectMemberDecl = 0;
9464 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9465 MemberDecl = IndirectMemberDecl->getAnonField();
9469 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9470 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
9474 // (If the specified member is a bit-field, the behavior is undefined.)
9476 // We diagnose this as an error.
9477 if (MemberDecl->isBitField()) {
9478 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9479 << MemberDecl->getDeclName()
9480 << SourceRange(BuiltinLoc, RParenLoc);
9481 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9485 RecordDecl *Parent = MemberDecl->getParent();
9486 if (IndirectMemberDecl)
9487 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
9489 // If the member was found in a base class, introduce OffsetOfNodes for
9490 // the base class indirections.
9491 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9492 /*DetectVirtual=*/false);
9493 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
9494 CXXBasePath &Path = Paths.front();
9495 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9497 Comps.push_back(OffsetOfNode(B->Base));
9500 if (IndirectMemberDecl) {
9501 for (IndirectFieldDecl::chain_iterator FI =
9502 IndirectMemberDecl->chain_begin(),
9503 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9504 assert(isa<FieldDecl>(*FI));
9505 Comps.push_back(OffsetOfNode(OC.LocStart,
9506 cast<FieldDecl>(*FI), OC.LocEnd));
9509 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
9511 CurrentType = MemberDecl->getType().getNonReferenceType();
9514 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9515 TInfo, Comps, Exprs, RParenLoc));
9518 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
9519 SourceLocation BuiltinLoc,
9520 SourceLocation TypeLoc,
9521 ParsedType ParsedArgTy,
9522 OffsetOfComponent *CompPtr,
9523 unsigned NumComponents,
9524 SourceLocation RParenLoc) {
9526 TypeSourceInfo *ArgTInfo;
9527 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
9532 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9534 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
9539 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
9541 Expr *LHSExpr, Expr *RHSExpr,
9542 SourceLocation RPLoc) {
9543 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9545 ExprValueKind VK = VK_RValue;
9546 ExprObjectKind OK = OK_Ordinary;
9548 bool ValueDependent = false;
9549 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
9550 resType = Context.DependentTy;
9551 ValueDependent = true;
9553 // The conditional expression is required to be a constant expression.
9554 llvm::APSInt condEval(32);
9556 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9557 diag::err_typecheck_choose_expr_requires_constant, false);
9558 if (CondICE.isInvalid())
9560 CondExpr = CondICE.take();
9562 // If the condition is > zero, then the AST type is the same as the LSHExpr.
9563 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9565 resType = ActiveExpr->getType();
9566 ValueDependent = ActiveExpr->isValueDependent();
9567 VK = ActiveExpr->getValueKind();
9568 OK = ActiveExpr->getObjectKind();
9571 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
9572 resType, VK, OK, RPLoc,
9573 resType->isDependentType(),
9577 //===----------------------------------------------------------------------===//
9578 // Clang Extensions.
9579 //===----------------------------------------------------------------------===//
9581 /// ActOnBlockStart - This callback is invoked when a block literal is started.
9582 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
9583 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9584 PushBlockScope(CurScope, Block);
9585 CurContext->addDecl(Block);
9587 PushDeclContext(CurScope, Block);
9591 getCurBlock()->HasImplicitReturnType = true;
9593 // Enter a new evaluation context to insulate the block from any
9594 // cleanups from the enclosing full-expression.
9595 PushExpressionEvaluationContext(PotentiallyEvaluated);
9598 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9600 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
9601 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
9602 BlockScopeInfo *CurBlock = getCurBlock();
9604 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
9605 QualType T = Sig->getType();
9607 // FIXME: We should allow unexpanded parameter packs here, but that would,
9608 // in turn, make the block expression contain unexpanded parameter packs.
9609 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9610 // Drop the parameters.
9611 FunctionProtoType::ExtProtoInfo EPI;
9612 EPI.HasTrailingReturn = false;
9613 EPI.TypeQuals |= DeclSpec::TQ_const;
9614 T = Context.getFunctionType(Context.DependentTy, ArrayRef<QualType>(), EPI);
9615 Sig = Context.getTrivialTypeSourceInfo(T);
9618 // GetTypeForDeclarator always produces a function type for a block
9619 // literal signature. Furthermore, it is always a FunctionProtoType
9620 // unless the function was written with a typedef.
9621 assert(T->isFunctionType() &&
9622 "GetTypeForDeclarator made a non-function block signature");
9624 // Look for an explicit signature in that function type.
9625 FunctionProtoTypeLoc ExplicitSignature;
9627 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9628 if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
9630 // Check whether that explicit signature was synthesized by
9631 // GetTypeForDeclarator. If so, don't save that as part of the
9632 // written signature.
9633 if (ExplicitSignature.getLocalRangeBegin() ==
9634 ExplicitSignature.getLocalRangeEnd()) {
9635 // This would be much cheaper if we stored TypeLocs instead of
9637 TypeLoc Result = ExplicitSignature.getResultLoc();
9638 unsigned Size = Result.getFullDataSize();
9639 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9640 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9642 ExplicitSignature = FunctionProtoTypeLoc();
9646 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9647 CurBlock->FunctionType = T;
9649 const FunctionType *Fn = T->getAs<FunctionType>();
9650 QualType RetTy = Fn->getResultType();
9652 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9654 CurBlock->TheDecl->setIsVariadic(isVariadic);
9656 // Don't allow returning a objc interface by value.
9657 if (RetTy->isObjCObjectType()) {
9658 Diag(ParamInfo.getLocStart(),
9659 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9663 // Context.DependentTy is used as a placeholder for a missing block
9664 // return type. TODO: what should we do with declarators like:
9666 // If the answer is "apply template argument deduction"....
9667 if (RetTy != Context.DependentTy) {
9668 CurBlock->ReturnType = RetTy;
9669 CurBlock->TheDecl->setBlockMissingReturnType(false);
9670 CurBlock->HasImplicitReturnType = false;
9673 // Push block parameters from the declarator if we had them.
9674 SmallVector<ParmVarDecl*, 8> Params;
9675 if (ExplicitSignature) {
9676 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9677 ParmVarDecl *Param = ExplicitSignature.getArg(I);
9678 if (Param->getIdentifier() == 0 &&
9679 !Param->isImplicit() &&
9680 !Param->isInvalidDecl() &&
9681 !getLangOpts().CPlusPlus)
9682 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9683 Params.push_back(Param);
9686 // Fake up parameter variables if we have a typedef, like
9688 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9689 for (FunctionProtoType::arg_type_iterator
9690 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9691 ParmVarDecl *Param =
9692 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9693 ParamInfo.getLocStart(),
9695 Params.push_back(Param);
9699 // Set the parameters on the block decl.
9700 if (!Params.empty()) {
9701 CurBlock->TheDecl->setParams(Params);
9702 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9703 CurBlock->TheDecl->param_end(),
9704 /*CheckParameterNames=*/false);
9707 // Finally we can process decl attributes.
9708 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
9710 // Put the parameter variables in scope. We can bail out immediately
9711 // if we don't have any.
9715 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
9716 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9717 (*AI)->setOwningFunction(CurBlock->TheDecl);
9719 // If this has an identifier, add it to the scope stack.
9720 if ((*AI)->getIdentifier()) {
9721 CheckShadow(CurBlock->TheScope, *AI);
9723 PushOnScopeChains(*AI, CurBlock->TheScope);
9728 /// ActOnBlockError - If there is an error parsing a block, this callback
9729 /// is invoked to pop the information about the block from the action impl.
9730 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
9731 // Leave the expression-evaluation context.
9732 DiscardCleanupsInEvaluationContext();
9733 PopExpressionEvaluationContext();
9735 // Pop off CurBlock, handle nested blocks.
9737 PopFunctionScopeInfo();
9740 /// ActOnBlockStmtExpr - This is called when the body of a block statement
9741 /// literal was successfully completed. ^(int x){...}
9742 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
9743 Stmt *Body, Scope *CurScope) {
9744 // If blocks are disabled, emit an error.
9745 if (!LangOpts.Blocks)
9746 Diag(CaretLoc, diag::err_blocks_disable);
9748 // Leave the expression-evaluation context.
9749 if (hasAnyUnrecoverableErrorsInThisFunction())
9750 DiscardCleanupsInEvaluationContext();
9751 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9752 PopExpressionEvaluationContext();
9754 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
9756 if (BSI->HasImplicitReturnType)
9757 deduceClosureReturnType(*BSI);
9761 QualType RetTy = Context.VoidTy;
9762 if (!BSI->ReturnType.isNull())
9763 RetTy = BSI->ReturnType;
9765 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
9768 // Set the captured variables on the block.
9769 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9770 SmallVector<BlockDecl::Capture, 4> Captures;
9771 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9772 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9773 if (Cap.isThisCapture())
9775 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
9776 Cap.isNested(), Cap.getCopyExpr());
9777 Captures.push_back(NewCap);
9779 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9780 BSI->CXXThisCaptureIndex != 0);
9782 // If the user wrote a function type in some form, try to use that.
9783 if (!BSI->FunctionType.isNull()) {
9784 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9786 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9787 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9789 // Turn protoless block types into nullary block types.
9790 if (isa<FunctionNoProtoType>(FTy)) {
9791 FunctionProtoType::ExtProtoInfo EPI;
9793 BlockTy = Context.getFunctionType(RetTy, ArrayRef<QualType>(), EPI);
9795 // Otherwise, if we don't need to change anything about the function type,
9796 // preserve its sugar structure.
9797 } else if (FTy->getResultType() == RetTy &&
9798 (!NoReturn || FTy->getNoReturnAttr())) {
9799 BlockTy = BSI->FunctionType;
9801 // Otherwise, make the minimal modifications to the function type.
9803 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
9804 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9805 EPI.TypeQuals = 0; // FIXME: silently?
9808 Context.getFunctionType(RetTy,
9809 ArrayRef<QualType>(FPT->arg_type_begin(),
9814 // If we don't have a function type, just build one from nothing.
9816 FunctionProtoType::ExtProtoInfo EPI;
9817 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
9818 BlockTy = Context.getFunctionType(RetTy, ArrayRef<QualType>(), EPI);
9821 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9822 BSI->TheDecl->param_end());
9823 BlockTy = Context.getBlockPointerType(BlockTy);
9825 // If needed, diagnose invalid gotos and switches in the block.
9826 if (getCurFunction()->NeedsScopeChecking() &&
9827 !hasAnyUnrecoverableErrorsInThisFunction() &&
9828 !PP.isCodeCompletionEnabled())
9829 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
9831 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
9833 // Try to apply the named return value optimization. We have to check again
9834 // if we can do this, though, because blocks keep return statements around
9835 // to deduce an implicit return type.
9836 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9837 !BSI->TheDecl->isDependentContext())
9838 computeNRVO(Body, getCurBlock());
9840 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9841 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9842 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
9844 // If the block isn't obviously global, i.e. it captures anything at
9845 // all, then we need to do a few things in the surrounding context:
9846 if (Result->getBlockDecl()->hasCaptures()) {
9847 // First, this expression has a new cleanup object.
9848 ExprCleanupObjects.push_back(Result->getBlockDecl());
9849 ExprNeedsCleanups = true;
9851 // It also gets a branch-protected scope if any of the captured
9852 // variables needs destruction.
9853 for (BlockDecl::capture_const_iterator
9854 ci = Result->getBlockDecl()->capture_begin(),
9855 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9856 const VarDecl *var = ci->getVariable();
9857 if (var->getType().isDestructedType() != QualType::DK_none) {
9858 getCurFunction()->setHasBranchProtectedScope();
9864 return Owned(Result);
9867 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
9868 Expr *E, ParsedType Ty,
9869 SourceLocation RPLoc) {
9870 TypeSourceInfo *TInfo;
9871 GetTypeFromParser(Ty, &TInfo);
9872 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
9875 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
9876 Expr *E, TypeSourceInfo *TInfo,
9877 SourceLocation RPLoc) {
9880 // Get the va_list type
9881 QualType VaListType = Context.getBuiltinVaListType();
9882 if (VaListType->isArrayType()) {
9883 // Deal with implicit array decay; for example, on x86-64,
9884 // va_list is an array, but it's supposed to decay to
9885 // a pointer for va_arg.
9886 VaListType = Context.getArrayDecayedType(VaListType);
9887 // Make sure the input expression also decays appropriately.
9888 ExprResult Result = UsualUnaryConversions(E);
9889 if (Result.isInvalid())
9892 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
9893 // If va_list is a record type and we are compiling in C++ mode,
9894 // check the argument using reference binding.
9895 InitializedEntity Entity
9896 = InitializedEntity::InitializeParameter(Context,
9897 Context.getLValueReferenceType(VaListType), false);
9898 ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
9899 if (Init.isInvalid())
9901 E = Init.takeAs<Expr>();
9903 // Otherwise, the va_list argument must be an l-value because
9904 // it is modified by va_arg.
9905 if (!E->isTypeDependent() &&
9906 CheckForModifiableLvalue(E, BuiltinLoc, *this))
9910 if (!E->isTypeDependent() &&
9911 !Context.hasSameType(VaListType, E->getType())) {
9912 return ExprError(Diag(E->getLocStart(),
9913 diag::err_first_argument_to_va_arg_not_of_type_va_list)
9914 << OrigExpr->getType() << E->getSourceRange());
9917 if (!TInfo->getType()->isDependentType()) {
9918 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
9919 diag::err_second_parameter_to_va_arg_incomplete,
9920 TInfo->getTypeLoc()))
9923 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
9925 diag::err_second_parameter_to_va_arg_abstract,
9926 TInfo->getTypeLoc()))
9929 if (!TInfo->getType().isPODType(Context)) {
9930 Diag(TInfo->getTypeLoc().getBeginLoc(),
9931 TInfo->getType()->isObjCLifetimeType()
9932 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9933 : diag::warn_second_parameter_to_va_arg_not_pod)
9935 << TInfo->getTypeLoc().getSourceRange();
9938 // Check for va_arg where arguments of the given type will be promoted
9939 // (i.e. this va_arg is guaranteed to have undefined behavior).
9940 QualType PromoteType;
9941 if (TInfo->getType()->isPromotableIntegerType()) {
9942 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9943 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9944 PromoteType = QualType();
9946 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9947 PromoteType = Context.DoubleTy;
9948 if (!PromoteType.isNull())
9949 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
9950 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
9953 << TInfo->getTypeLoc().getSourceRange());
9956 QualType T = TInfo->getType().getNonLValueExprType(Context);
9957 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
9960 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
9961 // The type of __null will be int or long, depending on the size of
9962 // pointers on the target.
9964 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9965 if (pw == Context.getTargetInfo().getIntWidth())
9967 else if (pw == Context.getTargetInfo().getLongWidth())
9968 Ty = Context.LongTy;
9969 else if (pw == Context.getTargetInfo().getLongLongWidth())
9970 Ty = Context.LongLongTy;
9972 llvm_unreachable("I don't know size of pointer!");
9975 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
9978 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
9979 Expr *SrcExpr, FixItHint &Hint) {
9980 if (!SemaRef.getLangOpts().ObjC1)
9983 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9987 // Check if the destination is of type 'id'.
9988 if (!PT->isObjCIdType()) {
9989 // Check if the destination is the 'NSString' interface.
9990 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9991 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9995 // Ignore any parens, implicit casts (should only be
9996 // array-to-pointer decays), and not-so-opaque values. The last is
9997 // important for making this trigger for property assignments.
9998 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9999 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10000 if (OV->getSourceExpr())
10001 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10003 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10004 if (!SL || !SL->isAscii())
10007 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
10010 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10011 SourceLocation Loc,
10012 QualType DstType, QualType SrcType,
10013 Expr *SrcExpr, AssignmentAction Action,
10014 bool *Complained) {
10016 *Complained = false;
10018 // Decode the result (notice that AST's are still created for extensions).
10019 bool CheckInferredResultType = false;
10020 bool isInvalid = false;
10021 unsigned DiagKind = 0;
10023 ConversionFixItGenerator ConvHints;
10024 bool MayHaveConvFixit = false;
10025 bool MayHaveFunctionDiff = false;
10029 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10033 DiagKind = diag::ext_typecheck_convert_pointer_int;
10034 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10035 MayHaveConvFixit = true;
10038 DiagKind = diag::ext_typecheck_convert_int_pointer;
10039 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10040 MayHaveConvFixit = true;
10042 case IncompatiblePointer:
10043 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
10044 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
10045 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10046 SrcType->isObjCObjectPointerType();
10047 if (Hint.isNull() && !CheckInferredResultType) {
10048 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10050 MayHaveConvFixit = true;
10052 case IncompatiblePointerSign:
10053 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10055 case FunctionVoidPointer:
10056 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10058 case IncompatiblePointerDiscardsQualifiers: {
10059 // Perform array-to-pointer decay if necessary.
10060 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10062 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10063 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10064 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10065 DiagKind = diag::err_typecheck_incompatible_address_space;
10069 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10070 DiagKind = diag::err_typecheck_incompatible_ownership;
10074 llvm_unreachable("unknown error case for discarding qualifiers!");
10077 case CompatiblePointerDiscardsQualifiers:
10078 // If the qualifiers lost were because we were applying the
10079 // (deprecated) C++ conversion from a string literal to a char*
10080 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
10081 // Ideally, this check would be performed in
10082 // checkPointerTypesForAssignment. However, that would require a
10083 // bit of refactoring (so that the second argument is an
10084 // expression, rather than a type), which should be done as part
10085 // of a larger effort to fix checkPointerTypesForAssignment for
10087 if (getLangOpts().CPlusPlus &&
10088 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10090 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10092 case IncompatibleNestedPointerQualifiers:
10093 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10095 case IntToBlockPointer:
10096 DiagKind = diag::err_int_to_block_pointer;
10098 case IncompatibleBlockPointer:
10099 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10101 case IncompatibleObjCQualifiedId:
10102 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
10103 // it can give a more specific diagnostic.
10104 DiagKind = diag::warn_incompatible_qualified_id;
10106 case IncompatibleVectors:
10107 DiagKind = diag::warn_incompatible_vectors;
10109 case IncompatibleObjCWeakRef:
10110 DiagKind = diag::err_arc_weak_unavailable_assign;
10113 DiagKind = diag::err_typecheck_convert_incompatible;
10114 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10115 MayHaveConvFixit = true;
10117 MayHaveFunctionDiff = true;
10121 QualType FirstType, SecondType;
10124 case AA_Initializing:
10125 // The destination type comes first.
10126 FirstType = DstType;
10127 SecondType = SrcType;
10132 case AA_Converting:
10135 // The source type comes first.
10136 FirstType = SrcType;
10137 SecondType = DstType;
10141 PartialDiagnostic FDiag = PDiag(DiagKind);
10142 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10144 // If we can fix the conversion, suggest the FixIts.
10145 assert(ConvHints.isNull() || Hint.isNull());
10146 if (!ConvHints.isNull()) {
10147 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10148 HE = ConvHints.Hints.end(); HI != HE; ++HI)
10153 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10155 if (MayHaveFunctionDiff)
10156 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10160 if (SecondType == Context.OverloadTy)
10161 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10164 if (CheckInferredResultType)
10165 EmitRelatedResultTypeNote(SrcExpr);
10167 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
10168 EmitRelatedResultTypeNoteForReturn(DstType);
10171 *Complained = true;
10175 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10176 llvm::APSInt *Result) {
10177 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10179 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10180 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10184 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10187 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10188 llvm::APSInt *Result,
10191 class IDDiagnoser : public VerifyICEDiagnoser {
10195 IDDiagnoser(unsigned DiagID)
10196 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10198 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10199 S.Diag(Loc, DiagID) << SR;
10201 } Diagnoser(DiagID);
10203 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10206 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10208 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
10212 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10213 VerifyICEDiagnoser &Diagnoser,
10215 SourceLocation DiagLoc = E->getLocStart();
10217 if (getLangOpts().CPlusPlus11) {
10218 // C++11 [expr.const]p5:
10219 // If an expression of literal class type is used in a context where an
10220 // integral constant expression is required, then that class type shall
10221 // have a single non-explicit conversion function to an integral or
10222 // unscoped enumeration type
10223 ExprResult Converted;
10224 if (!Diagnoser.Suppress) {
10225 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10227 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
10229 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10231 return S.Diag(Loc, diag::err_ice_not_integral) << T;
10234 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10235 SourceLocation Loc,
10237 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10240 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10241 SourceLocation Loc,
10244 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10247 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10248 CXXConversionDecl *Conv,
10250 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10251 << ConvTy->isEnumeralType() << ConvTy;
10254 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10256 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10259 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10260 CXXConversionDecl *Conv,
10262 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10263 << ConvTy->isEnumeralType() << ConvTy;
10266 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10267 SourceLocation Loc,
10270 return DiagnosticBuilder::getEmpty();
10272 } ConvertDiagnoser;
10274 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10276 /*AllowScopedEnumerations*/ false);
10278 // The caller wants to silently enquire whether this is an ICE. Don't
10279 // produce any diagnostics if it isn't.
10280 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
10282 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
10284 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10286 return DiagnosticBuilder::getEmpty();
10289 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10290 SourceLocation Loc,
10292 return DiagnosticBuilder::getEmpty();
10295 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10296 SourceLocation Loc,
10299 return DiagnosticBuilder::getEmpty();
10302 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10303 CXXConversionDecl *Conv,
10305 return DiagnosticBuilder::getEmpty();
10308 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10310 return DiagnosticBuilder::getEmpty();
10313 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10314 CXXConversionDecl *Conv,
10316 return DiagnosticBuilder::getEmpty();
10319 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10320 SourceLocation Loc,
10323 return DiagnosticBuilder::getEmpty();
10325 } ConvertDiagnoser;
10327 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10328 ConvertDiagnoser, false);
10330 if (Converted.isInvalid())
10332 E = Converted.take();
10333 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10334 return ExprError();
10335 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10336 // An ICE must be of integral or unscoped enumeration type.
10337 if (!Diagnoser.Suppress)
10338 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10339 return ExprError();
10342 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10343 // in the non-ICE case.
10344 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
10346 *Result = E->EvaluateKnownConstInt(Context);
10350 Expr::EvalResult EvalResult;
10351 SmallVector<PartialDiagnosticAt, 8> Notes;
10352 EvalResult.Diag = &Notes;
10354 // Try to evaluate the expression, and produce diagnostics explaining why it's
10355 // not a constant expression as a side-effect.
10356 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10357 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10359 // In C++11, we can rely on diagnostics being produced for any expression
10360 // which is not a constant expression. If no diagnostics were produced, then
10361 // this is a constant expression.
10362 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
10364 *Result = EvalResult.Val.getInt();
10368 // If our only note is the usual "invalid subexpression" note, just point
10369 // the caret at its location rather than producing an essentially
10371 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10372 diag::note_invalid_subexpr_in_const_expr) {
10373 DiagLoc = Notes[0].first;
10377 if (!Folded || !AllowFold) {
10378 if (!Diagnoser.Suppress) {
10379 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10380 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10381 Diag(Notes[I].first, Notes[I].second);
10384 return ExprError();
10387 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10388 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10389 Diag(Notes[I].first, Notes[I].second);
10392 *Result = EvalResult.Val.getInt();
10397 // Handle the case where we conclude a expression which we speculatively
10398 // considered to be unevaluated is actually evaluated.
10399 class TransformToPE : public TreeTransform<TransformToPE> {
10400 typedef TreeTransform<TransformToPE> BaseTransform;
10403 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10405 // Make sure we redo semantic analysis
10406 bool AlwaysRebuild() { return true; }
10408 // Make sure we handle LabelStmts correctly.
10409 // FIXME: This does the right thing, but maybe we need a more general
10410 // fix to TreeTransform?
10411 StmtResult TransformLabelStmt(LabelStmt *S) {
10412 S->getDecl()->setStmt(0);
10413 return BaseTransform::TransformLabelStmt(S);
10416 // We need to special-case DeclRefExprs referring to FieldDecls which
10417 // are not part of a member pointer formation; normal TreeTransforming
10418 // doesn't catch this case because of the way we represent them in the AST.
10419 // FIXME: This is a bit ugly; is it really the best way to handle this
10422 // Error on DeclRefExprs referring to FieldDecls.
10423 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10424 if (isa<FieldDecl>(E->getDecl()) &&
10425 !SemaRef.isUnevaluatedContext())
10426 return SemaRef.Diag(E->getLocation(),
10427 diag::err_invalid_non_static_member_use)
10428 << E->getDecl() << E->getSourceRange();
10430 return BaseTransform::TransformDeclRefExpr(E);
10433 // Exception: filter out member pointer formation
10434 ExprResult TransformUnaryOperator(UnaryOperator *E) {
10435 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10438 return BaseTransform::TransformUnaryOperator(E);
10441 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10442 // Lambdas never need to be transformed.
10448 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
10449 assert(ExprEvalContexts.back().Context == Unevaluated &&
10450 "Should only transform unevaluated expressions");
10451 ExprEvalContexts.back().Context =
10452 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10453 if (ExprEvalContexts.back().Context == Unevaluated)
10455 return TransformToPE(*this).TransformExpr(E);
10459 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10460 Decl *LambdaContextDecl,
10462 ExprEvalContexts.push_back(
10463 ExpressionEvaluationContextRecord(NewContext,
10464 ExprCleanupObjects.size(),
10468 ExprNeedsCleanups = false;
10469 if (!MaybeODRUseExprs.empty())
10470 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
10474 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10475 ReuseLambdaContextDecl_t,
10477 Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10478 PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10481 void Sema::PopExpressionEvaluationContext() {
10482 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
10484 if (!Rec.Lambdas.empty()) {
10485 if (Rec.Context == Unevaluated) {
10486 // C++11 [expr.prim.lambda]p2:
10487 // A lambda-expression shall not appear in an unevaluated operand
10489 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10490 Diag(Rec.Lambdas[I]->getLocStart(),
10491 diag::err_lambda_unevaluated_operand);
10493 // Mark the capture expressions odr-used. This was deferred
10494 // during lambda expression creation.
10495 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10496 LambdaExpr *Lambda = Rec.Lambdas[I];
10497 for (LambdaExpr::capture_init_iterator
10498 C = Lambda->capture_init_begin(),
10499 CEnd = Lambda->capture_init_end();
10501 MarkDeclarationsReferencedInExpr(*C);
10507 // When are coming out of an unevaluated context, clear out any
10508 // temporaries that we may have created as part of the evaluation of
10509 // the expression in that context: they aren't relevant because they
10510 // will never be constructed.
10511 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
10512 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10513 ExprCleanupObjects.end());
10514 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10515 CleanupVarDeclMarking();
10516 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
10517 // Otherwise, merge the contexts together.
10519 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10520 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10521 Rec.SavedMaybeODRUseExprs.end());
10524 // Pop the current expression evaluation context off the stack.
10525 ExprEvalContexts.pop_back();
10528 void Sema::DiscardCleanupsInEvaluationContext() {
10529 ExprCleanupObjects.erase(
10530 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10531 ExprCleanupObjects.end());
10532 ExprNeedsCleanups = false;
10533 MaybeODRUseExprs.clear();
10536 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10537 if (!E->getType()->isVariablyModifiedType())
10539 return TransformToPotentiallyEvaluated(E);
10542 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
10543 // Do not mark anything as "used" within a dependent context; wait for
10544 // an instantiation.
10545 if (SemaRef.CurContext->isDependentContext())
10548 switch (SemaRef.ExprEvalContexts.back().Context) {
10549 case Sema::Unevaluated:
10550 // We are in an expression that is not potentially evaluated; do nothing.
10551 // (Depending on how you read the standard, we actually do need to do
10552 // something here for null pointer constants, but the standard's
10553 // definition of a null pointer constant is completely crazy.)
10556 case Sema::ConstantEvaluated:
10557 case Sema::PotentiallyEvaluated:
10558 // We are in a potentially evaluated expression (or a constant-expression
10559 // in C++03); we need to do implicit template instantiation, implicitly
10560 // define class members, and mark most declarations as used.
10563 case Sema::PotentiallyEvaluatedIfUsed:
10564 // Referenced declarations will only be used if the construct in the
10565 // containing expression is used.
10568 llvm_unreachable("Invalid context");
10571 /// \brief Mark a function referenced, and check whether it is odr-used
10572 /// (C++ [basic.def.odr]p2, C99 6.9p3)
10573 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10574 assert(Func && "No function?");
10576 Func->setReferenced();
10578 // C++11 [basic.def.odr]p3:
10579 // A function whose name appears as a potentially-evaluated expression is
10580 // odr-used if it is the unique lookup result or the selected member of a
10581 // set of overloaded functions [...].
10583 // We (incorrectly) mark overload resolution as an unevaluated context, so we
10584 // can just check that here. Skip the rest of this function if we've already
10585 // marked the function as used.
10586 if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
10587 // C++11 [temp.inst]p3:
10588 // Unless a function template specialization has been explicitly
10589 // instantiated or explicitly specialized, the function template
10590 // specialization is implicitly instantiated when the specialization is
10591 // referenced in a context that requires a function definition to exist.
10593 // We consider constexpr function templates to be referenced in a context
10594 // that requires a definition to exist whenever they are referenced.
10596 // FIXME: This instantiates constexpr functions too frequently. If this is
10597 // really an unevaluated context (and we're not just in the definition of a
10598 // function template or overload resolution or other cases which we
10599 // incorrectly consider to be unevaluated contexts), and we're not in a
10600 // subexpression which we actually need to evaluate (for instance, a
10601 // template argument, array bound or an expression in a braced-init-list),
10602 // we are not permitted to instantiate this constexpr function definition.
10604 // FIXME: This also implicitly defines special members too frequently. They
10605 // are only supposed to be implicitly defined if they are odr-used, but they
10606 // are not odr-used from constant expressions in unevaluated contexts.
10607 // However, they cannot be referenced if they are deleted, and they are
10608 // deleted whenever the implicit definition of the special member would
10610 if (!Func->isConstexpr() || Func->getBody())
10612 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
10613 if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
10617 // Note that this declaration has been used.
10618 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
10619 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
10620 if (Constructor->isDefaultConstructor()) {
10621 if (Constructor->isTrivial())
10623 if (!Constructor->isUsed(false))
10624 DefineImplicitDefaultConstructor(Loc, Constructor);
10625 } else if (Constructor->isCopyConstructor()) {
10626 if (!Constructor->isUsed(false))
10627 DefineImplicitCopyConstructor(Loc, Constructor);
10628 } else if (Constructor->isMoveConstructor()) {
10629 if (!Constructor->isUsed(false))
10630 DefineImplicitMoveConstructor(Loc, Constructor);
10632 } else if (Constructor->getInheritedConstructor()) {
10633 if (!Constructor->isUsed(false))
10634 DefineInheritingConstructor(Loc, Constructor);
10637 MarkVTableUsed(Loc, Constructor->getParent());
10638 } else if (CXXDestructorDecl *Destructor =
10639 dyn_cast<CXXDestructorDecl>(Func)) {
10640 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10641 !Destructor->isUsed(false))
10642 DefineImplicitDestructor(Loc, Destructor);
10643 if (Destructor->isVirtual())
10644 MarkVTableUsed(Loc, Destructor->getParent());
10645 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
10646 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10647 MethodDecl->isOverloadedOperator() &&
10648 MethodDecl->getOverloadedOperator() == OO_Equal) {
10649 if (!MethodDecl->isUsed(false)) {
10650 if (MethodDecl->isCopyAssignmentOperator())
10651 DefineImplicitCopyAssignment(Loc, MethodDecl);
10653 DefineImplicitMoveAssignment(Loc, MethodDecl);
10655 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10656 MethodDecl->getParent()->isLambda()) {
10657 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10658 if (Conversion->isLambdaToBlockPointerConversion())
10659 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10661 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
10662 } else if (MethodDecl->isVirtual())
10663 MarkVTableUsed(Loc, MethodDecl->getParent());
10666 // Recursive functions should be marked when used from another function.
10667 // FIXME: Is this really right?
10668 if (CurContext == Func) return;
10670 // Resolve the exception specification for any function which is
10671 // used: CodeGen will need it.
10672 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10673 if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10674 ResolveExceptionSpec(Loc, FPT);
10676 // Implicit instantiation of function templates and member functions of
10677 // class templates.
10678 if (Func->isImplicitlyInstantiable()) {
10679 bool AlreadyInstantiated = false;
10680 SourceLocation PointOfInstantiation = Loc;
10681 if (FunctionTemplateSpecializationInfo *SpecInfo
10682 = Func->getTemplateSpecializationInfo()) {
10683 if (SpecInfo->getPointOfInstantiation().isInvalid())
10684 SpecInfo->setPointOfInstantiation(Loc);
10685 else if (SpecInfo->getTemplateSpecializationKind()
10686 == TSK_ImplicitInstantiation) {
10687 AlreadyInstantiated = true;
10688 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10690 } else if (MemberSpecializationInfo *MSInfo
10691 = Func->getMemberSpecializationInfo()) {
10692 if (MSInfo->getPointOfInstantiation().isInvalid())
10693 MSInfo->setPointOfInstantiation(Loc);
10694 else if (MSInfo->getTemplateSpecializationKind()
10695 == TSK_ImplicitInstantiation) {
10696 AlreadyInstantiated = true;
10697 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10701 if (!AlreadyInstantiated || Func->isConstexpr()) {
10702 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10703 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
10704 PendingLocalImplicitInstantiations.push_back(
10705 std::make_pair(Func, PointOfInstantiation));
10706 else if (Func->isConstexpr())
10707 // Do not defer instantiations of constexpr functions, to avoid the
10708 // expression evaluator needing to call back into Sema if it sees a
10709 // call to such a function.
10710 InstantiateFunctionDefinition(PointOfInstantiation, Func);
10712 PendingInstantiations.push_back(std::make_pair(Func,
10713 PointOfInstantiation));
10714 // Notify the consumer that a function was implicitly instantiated.
10715 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10719 // Walk redefinitions, as some of them may be instantiable.
10720 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10721 e(Func->redecls_end()); i != e; ++i) {
10722 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10723 MarkFunctionReferenced(Loc, *i);
10727 // Keep track of used but undefined functions.
10728 if (!Func->isDefined()) {
10729 if (mightHaveNonExternalLinkage(Func))
10730 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
10731 else if (Func->getMostRecentDecl()->isInlined() &&
10732 (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10733 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
10734 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
10737 // Normally the must current decl is marked used while processing the use and
10738 // any subsequent decls are marked used by decl merging. This fails with
10739 // template instantiation since marking can happen at the end of the file
10740 // and, because of the two phase lookup, this function is called with at
10741 // decl in the middle of a decl chain. We loop to maintain the invariant
10742 // that once a decl is used, all decls after it are also used.
10743 for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
10751 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10752 VarDecl *var, DeclContext *DC) {
10753 DeclContext *VarDC = var->getDeclContext();
10755 // If the parameter still belongs to the translation unit, then
10756 // we're actually just using one parameter in the declaration of
10758 if (isa<ParmVarDecl>(var) &&
10759 isa<TranslationUnitDecl>(VarDC))
10762 // For C code, don't diagnose about capture if we're not actually in code
10763 // right now; it's impossible to write a non-constant expression outside of
10764 // function context, so we'll get other (more useful) diagnostics later.
10766 // For C++, things get a bit more nasty... it would be nice to suppress this
10767 // diagnostic for certain cases like using a local variable in an array bound
10768 // for a member of a local class, but the correct predicate is not obvious.
10769 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
10772 if (isa<CXXMethodDecl>(VarDC) &&
10773 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10774 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10775 << var->getIdentifier();
10776 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10777 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10778 << var->getIdentifier() << fn->getDeclName();
10779 } else if (isa<BlockDecl>(VarDC)) {
10780 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10781 << var->getIdentifier();
10783 // FIXME: Is there any other context where a local variable can be
10785 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10786 << var->getIdentifier();
10789 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10790 << var->getIdentifier();
10792 // FIXME: Add additional diagnostic info about class etc. which prevents
10796 /// \brief Capture the given variable in the given lambda expression.
10797 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
10798 VarDecl *Var, QualType FieldType,
10799 QualType DeclRefType,
10800 SourceLocation Loc,
10801 bool RefersToEnclosingLocal) {
10802 CXXRecordDecl *Lambda = LSI->Lambda;
10804 // Build the non-static data member.
10806 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10807 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
10808 0, false, ICIS_NoInit);
10809 Field->setImplicit(true);
10810 Field->setAccess(AS_private);
10811 Lambda->addDecl(Field);
10813 // C++11 [expr.prim.lambda]p21:
10814 // When the lambda-expression is evaluated, the entities that
10815 // are captured by copy are used to direct-initialize each
10816 // corresponding non-static data member of the resulting closure
10817 // object. (For array members, the array elements are
10818 // direct-initialized in increasing subscript order.) These
10819 // initializations are performed in the (unspecified) order in
10820 // which the non-static data members are declared.
10822 // Introduce a new evaluation context for the initialization, so
10823 // that temporaries introduced as part of the capture are retained
10824 // to be re-"exported" from the lambda expression itself.
10825 EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
10827 // C++ [expr.prim.labda]p12:
10828 // An entity captured by a lambda-expression is odr-used (3.2) in
10829 // the scope containing the lambda-expression.
10830 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10831 DeclRefType, VK_LValue, Loc);
10832 Var->setReferenced(true);
10833 Var->setUsed(true);
10835 // When the field has array type, create index variables for each
10836 // dimension of the array. We use these index variables to subscript
10837 // the source array, and other clients (e.g., CodeGen) will perform
10838 // the necessary iteration with these index variables.
10839 SmallVector<VarDecl *, 4> IndexVariables;
10840 QualType BaseType = FieldType;
10841 QualType SizeType = S.Context.getSizeType();
10842 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
10843 while (const ConstantArrayType *Array
10844 = S.Context.getAsConstantArrayType(BaseType)) {
10845 // Create the iteration variable for this array index.
10846 IdentifierInfo *IterationVarName = 0;
10848 SmallString<8> Str;
10849 llvm::raw_svector_ostream OS(Str);
10850 OS << "__i" << IndexVariables.size();
10851 IterationVarName = &S.Context.Idents.get(OS.str());
10853 VarDecl *IterationVar
10854 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10855 IterationVarName, SizeType,
10856 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10858 IndexVariables.push_back(IterationVar);
10859 LSI->ArrayIndexVars.push_back(IterationVar);
10861 // Create a reference to the iteration variable.
10862 ExprResult IterationVarRef
10863 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10864 assert(!IterationVarRef.isInvalid() &&
10865 "Reference to invented variable cannot fail!");
10866 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10867 assert(!IterationVarRef.isInvalid() &&
10868 "Conversion of invented variable cannot fail!");
10870 // Subscript the array with this iteration variable.
10871 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10872 Ref, Loc, IterationVarRef.take(), Loc);
10873 if (Subscript.isInvalid()) {
10874 S.CleanupVarDeclMarking();
10875 S.DiscardCleanupsInEvaluationContext();
10876 return ExprError();
10879 Ref = Subscript.take();
10880 BaseType = Array->getElementType();
10883 // Construct the entity that we will be initializing. For an array, this
10884 // will be first element in the array, which may require several levels
10885 // of array-subscript entities.
10886 SmallVector<InitializedEntity, 4> Entities;
10887 Entities.reserve(1 + IndexVariables.size());
10888 Entities.push_back(
10889 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
10890 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10891 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10895 InitializationKind InitKind
10896 = InitializationKind::CreateDirect(Loc, Loc, Loc);
10897 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
10898 ExprResult Result(true);
10899 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10900 Result = Init.Perform(S, Entities.back(), InitKind, Ref);
10902 // If this initialization requires any cleanups (e.g., due to a
10903 // default argument to a copy constructor), note that for the
10905 if (S.ExprNeedsCleanups)
10906 LSI->ExprNeedsCleanups = true;
10908 // Exit the expression evaluation context used for the capture.
10909 S.CleanupVarDeclMarking();
10910 S.DiscardCleanupsInEvaluationContext();
10914 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10915 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10916 bool BuildAndDiagnose,
10917 QualType &CaptureType,
10918 QualType &DeclRefType) {
10919 bool Nested = false;
10921 DeclContext *DC = CurContext;
10922 if (Var->getDeclContext() == DC) return true;
10923 if (!Var->hasLocalStorage()) return true;
10925 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
10927 // Walk up the stack to determine whether we can capture the variable,
10928 // performing the "simple" checks that don't depend on type. We stop when
10929 // we've either hit the declared scope of the variable or find an existing
10930 // capture of that variable.
10931 CaptureType = Var->getType();
10932 DeclRefType = CaptureType.getNonReferenceType();
10933 bool Explicit = (Kind != TryCapture_Implicit);
10934 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
10936 // Only block literals and lambda expressions can capture; other
10937 // scopes don't work.
10938 DeclContext *ParentDC;
10939 if (isa<BlockDecl>(DC))
10940 ParentDC = DC->getParent();
10941 else if (isa<CXXMethodDecl>(DC) &&
10942 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
10943 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10944 ParentDC = DC->getParent()->getParent();
10946 if (BuildAndDiagnose)
10947 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
10951 CapturingScopeInfo *CSI =
10952 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
10954 // Check whether we've already captured it.
10955 if (CSI->CaptureMap.count(Var)) {
10956 // If we found a capture, any subcaptures are nested.
10959 // Retrieve the capture type for this variable.
10960 CaptureType = CSI->getCapture(Var).getCaptureType();
10962 // Compute the type of an expression that refers to this variable.
10963 DeclRefType = CaptureType.getNonReferenceType();
10965 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10966 if (Cap.isCopyCapture() &&
10967 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10968 DeclRefType.addConst();
10972 bool IsBlock = isa<BlockScopeInfo>(CSI);
10973 bool IsLambda = !IsBlock;
10975 // Lambdas are not allowed to capture unnamed variables
10976 // (e.g. anonymous unions).
10977 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10978 // assuming that's the intent.
10979 if (IsLambda && !Var->getDeclName()) {
10980 if (BuildAndDiagnose) {
10981 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10982 Diag(Var->getLocation(), diag::note_declared_at);
10987 // Prohibit variably-modified types; they're difficult to deal with.
10988 if (Var->getType()->isVariablyModifiedType()) {
10989 if (BuildAndDiagnose) {
10991 Diag(Loc, diag::err_ref_vm_type);
10993 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10994 Diag(Var->getLocation(), diag::note_previous_decl)
10995 << Var->getDeclName();
10999 // Prohibit structs with flexible array members too.
11000 // We cannot capture what is in the tail end of the struct.
11001 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11002 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11003 if (BuildAndDiagnose) {
11005 Diag(Loc, diag::err_ref_flexarray_type);
11007 Diag(Loc, diag::err_lambda_capture_flexarray_type)
11008 << Var->getDeclName();
11009 Diag(Var->getLocation(), diag::note_previous_decl)
11010 << Var->getDeclName();
11015 // Lambdas are not allowed to capture __block variables; they don't
11016 // support the expected semantics.
11017 if (IsLambda && HasBlocksAttr) {
11018 if (BuildAndDiagnose) {
11019 Diag(Loc, diag::err_lambda_capture_block)
11020 << Var->getDeclName();
11021 Diag(Var->getLocation(), diag::note_previous_decl)
11022 << Var->getDeclName();
11027 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
11028 // No capture-default
11029 if (BuildAndDiagnose) {
11030 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
11031 Diag(Var->getLocation(), diag::note_previous_decl)
11032 << Var->getDeclName();
11033 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
11034 diag::note_lambda_decl);
11039 FunctionScopesIndex--;
11042 } while (!Var->getDeclContext()->Equals(DC));
11044 // Walk back down the scope stack, computing the type of the capture at
11045 // each step, checking type-specific requirements, and adding captures if
11047 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
11049 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
11051 // Compute the type of the capture and of a reference to the capture within
11053 if (isa<BlockScopeInfo>(CSI)) {
11054 Expr *CopyExpr = 0;
11055 bool ByRef = false;
11057 // Blocks are not allowed to capture arrays.
11058 if (CaptureType->isArrayType()) {
11059 if (BuildAndDiagnose) {
11060 Diag(Loc, diag::err_ref_array_type);
11061 Diag(Var->getLocation(), diag::note_previous_decl)
11062 << Var->getDeclName();
11067 // Forbid the block-capture of autoreleasing variables.
11068 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11069 if (BuildAndDiagnose) {
11070 Diag(Loc, diag::err_arc_autoreleasing_capture)
11072 Diag(Var->getLocation(), diag::note_previous_decl)
11073 << Var->getDeclName();
11078 if (HasBlocksAttr || CaptureType->isReferenceType()) {
11079 // Block capture by reference does not change the capture or
11080 // declaration reference types.
11083 // Block capture by copy introduces 'const'.
11084 CaptureType = CaptureType.getNonReferenceType().withConst();
11085 DeclRefType = CaptureType;
11087 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
11088 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11089 // The capture logic needs the destructor, so make sure we mark it.
11090 // Usually this is unnecessary because most local variables have
11091 // their destructors marked at declaration time, but parameters are
11092 // an exception because it's technically only the call site that
11093 // actually requires the destructor.
11094 if (isa<ParmVarDecl>(Var))
11095 FinalizeVarWithDestructor(Var, Record);
11097 // Enter a new evaluation context to insulate the copy
11098 // full-expression.
11099 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11101 // According to the blocks spec, the capture of a variable from
11102 // the stack requires a const copy constructor. This is not true
11103 // of the copy/move done to move a __block variable to the heap.
11104 Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested,
11105 DeclRefType.withConst(),
11109 = PerformCopyInitialization(
11110 InitializedEntity::InitializeBlock(Var->getLocation(),
11111 CaptureType, false),
11112 Loc, Owned(DeclRef));
11114 // Build a full-expression copy expression if initialization
11115 // succeeded and used a non-trivial constructor. Recover from
11116 // errors by pretending that the copy isn't necessary.
11117 if (!Result.isInvalid() &&
11118 !cast<CXXConstructExpr>(Result.get())->getConstructor()
11120 Result = MaybeCreateExprWithCleanups(Result);
11121 CopyExpr = Result.take();
11127 // Actually capture the variable.
11128 if (BuildAndDiagnose)
11129 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11130 SourceLocation(), CaptureType, CopyExpr);
11135 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11137 // Determine whether we are capturing by reference or by value.
11138 bool ByRef = false;
11139 if (I == N - 1 && Kind != TryCapture_Implicit) {
11140 ByRef = (Kind == TryCapture_ExplicitByRef);
11142 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11145 // Compute the type of the field that will capture this variable.
11147 // C++11 [expr.prim.lambda]p15:
11148 // An entity is captured by reference if it is implicitly or
11149 // explicitly captured but not captured by copy. It is
11150 // unspecified whether additional unnamed non-static data
11151 // members are declared in the closure type for entities
11152 // captured by reference.
11154 // FIXME: It is not clear whether we want to build an lvalue reference
11155 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11156 // to do the former, while EDG does the latter. Core issue 1249 will
11157 // clarify, but for now we follow GCC because it's a more permissive and
11158 // easily defensible position.
11159 CaptureType = Context.getLValueReferenceType(DeclRefType);
11161 // C++11 [expr.prim.lambda]p14:
11162 // For each entity captured by copy, an unnamed non-static
11163 // data member is declared in the closure type. The
11164 // declaration order of these members is unspecified. The type
11165 // of such a data member is the type of the corresponding
11166 // captured entity if the entity is not a reference to an
11167 // object, or the referenced type otherwise. [Note: If the
11168 // captured entity is a reference to a function, the
11169 // corresponding data member is also a reference to a
11170 // function. - end note ]
11171 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11172 if (!RefType->getPointeeType()->isFunctionType())
11173 CaptureType = RefType->getPointeeType();
11176 // Forbid the lambda copy-capture of autoreleasing variables.
11177 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11178 if (BuildAndDiagnose) {
11179 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11180 Diag(Var->getLocation(), diag::note_previous_decl)
11181 << Var->getDeclName();
11187 // Capture this variable in the lambda.
11188 Expr *CopyExpr = 0;
11189 if (BuildAndDiagnose) {
11190 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
11193 if (!Result.isInvalid())
11194 CopyExpr = Result.take();
11197 // Compute the type of a reference to this captured variable.
11199 DeclRefType = CaptureType.getNonReferenceType();
11201 // C++ [expr.prim.lambda]p5:
11202 // The closure type for a lambda-expression has a public inline
11203 // function call operator [...]. This function call operator is
11204 // declared const (9.3.1) if and only if the lambda-expression’s
11205 // parameter-declaration-clause is not followed by mutable.
11206 DeclRefType = CaptureType.getNonReferenceType();
11207 if (!LSI->Mutable && !CaptureType->isReferenceType())
11208 DeclRefType.addConst();
11211 // Add the capture.
11212 if (BuildAndDiagnose)
11213 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
11214 EllipsisLoc, CaptureType, CopyExpr);
11221 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11222 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
11223 QualType CaptureType;
11224 QualType DeclRefType;
11225 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
11226 /*BuildAndDiagnose=*/true, CaptureType,
11230 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
11231 QualType CaptureType;
11232 QualType DeclRefType;
11234 // Determine whether we can capture this variable.
11235 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
11236 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
11239 return DeclRefType;
11242 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
11243 SourceLocation Loc) {
11244 // Keep track of used but undefined variables.
11245 // FIXME: We shouldn't suppress this warning for static data members.
11246 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
11247 Var->getLinkage() != ExternalLinkage &&
11248 !(Var->isStaticDataMember() && Var->hasInit())) {
11249 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
11250 if (old.isInvalid()) old = Loc;
11253 SemaRef.tryCaptureVariable(Var, Loc);
11255 Var->setUsed(true);
11258 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
11259 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
11260 // an object that satisfies the requirements for appearing in a
11261 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
11262 // is immediately applied." This function handles the lvalue-to-rvalue
11263 // conversion part.
11264 MaybeODRUseExprs.erase(E->IgnoreParens());
11267 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
11268 if (!Res.isUsable())
11271 // If a constant-expression is a reference to a variable where we delay
11272 // deciding whether it is an odr-use, just assume we will apply the
11273 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
11274 // (a non-type template argument), we have special handling anyway.
11275 UpdateMarkingForLValueToRValue(Res.get());
11279 void Sema::CleanupVarDeclMarking() {
11280 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
11281 e = MaybeODRUseExprs.end();
11284 SourceLocation Loc;
11285 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
11286 Var = cast<VarDecl>(DRE->getDecl());
11287 Loc = DRE->getLocation();
11288 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
11289 Var = cast<VarDecl>(ME->getMemberDecl());
11290 Loc = ME->getMemberLoc();
11292 llvm_unreachable("Unexpcted expression");
11295 MarkVarDeclODRUsed(*this, Var, Loc);
11298 MaybeODRUseExprs.clear();
11301 // Mark a VarDecl referenced, and perform the necessary handling to compute
11303 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11304 VarDecl *Var, Expr *E) {
11305 Var->setReferenced();
11307 if (!IsPotentiallyEvaluatedContext(SemaRef))
11310 // Implicit instantiation of static data members of class templates.
11311 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
11312 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
11313 assert(MSInfo && "Missing member specialization information?");
11314 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
11315 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
11316 (!AlreadyInstantiated ||
11317 Var->isUsableInConstantExpressions(SemaRef.Context))) {
11318 if (!AlreadyInstantiated) {
11319 // This is a modification of an existing AST node. Notify listeners.
11320 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11321 L->StaticDataMemberInstantiated(Var);
11322 MSInfo->setPointOfInstantiation(Loc);
11324 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
11325 if (Var->isUsableInConstantExpressions(SemaRef.Context))
11326 // Do not defer instantiations of variables which could be used in a
11327 // constant expression.
11328 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
11330 SemaRef.PendingInstantiations.push_back(
11331 std::make_pair(Var, PointOfInstantiation));
11335 // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11336 // the requirements for appearing in a constant expression (5.19) and, if
11337 // it is an object, the lvalue-to-rvalue conversion (4.1)
11338 // is immediately applied." We check the first part here, and
11339 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11340 // Note that we use the C++11 definition everywhere because nothing in
11341 // C++03 depends on whether we get the C++03 version correct. The second
11342 // part does not apply to references, since they are not objects.
11343 const VarDecl *DefVD;
11344 if (E && !isa<ParmVarDecl>(Var) &&
11345 Var->isUsableInConstantExpressions(SemaRef.Context) &&
11346 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11347 if (!Var->getType()->isReferenceType())
11348 SemaRef.MaybeODRUseExprs.insert(E);
11350 MarkVarDeclODRUsed(SemaRef, Var, Loc);
11353 /// \brief Mark a variable referenced, and check whether it is odr-used
11354 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
11355 /// used directly for normal expressions referring to VarDecl.
11356 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11357 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
11360 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11361 Decl *D, Expr *E, bool OdrUse) {
11362 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11363 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11367 SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
11369 // If this is a call to a method via a cast, also mark the method in the
11370 // derived class used in case codegen can devirtualize the call.
11371 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11374 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11377 const Expr *Base = ME->getBase();
11378 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
11379 if (!MostDerivedClassDecl)
11381 CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
11382 if (!DM || DM->isPure())
11384 SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
11387 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11388 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11389 // TODO: update this with DR# once a defect report is filed.
11390 // C++11 defect. The address of a pure member should not be an ODR use, even
11391 // if it's a qualified reference.
11392 bool OdrUse = true;
11393 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
11394 if (Method->isVirtual())
11396 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
11399 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11400 void Sema::MarkMemberReferenced(MemberExpr *E) {
11401 // C++11 [basic.def.odr]p2:
11402 // A non-overloaded function whose name appears as a potentially-evaluated
11403 // expression or a member of a set of candidate functions, if selected by
11404 // overload resolution when referred to from a potentially-evaluated
11405 // expression, is odr-used, unless it is a pure virtual function and its
11406 // name is not explicitly qualified.
11407 bool OdrUse = true;
11408 if (!E->hasQualifier()) {
11409 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
11410 if (Method->isPure())
11413 SourceLocation Loc = E->getMemberLoc().isValid() ?
11414 E->getMemberLoc() : E->getLocStart();
11415 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
11418 /// \brief Perform marking for a reference to an arbitrary declaration. It
11419 /// marks the declaration referenced, and performs odr-use checking for functions
11420 /// and variables. This method should not be used when building an normal
11421 /// expression which refers to a variable.
11422 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
11424 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11425 MarkVariableReferenced(Loc, VD);
11428 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
11429 MarkFunctionReferenced(Loc, FD);
11433 D->setReferenced();
11437 // Mark all of the declarations referenced
11438 // FIXME: Not fully implemented yet! We need to have a better understanding
11439 // of when we're entering
11440 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11442 SourceLocation Loc;
11445 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
11447 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
11449 bool TraverseTemplateArgument(const TemplateArgument &Arg);
11450 bool TraverseRecordType(RecordType *T);
11454 bool MarkReferencedDecls::TraverseTemplateArgument(
11455 const TemplateArgument &Arg) {
11456 if (Arg.getKind() == TemplateArgument::Declaration) {
11457 if (Decl *D = Arg.getAsDecl())
11458 S.MarkAnyDeclReferenced(Loc, D, true);
11461 return Inherited::TraverseTemplateArgument(Arg);
11464 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
11465 if (ClassTemplateSpecializationDecl *Spec
11466 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11467 const TemplateArgumentList &Args = Spec->getTemplateArgs();
11468 return TraverseTemplateArguments(Args.data(), Args.size());
11474 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11475 MarkReferencedDecls Marker(*this, Loc);
11476 Marker.TraverseType(Context.getCanonicalType(T));
11480 /// \brief Helper class that marks all of the declarations referenced by
11481 /// potentially-evaluated subexpressions as "referenced".
11482 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11484 bool SkipLocalVariables;
11487 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11489 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
11490 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
11492 void VisitDeclRefExpr(DeclRefExpr *E) {
11493 // If we were asked not to visit local variables, don't.
11494 if (SkipLocalVariables) {
11495 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11496 if (VD->hasLocalStorage())
11500 S.MarkDeclRefReferenced(E);
11503 void VisitMemberExpr(MemberExpr *E) {
11504 S.MarkMemberReferenced(E);
11505 Inherited::VisitMemberExpr(E);
11508 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11509 S.MarkFunctionReferenced(E->getLocStart(),
11510 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11511 Visit(E->getSubExpr());
11514 void VisitCXXNewExpr(CXXNewExpr *E) {
11515 if (E->getOperatorNew())
11516 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
11517 if (E->getOperatorDelete())
11518 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11519 Inherited::VisitCXXNewExpr(E);
11522 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11523 if (E->getOperatorDelete())
11524 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11525 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11526 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11527 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
11528 S.MarkFunctionReferenced(E->getLocStart(),
11529 S.LookupDestructor(Record));
11532 Inherited::VisitCXXDeleteExpr(E);
11535 void VisitCXXConstructExpr(CXXConstructExpr *E) {
11536 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
11537 Inherited::VisitCXXConstructExpr(E);
11540 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11541 Visit(E->getExpr());
11544 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11545 Inherited::VisitImplicitCastExpr(E);
11547 if (E->getCastKind() == CK_LValueToRValue)
11548 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11553 /// \brief Mark any declarations that appear within this expression or any
11554 /// potentially-evaluated subexpressions as "referenced".
11556 /// \param SkipLocalVariables If true, don't mark local variables as
11558 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
11559 bool SkipLocalVariables) {
11560 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
11563 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
11564 /// of the program being compiled.
11566 /// This routine emits the given diagnostic when the code currently being
11567 /// type-checked is "potentially evaluated", meaning that there is a
11568 /// possibility that the code will actually be executable. Code in sizeof()
11569 /// expressions, code used only during overload resolution, etc., are not
11570 /// potentially evaluated. This routine will suppress such diagnostics or,
11571 /// in the absolutely nutty case of potentially potentially evaluated
11572 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
11575 /// This routine should be used for all diagnostics that describe the run-time
11576 /// behavior of a program, such as passing a non-POD value through an ellipsis.
11577 /// Failure to do so will likely result in spurious diagnostics or failures
11578 /// during overload resolution or within sizeof/alignof/typeof/typeid.
11579 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
11580 const PartialDiagnostic &PD) {
11581 switch (ExprEvalContexts.back().Context) {
11583 // The argument will never be evaluated, so don't complain.
11586 case ConstantEvaluated:
11587 // Relevant diagnostics should be produced by constant evaluation.
11590 case PotentiallyEvaluated:
11591 case PotentiallyEvaluatedIfUsed:
11592 if (Statement && getCurFunctionOrMethodDecl()) {
11593 FunctionScopes.back()->PossiblyUnreachableDiags.
11594 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
11605 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11606 CallExpr *CE, FunctionDecl *FD) {
11607 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11610 // If we're inside a decltype's expression, don't check for a valid return
11611 // type or construct temporaries until we know whether this is the last call.
11612 if (ExprEvalContexts.back().IsDecltype) {
11613 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11617 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
11622 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11623 : FD(FD), CE(CE) { }
11625 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11627 S.Diag(Loc, diag::err_call_incomplete_return)
11628 << T << CE->getSourceRange();
11632 S.Diag(Loc, diag::err_call_function_incomplete_return)
11633 << CE->getSourceRange() << FD->getDeclName() << T;
11634 S.Diag(FD->getLocation(),
11635 diag::note_function_with_incomplete_return_type_declared_here)
11636 << FD->getDeclName();
11638 } Diagnoser(FD, CE);
11640 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
11646 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
11647 // will prevent this condition from triggering, which is what we want.
11648 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11649 SourceLocation Loc;
11651 unsigned diagnostic = diag::warn_condition_is_assignment;
11652 bool IsOrAssign = false;
11654 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
11655 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
11658 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11660 // Greylist some idioms by putting them into a warning subcategory.
11661 if (ObjCMessageExpr *ME
11662 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11663 Selector Sel = ME->getSelector();
11665 // self = [<foo> init...]
11666 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
11667 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11669 // <foo> = [<bar> nextObject]
11670 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
11671 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11674 Loc = Op->getOperatorLoc();
11675 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
11676 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
11679 IsOrAssign = Op->getOperator() == OO_PipeEqual;
11680 Loc = Op->getOperatorLoc();
11681 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11682 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11684 // Not an assignment.
11688 Diag(Loc, diagnostic) << E->getSourceRange();
11690 SourceLocation Open = E->getLocStart();
11691 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11692 Diag(Loc, diag::note_condition_assign_silence)
11693 << FixItHint::CreateInsertion(Open, "(")
11694 << FixItHint::CreateInsertion(Close, ")");
11697 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11698 << FixItHint::CreateReplacement(Loc, "!=");
11700 Diag(Loc, diag::note_condition_assign_to_comparison)
11701 << FixItHint::CreateReplacement(Loc, "==");
11704 /// \brief Redundant parentheses over an equality comparison can indicate
11705 /// that the user intended an assignment used as condition.
11706 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
11707 // Don't warn if the parens came from a macro.
11708 SourceLocation parenLoc = ParenE->getLocStart();
11709 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11711 // Don't warn for dependent expressions.
11712 if (ParenE->isTypeDependent())
11715 Expr *E = ParenE->IgnoreParens();
11717 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
11718 if (opE->getOpcode() == BO_EQ &&
11719 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11720 == Expr::MLV_Valid) {
11721 SourceLocation Loc = opE->getOperatorLoc();
11723 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
11724 SourceRange ParenERange = ParenE->getSourceRange();
11725 Diag(Loc, diag::note_equality_comparison_silence)
11726 << FixItHint::CreateRemoval(ParenERange.getBegin())
11727 << FixItHint::CreateRemoval(ParenERange.getEnd());
11728 Diag(Loc, diag::note_equality_comparison_to_assign)
11729 << FixItHint::CreateReplacement(Loc, "=");
11733 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
11734 DiagnoseAssignmentAsCondition(E);
11735 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11736 DiagnoseEqualityWithExtraParens(parenE);
11738 ExprResult result = CheckPlaceholderExpr(E);
11739 if (result.isInvalid()) return ExprError();
11742 if (!E->isTypeDependent()) {
11743 if (getLangOpts().CPlusPlus)
11744 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11746 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11747 if (ERes.isInvalid())
11748 return ExprError();
11751 QualType T = E->getType();
11752 if (!T->isScalarType()) { // C99 6.8.4.1p1
11753 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11754 << T << E->getSourceRange();
11755 return ExprError();
11762 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
11765 return ExprError();
11767 return CheckBooleanCondition(SubExpr, Loc);
11771 /// A visitor for rebuilding a call to an __unknown_any expression
11772 /// to have an appropriate type.
11773 struct RebuildUnknownAnyFunction
11774 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11778 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11780 ExprResult VisitStmt(Stmt *S) {
11781 llvm_unreachable("unexpected statement!");
11784 ExprResult VisitExpr(Expr *E) {
11785 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11786 << E->getSourceRange();
11787 return ExprError();
11790 /// Rebuild an expression which simply semantically wraps another
11791 /// expression which it shares the type and value kind of.
11792 template <class T> ExprResult rebuildSugarExpr(T *E) {
11793 ExprResult SubResult = Visit(E->getSubExpr());
11794 if (SubResult.isInvalid()) return ExprError();
11796 Expr *SubExpr = SubResult.take();
11797 E->setSubExpr(SubExpr);
11798 E->setType(SubExpr->getType());
11799 E->setValueKind(SubExpr->getValueKind());
11800 assert(E->getObjectKind() == OK_Ordinary);
11804 ExprResult VisitParenExpr(ParenExpr *E) {
11805 return rebuildSugarExpr(E);
11808 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11809 return rebuildSugarExpr(E);
11812 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11813 ExprResult SubResult = Visit(E->getSubExpr());
11814 if (SubResult.isInvalid()) return ExprError();
11816 Expr *SubExpr = SubResult.take();
11817 E->setSubExpr(SubExpr);
11818 E->setType(S.Context.getPointerType(SubExpr->getType()));
11819 assert(E->getValueKind() == VK_RValue);
11820 assert(E->getObjectKind() == OK_Ordinary);
11824 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11825 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
11827 E->setType(VD->getType());
11829 assert(E->getValueKind() == VK_RValue);
11830 if (S.getLangOpts().CPlusPlus &&
11831 !(isa<CXXMethodDecl>(VD) &&
11832 cast<CXXMethodDecl>(VD)->isInstance()))
11833 E->setValueKind(VK_LValue);
11838 ExprResult VisitMemberExpr(MemberExpr *E) {
11839 return resolveDecl(E, E->getMemberDecl());
11842 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11843 return resolveDecl(E, E->getDecl());
11848 /// Given a function expression of unknown-any type, try to rebuild it
11849 /// to have a function type.
11850 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11851 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11852 if (Result.isInvalid()) return ExprError();
11853 return S.DefaultFunctionArrayConversion(Result.take());
11857 /// A visitor for rebuilding an expression of type __unknown_anytype
11858 /// into one which resolves the type directly on the referring
11859 /// expression. Strict preservation of the original source
11860 /// structure is not a goal.
11861 struct RebuildUnknownAnyExpr
11862 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
11866 /// The current destination type.
11869 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11870 : S(S), DestType(CastType) {}
11872 ExprResult VisitStmt(Stmt *S) {
11873 llvm_unreachable("unexpected statement!");
11876 ExprResult VisitExpr(Expr *E) {
11877 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11878 << E->getSourceRange();
11879 return ExprError();
11882 ExprResult VisitCallExpr(CallExpr *E);
11883 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
11885 /// Rebuild an expression which simply semantically wraps another
11886 /// expression which it shares the type and value kind of.
11887 template <class T> ExprResult rebuildSugarExpr(T *E) {
11888 ExprResult SubResult = Visit(E->getSubExpr());
11889 if (SubResult.isInvalid()) return ExprError();
11890 Expr *SubExpr = SubResult.take();
11891 E->setSubExpr(SubExpr);
11892 E->setType(SubExpr->getType());
11893 E->setValueKind(SubExpr->getValueKind());
11894 assert(E->getObjectKind() == OK_Ordinary);
11898 ExprResult VisitParenExpr(ParenExpr *E) {
11899 return rebuildSugarExpr(E);
11902 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11903 return rebuildSugarExpr(E);
11906 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11907 const PointerType *Ptr = DestType->getAs<PointerType>();
11909 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11910 << E->getSourceRange();
11911 return ExprError();
11913 assert(E->getValueKind() == VK_RValue);
11914 assert(E->getObjectKind() == OK_Ordinary);
11915 E->setType(DestType);
11917 // Build the sub-expression as if it were an object of the pointee type.
11918 DestType = Ptr->getPointeeType();
11919 ExprResult SubResult = Visit(E->getSubExpr());
11920 if (SubResult.isInvalid()) return ExprError();
11921 E->setSubExpr(SubResult.take());
11925 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
11927 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
11929 ExprResult VisitMemberExpr(MemberExpr *E) {
11930 return resolveDecl(E, E->getMemberDecl());
11933 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11934 return resolveDecl(E, E->getDecl());
11939 /// Rebuilds a call expression which yielded __unknown_anytype.
11940 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11941 Expr *CalleeExpr = E->getCallee();
11945 FK_FunctionPointer,
11950 QualType CalleeType = CalleeExpr->getType();
11951 if (CalleeType == S.Context.BoundMemberTy) {
11952 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11953 Kind = FK_MemberFunction;
11954 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11955 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11956 CalleeType = Ptr->getPointeeType();
11957 Kind = FK_FunctionPointer;
11959 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11960 Kind = FK_BlockPointer;
11962 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
11964 // Verify that this is a legal result type of a function.
11965 if (DestType->isArrayType() || DestType->isFunctionType()) {
11966 unsigned diagID = diag::err_func_returning_array_function;
11967 if (Kind == FK_BlockPointer)
11968 diagID = diag::err_block_returning_array_function;
11970 S.Diag(E->getExprLoc(), diagID)
11971 << DestType->isFunctionType() << DestType;
11972 return ExprError();
11975 // Otherwise, go ahead and set DestType as the call's result.
11976 E->setType(DestType.getNonLValueExprType(S.Context));
11977 E->setValueKind(Expr::getValueKindForType(DestType));
11978 assert(E->getObjectKind() == OK_Ordinary);
11980 // Rebuild the function type, replacing the result type with DestType.
11981 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
11983 S.Context.getFunctionType(DestType,
11984 ArrayRef<QualType>(Proto->arg_type_begin(),
11985 Proto->getNumArgs()),
11986 Proto->getExtProtoInfo());
11988 DestType = S.Context.getFunctionNoProtoType(DestType,
11989 FnType->getExtInfo());
11991 // Rebuild the appropriate pointer-to-function type.
11993 case FK_MemberFunction:
11997 case FK_FunctionPointer:
11998 DestType = S.Context.getPointerType(DestType);
12001 case FK_BlockPointer:
12002 DestType = S.Context.getBlockPointerType(DestType);
12006 // Finally, we can recurse.
12007 ExprResult CalleeResult = Visit(CalleeExpr);
12008 if (!CalleeResult.isUsable()) return ExprError();
12009 E->setCallee(CalleeResult.take());
12011 // Bind a temporary if necessary.
12012 return S.MaybeBindToTemporary(E);
12015 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
12016 // Verify that this is a legal result type of a call.
12017 if (DestType->isArrayType() || DestType->isFunctionType()) {
12018 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
12019 << DestType->isFunctionType() << DestType;
12020 return ExprError();
12023 // Rewrite the method result type if available.
12024 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
12025 assert(Method->getResultType() == S.Context.UnknownAnyTy);
12026 Method->setResultType(DestType);
12029 // Change the type of the message.
12030 E->setType(DestType.getNonReferenceType());
12031 E->setValueKind(Expr::getValueKindForType(DestType));
12033 return S.MaybeBindToTemporary(E);
12036 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
12037 // The only case we should ever see here is a function-to-pointer decay.
12038 if (E->getCastKind() == CK_FunctionToPointerDecay) {
12039 assert(E->getValueKind() == VK_RValue);
12040 assert(E->getObjectKind() == OK_Ordinary);
12042 E->setType(DestType);
12044 // Rebuild the sub-expression as the pointee (function) type.
12045 DestType = DestType->castAs<PointerType>()->getPointeeType();
12047 ExprResult Result = Visit(E->getSubExpr());
12048 if (!Result.isUsable()) return ExprError();
12050 E->setSubExpr(Result.take());
12052 } else if (E->getCastKind() == CK_LValueToRValue) {
12053 assert(E->getValueKind() == VK_RValue);
12054 assert(E->getObjectKind() == OK_Ordinary);
12056 assert(isa<BlockPointerType>(E->getType()));
12058 E->setType(DestType);
12060 // The sub-expression has to be a lvalue reference, so rebuild it as such.
12061 DestType = S.Context.getLValueReferenceType(DestType);
12063 ExprResult Result = Visit(E->getSubExpr());
12064 if (!Result.isUsable()) return ExprError();
12066 E->setSubExpr(Result.take());
12069 llvm_unreachable("Unhandled cast type!");
12073 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
12074 ExprValueKind ValueKind = VK_LValue;
12075 QualType Type = DestType;
12077 // We know how to make this work for certain kinds of decls:
12080 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
12081 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
12082 DestType = Ptr->getPointeeType();
12083 ExprResult Result = resolveDecl(E, VD);
12084 if (Result.isInvalid()) return ExprError();
12085 return S.ImpCastExprToType(Result.take(), Type,
12086 CK_FunctionToPointerDecay, VK_RValue);
12089 if (!Type->isFunctionType()) {
12090 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
12091 << VD << E->getSourceRange();
12092 return ExprError();
12095 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
12096 if (MD->isInstance()) {
12097 ValueKind = VK_RValue;
12098 Type = S.Context.BoundMemberTy;
12101 // Function references aren't l-values in C.
12102 if (!S.getLangOpts().CPlusPlus)
12103 ValueKind = VK_RValue;
12106 } else if (isa<VarDecl>(VD)) {
12107 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
12108 Type = RefTy->getPointeeType();
12109 } else if (Type->isFunctionType()) {
12110 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
12111 << VD << E->getSourceRange();
12112 return ExprError();
12117 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
12118 << VD << E->getSourceRange();
12119 return ExprError();
12122 VD->setType(DestType);
12124 E->setValueKind(ValueKind);
12128 /// Check a cast of an unknown-any type. We intentionally only
12129 /// trigger this for C-style casts.
12130 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12131 Expr *CastExpr, CastKind &CastKind,
12132 ExprValueKind &VK, CXXCastPath &Path) {
12133 // Rewrite the casted expression from scratch.
12134 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
12135 if (!result.isUsable()) return ExprError();
12137 CastExpr = result.take();
12138 VK = CastExpr->getValueKind();
12139 CastKind = CK_NoOp;
12144 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
12145 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
12148 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
12149 Expr *arg, QualType ¶mType) {
12150 // If the syntactic form of the argument is not an explicit cast of
12151 // any sort, just do default argument promotion.
12152 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
12154 ExprResult result = DefaultArgumentPromotion(arg);
12155 if (result.isInvalid()) return ExprError();
12156 paramType = result.get()->getType();
12160 // Otherwise, use the type that was written in the explicit cast.
12161 assert(!arg->hasPlaceholderType());
12162 paramType = castArg->getTypeAsWritten();
12164 // Copy-initialize a parameter of that type.
12165 InitializedEntity entity =
12166 InitializedEntity::InitializeParameter(Context, paramType,
12167 /*consumed*/ false);
12168 return PerformCopyInitialization(entity, callLoc, Owned(arg));
12171 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
12173 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
12175 E = E->IgnoreParenImpCasts();
12176 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
12177 E = call->getCallee();
12178 diagID = diag::err_uncasted_call_of_unknown_any;
12184 SourceLocation loc;
12186 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
12187 loc = ref->getLocation();
12188 d = ref->getDecl();
12189 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
12190 loc = mem->getMemberLoc();
12191 d = mem->getMemberDecl();
12192 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
12193 diagID = diag::err_uncasted_call_of_unknown_any;
12194 loc = msg->getSelectorStartLoc();
12195 d = msg->getMethodDecl();
12197 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
12198 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
12199 << orig->getSourceRange();
12200 return ExprError();
12203 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12204 << E->getSourceRange();
12205 return ExprError();
12208 S.Diag(loc, diagID) << d << orig->getSourceRange();
12210 // Never recoverable.
12211 return ExprError();
12214 /// Check for operands with placeholder types and complain if found.
12215 /// Returns true if there was an error and no recovery was possible.
12216 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
12217 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
12218 if (!placeholderType) return Owned(E);
12220 switch (placeholderType->getKind()) {
12222 // Overloaded expressions.
12223 case BuiltinType::Overload: {
12224 // Try to resolve a single function template specialization.
12225 // This is obligatory.
12226 ExprResult result = Owned(E);
12227 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
12230 // If that failed, try to recover with a call.
12232 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
12233 /*complain*/ true);
12238 // Bound member functions.
12239 case BuiltinType::BoundMember: {
12240 ExprResult result = Owned(E);
12241 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
12242 /*complain*/ true);
12246 // ARC unbridged casts.
12247 case BuiltinType::ARCUnbridgedCast: {
12248 Expr *realCast = stripARCUnbridgedCast(E);
12249 diagnoseARCUnbridgedCast(realCast);
12250 return Owned(realCast);
12253 // Expressions of unknown type.
12254 case BuiltinType::UnknownAny:
12255 return diagnoseUnknownAnyExpr(*this, E);
12258 case BuiltinType::PseudoObject:
12259 return checkPseudoObjectRValue(E);
12261 case BuiltinType::BuiltinFn:
12262 Diag(E->getLocStart(), diag::err_builtin_fn_use);
12263 return ExprError();
12265 // Everything else should be impossible.
12266 #define BUILTIN_TYPE(Id, SingletonId) \
12267 case BuiltinType::Id:
12268 #define PLACEHOLDER_TYPE(Id, SingletonId)
12269 #include "clang/AST/BuiltinTypes.def"
12273 llvm_unreachable("invalid placeholder type!");
12276 bool Sema::CheckCaseExpression(Expr *E) {
12277 if (E->isTypeDependent())
12279 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
12280 return E->getType()->isIntegralOrEnumerationType();
12284 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
12286 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
12287 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
12288 "Unknown Objective-C Boolean value!");
12289 QualType BoolT = Context.ObjCBuiltinBoolTy;
12290 if (!Context.getBOOLDecl()) {
12291 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
12292 Sema::LookupOrdinaryName);
12293 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
12294 NamedDecl *ND = Result.getFoundDecl();
12295 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
12296 Context.setBOOLDecl(TD);
12299 if (Context.getBOOLDecl())
12300 BoolT = Context.getBOOLType();
12301 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,