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 //===----------------------------------------------------------------------===//
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/Basic/PartialDiagnostic.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Lex/LiteralSupport.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Parse/DeclSpec.h"
28 #include "clang/Parse/Designator.h"
29 #include "clang/Parse/Scope.h"
30 #include "clang/Parse/Template.h"
31 using namespace clang;
34 /// \brief Determine whether the use of this declaration is valid, and
35 /// emit any corresponding diagnostics.
37 /// This routine diagnoses various problems with referencing
38 /// declarations that can occur when using a declaration. For example,
39 /// it might warn if a deprecated or unavailable declaration is being
40 /// used, or produce an error (and return true) if a C++0x deleted
41 /// function is being used.
43 /// If IgnoreDeprecated is set to true, this should not want about deprecated
46 /// \returns true if there was an error (this declaration cannot be
47 /// referenced), false otherwise.
49 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
50 // See if the decl is deprecated.
51 if (D->getAttr<DeprecatedAttr>()) {
52 EmitDeprecationWarning(D, Loc);
55 // See if the decl is unavailable
56 if (D->getAttr<UnavailableAttr>()) {
57 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
58 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
61 // See if this is a deleted function.
62 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
63 if (FD->isDeleted()) {
64 Diag(Loc, diag::err_deleted_function_use);
65 Diag(D->getLocation(), diag::note_unavailable_here) << true;
73 /// DiagnoseSentinelCalls - This routine checks on method dispatch calls
74 /// (and other functions in future), which have been declared with sentinel
75 /// attribute. It warns if call does not have the sentinel argument.
77 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
78 Expr **Args, unsigned NumArgs) {
79 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
82 int sentinelPos = attr->getSentinel();
83 int nullPos = attr->getNullPos();
85 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
86 // base class. Then we won't be needing two versions of the same code.
88 bool warnNotEnoughArgs = false;
90 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
91 // skip over named parameters.
92 ObjCMethodDecl::param_iterator P, E = MD->param_end();
93 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
99 warnNotEnoughArgs = (P != E || i >= NumArgs);
101 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
102 // skip over named parameters.
103 ObjCMethodDecl::param_iterator P, E = FD->param_end();
104 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
110 warnNotEnoughArgs = (P != E || i >= NumArgs);
111 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
112 // block or function pointer call.
113 QualType Ty = V->getType();
114 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
115 const FunctionType *FT = Ty->isFunctionPointerType()
116 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
117 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
118 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
119 unsigned NumArgsInProto = Proto->getNumArgs();
121 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
127 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
129 if (Ty->isBlockPointerType())
136 if (warnNotEnoughArgs) {
137 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
138 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
142 while (sentinelPos > 0 && i < NumArgs-1) {
146 if (sentinelPos > 0) {
147 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
148 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
151 while (i < NumArgs-1) {
155 Expr *sentinelExpr = Args[sentinel];
156 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
157 (!sentinelExpr->getType()->isPointerType() ||
158 !sentinelExpr->isNullPointerConstant(Context,
159 Expr::NPC_ValueDependentIsNull)))) {
160 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
161 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
166 SourceRange Sema::getExprRange(ExprTy *E) const {
167 Expr *Ex = (Expr *)E;
168 return Ex? Ex->getSourceRange() : SourceRange();
171 //===----------------------------------------------------------------------===//
172 // Standard Promotions and Conversions
173 //===----------------------------------------------------------------------===//
175 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
176 void Sema::DefaultFunctionArrayConversion(Expr *&E) {
177 QualType Ty = E->getType();
178 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
180 if (Ty->isFunctionType())
181 ImpCastExprToType(E, Context.getPointerType(Ty),
182 CastExpr::CK_FunctionToPointerDecay);
183 else if (Ty->isArrayType()) {
184 // In C90 mode, arrays only promote to pointers if the array expression is
185 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
186 // type 'array of type' is converted to an expression that has type 'pointer
187 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
188 // that has type 'array of type' ...". The relevant change is "an lvalue"
189 // (C90) to "an expression" (C99).
192 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
193 // T" can be converted to an rvalue of type "pointer to T".
195 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
196 E->isLvalue(Context) == Expr::LV_Valid)
197 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
198 CastExpr::CK_ArrayToPointerDecay);
202 /// UsualUnaryConversions - Performs various conversions that are common to most
203 /// operators (C99 6.3). The conversions of array and function types are
204 /// sometimes surpressed. For example, the array->pointer conversion doesn't
205 /// apply if the array is an argument to the sizeof or address (&) operators.
206 /// In these instances, this routine should *not* be called.
207 Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
208 QualType Ty = Expr->getType();
209 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
213 // The following may be used in an expression wherever an int or
214 // unsigned int may be used:
215 // - an object or expression with an integer type whose integer
216 // conversion rank is less than or equal to the rank of int
218 // - A bit-field of type _Bool, int, signed int, or unsigned int.
220 // If an int can represent all values of the original type, the
221 // value is converted to an int; otherwise, it is converted to an
222 // unsigned int. These are called the integer promotions. All
223 // other types are unchanged by the integer promotions.
224 QualType PTy = Context.isPromotableBitField(Expr);
226 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
229 if (Ty->isPromotableIntegerType()) {
230 QualType PT = Context.getPromotedIntegerType(Ty);
231 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
235 DefaultFunctionArrayConversion(Expr);
239 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
240 /// do not have a prototype. Arguments that have type float are promoted to
241 /// double. All other argument types are converted by UsualUnaryConversions().
242 void Sema::DefaultArgumentPromotion(Expr *&Expr) {
243 QualType Ty = Expr->getType();
244 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
246 // If this is a 'float' (CVR qualified or typedef) promote to double.
247 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
248 if (BT->getKind() == BuiltinType::Float)
249 return ImpCastExprToType(Expr, Context.DoubleTy,
250 CastExpr::CK_FloatingCast);
252 UsualUnaryConversions(Expr);
255 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
256 /// will warn if the resulting type is not a POD type, and rejects ObjC
257 /// interfaces passed by value. This returns true if the argument type is
258 /// completely illegal.
259 bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
260 DefaultArgumentPromotion(Expr);
262 if (Expr->getType()->isObjCInterfaceType() &&
263 DiagRuntimeBehavior(Expr->getLocStart(),
264 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
265 << Expr->getType() << CT))
268 if (!Expr->getType()->isPODType() &&
269 DiagRuntimeBehavior(Expr->getLocStart(),
270 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
271 << Expr->getType() << CT))
278 /// UsualArithmeticConversions - Performs various conversions that are common to
279 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
280 /// routine returns the first non-arithmetic type found. The client is
281 /// responsible for emitting appropriate error diagnostics.
282 /// FIXME: verify the conversion rules for "complex int" are consistent with
284 QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
287 UsualUnaryConversions(lhsExpr);
289 UsualUnaryConversions(rhsExpr);
291 // For conversion purposes, we ignore any qualifiers.
292 // For example, "const float" and "float" are equivalent.
294 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
296 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
298 // If both types are identical, no conversion is needed.
302 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
303 // The caller can deal with this (e.g. pointer + int).
304 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
307 // Perform bitfield promotions.
308 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
309 if (!LHSBitfieldPromoteTy.isNull())
310 lhs = LHSBitfieldPromoteTy;
311 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
312 if (!RHSBitfieldPromoteTy.isNull())
313 rhs = RHSBitfieldPromoteTy;
315 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
317 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
318 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
322 //===----------------------------------------------------------------------===//
323 // Semantic Analysis for various Expression Types
324 //===----------------------------------------------------------------------===//
327 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
328 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
329 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
330 /// multiple tokens. However, the common case is that StringToks points to one
333 Action::OwningExprResult
334 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
335 assert(NumStringToks && "Must have at least one string!");
337 StringLiteralParser Literal(StringToks, NumStringToks, PP);
338 if (Literal.hadError)
341 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
342 for (unsigned i = 0; i != NumStringToks; ++i)
343 StringTokLocs.push_back(StringToks[i].getLocation());
345 QualType StrTy = Context.CharTy;
346 if (Literal.AnyWide) StrTy = Context.getWCharType();
347 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
349 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
350 if (getLangOptions().CPlusPlus)
353 // Get an array type for the string, according to C99 6.4.5. This includes
354 // the nul terminator character as well as the string length for pascal
356 StrTy = Context.getConstantArrayType(StrTy,
357 llvm::APInt(32, Literal.GetNumStringChars()+1),
358 ArrayType::Normal, 0);
360 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
361 return Owned(StringLiteral::Create(Context, Literal.GetString(),
362 Literal.GetStringLength(),
363 Literal.AnyWide, StrTy,
365 StringTokLocs.size()));
368 /// ShouldSnapshotBlockValueReference - Return true if a reference inside of
369 /// CurBlock to VD should cause it to be snapshotted (as we do for auto
370 /// variables defined outside the block) or false if this is not needed (e.g.
371 /// for values inside the block or for globals).
373 /// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
376 static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
378 // If the value is defined inside the block, we couldn't snapshot it even if
380 if (CurBlock->TheDecl == VD->getDeclContext())
383 // If this is an enum constant or function, it is constant, don't snapshot.
384 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
387 // If this is a reference to an extern, static, or global variable, no need to
389 // FIXME: What about 'const' variables in C++?
390 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
391 if (!Var->hasLocalStorage())
394 // Blocks that have these can't be constant.
395 CurBlock->hasBlockDeclRefExprs = true;
397 // If we have nested blocks, the decl may be declared in an outer block (in
398 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
399 // be defined outside all of the current blocks (in which case the blocks do
400 // all get the bit). Walk the nesting chain.
401 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
402 NextBlock = NextBlock->PrevBlockInfo) {
403 // If we found the defining block for the variable, don't mark the block as
404 // having a reference outside it.
405 if (NextBlock->TheDecl == VD->getDeclContext())
408 // Otherwise, the DeclRef from the inner block causes the outer one to need
409 // a snapshot as well.
410 NextBlock->hasBlockDeclRefExprs = true;
418 /// BuildDeclRefExpr - Build a DeclRefExpr.
419 Sema::OwningExprResult
420 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
421 const CXXScopeSpec *SS) {
422 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
424 diag::err_auto_variable_cannot_appear_in_own_initializer)
429 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
430 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
431 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
432 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
433 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
434 << D->getIdentifier() << FD->getDeclName();
435 Diag(D->getLocation(), diag::note_local_variable_declared_here)
436 << D->getIdentifier();
443 MarkDeclarationReferenced(Loc, D);
445 return Owned(DeclRefExpr::Create(Context,
446 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
447 SS? SS->getRange() : SourceRange(),
451 /// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
452 /// variable corresponding to the anonymous union or struct whose type
454 static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
455 RecordDecl *Record) {
456 assert(Record->isAnonymousStructOrUnion() &&
457 "Record must be an anonymous struct or union!");
459 // FIXME: Once Decls are directly linked together, this will be an O(1)
460 // operation rather than a slow walk through DeclContext's vector (which
461 // itself will be eliminated). DeclGroups might make this even better.
462 DeclContext *Ctx = Record->getDeclContext();
463 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
464 DEnd = Ctx->decls_end();
467 // The object for the anonymous struct/union directly
468 // follows its type in the list of declarations.
470 assert(D != DEnd && "Missing object for anonymous record");
471 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
476 assert(false && "Missing object for anonymous record");
480 /// \brief Given a field that represents a member of an anonymous
481 /// struct/union, build the path from that field's context to the
484 /// Construct the sequence of field member references we'll have to
485 /// perform to get to the field in the anonymous union/struct. The
486 /// list of members is built from the field outward, so traverse it
487 /// backwards to go from an object in the current context to the field
490 /// \returns The variable from which the field access should begin,
491 /// for an anonymous struct/union that is not a member of another
492 /// class. Otherwise, returns NULL.
493 VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
494 llvm::SmallVectorImpl<FieldDecl *> &Path) {
495 assert(Field->getDeclContext()->isRecord() &&
496 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
497 && "Field must be stored inside an anonymous struct or union");
499 Path.push_back(Field);
500 VarDecl *BaseObject = 0;
501 DeclContext *Ctx = Field->getDeclContext();
503 RecordDecl *Record = cast<RecordDecl>(Ctx);
504 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
505 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
506 Path.push_back(AnonField);
508 BaseObject = cast<VarDecl>(AnonObject);
511 Ctx = Ctx->getParent();
512 } while (Ctx->isRecord() &&
513 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
518 Sema::OwningExprResult
519 Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
521 Expr *BaseObjectExpr,
522 SourceLocation OpLoc) {
523 llvm::SmallVector<FieldDecl *, 4> AnonFields;
524 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
527 // Build the expression that refers to the base object, from
528 // which we will build a sequence of member references to each
529 // of the anonymous union objects and, eventually, the field we
530 // found via name lookup.
531 bool BaseObjectIsPointer = false;
532 Qualifiers BaseQuals;
534 // BaseObject is an anonymous struct/union variable (and is,
535 // therefore, not part of another non-anonymous record).
536 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
537 MarkDeclarationReferenced(Loc, BaseObject);
538 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
541 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
542 } else if (BaseObjectExpr) {
543 // The caller provided the base object expression. Determine
544 // whether its a pointer and whether it adds any qualifiers to the
545 // anonymous struct/union fields we're looking into.
546 QualType ObjectType = BaseObjectExpr->getType();
547 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
548 BaseObjectIsPointer = true;
549 ObjectType = ObjectPtr->getPointeeType();
552 = Context.getCanonicalType(ObjectType).getQualifiers();
554 // We've found a member of an anonymous struct/union that is
555 // inside a non-anonymous struct/union, so in a well-formed
556 // program our base object expression is "this".
557 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
558 if (!MD->isStatic()) {
559 QualType AnonFieldType
560 = Context.getTagDeclType(
561 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
562 QualType ThisType = Context.getTagDeclType(MD->getParent());
563 if ((Context.getCanonicalType(AnonFieldType)
564 == Context.getCanonicalType(ThisType)) ||
565 IsDerivedFrom(ThisType, AnonFieldType)) {
566 // Our base object expression is "this".
567 BaseObjectExpr = new (Context) CXXThisExpr(Loc,
568 MD->getThisType(Context));
569 BaseObjectIsPointer = true;
572 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
573 << Field->getDeclName());
575 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
579 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
580 << Field->getDeclName());
583 // Build the implicit member references to the field of the
584 // anonymous struct/union.
585 Expr *Result = BaseObjectExpr;
586 Qualifiers ResultQuals = BaseQuals;
587 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
588 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
590 QualType MemberType = (*FI)->getType();
591 Qualifiers MemberTypeQuals =
592 Context.getCanonicalType(MemberType).getQualifiers();
594 // CVR attributes from the base are picked up by members,
595 // except that 'mutable' members don't pick up 'const'.
596 if ((*FI)->isMutable())
597 ResultQuals.removeConst();
599 // GC attributes are never picked up by members.
600 ResultQuals.removeObjCGCAttr();
602 // TR 18037 does not allow fields to be declared with address spaces.
603 assert(!MemberTypeQuals.hasAddressSpace());
605 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
606 if (NewQuals != MemberTypeQuals)
607 MemberType = Context.getQualifiedType(MemberType, NewQuals);
609 MarkDeclarationReferenced(Loc, *FI);
610 PerformObjectMemberConversion(Result, *FI);
611 // FIXME: Might this end up being a qualified name?
612 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
614 BaseObjectIsPointer = false;
615 ResultQuals = NewQuals;
618 return Owned(Result);
621 /// Decomposes the given name into a DeclarationName, its location, and
622 /// possibly a list of template arguments.
624 /// If this produces template arguments, it is permitted to call
625 /// DecomposeTemplateName.
627 /// This actually loses a lot of source location information for
628 /// non-standard name kinds; we should consider preserving that in
630 static void DecomposeUnqualifiedId(Sema &SemaRef,
631 const UnqualifiedId &Id,
632 TemplateArgumentListInfo &Buffer,
633 DeclarationName &Name,
634 SourceLocation &NameLoc,
635 const TemplateArgumentListInfo *&TemplateArgs) {
636 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
637 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
638 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
640 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
641 Id.TemplateId->getTemplateArgs(),
642 Id.TemplateId->NumArgs);
643 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
644 TemplateArgsPtr.release();
647 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
649 Name = SemaRef.Context.getNameForTemplate(TName);
650 NameLoc = Id.TemplateId->TemplateNameLoc;
651 TemplateArgs = &Buffer;
653 Name = SemaRef.GetNameFromUnqualifiedId(Id);
654 NameLoc = Id.StartLocation;
659 /// Decompose the given template name into a list of lookup results.
661 /// The unqualified ID must name a non-dependent template, which can
662 /// be more easily tested by checking whether DecomposeUnqualifiedId
663 /// found template arguments.
664 static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
665 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
667 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
669 if (TemplateDecl *TD = TName.getAsTemplateDecl())
671 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
672 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
679 static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
680 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
681 E = Record->bases_end(); I != E; ++I) {
682 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
683 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
684 if (!BaseRT) return false;
686 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
687 if (!BaseRecord->isDefinition() ||
688 !IsFullyFormedScope(SemaRef, BaseRecord))
695 /// Determines whether we can lookup this id-expression now or whether
696 /// we have to wait until template instantiation is complete.
697 static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
698 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
700 // If the qualifier scope isn't computable, it's definitely dependent.
701 if (!DC) return true;
703 // If the qualifier scope doesn't name a record, we can always look into it.
704 if (!isa<CXXRecordDecl>(DC)) return false;
706 // We can't look into record types unless they're fully-formed.
707 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
712 /// Determines if the given class is provably not derived from all of
713 /// the prospective base classes.
714 static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
715 CXXRecordDecl *Record,
716 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
717 if (Bases.count(Record->getCanonicalDecl()))
720 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
721 if (!RD) return false;
722 Record = cast<CXXRecordDecl>(RD);
724 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
725 E = Record->bases_end(); I != E; ++I) {
726 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
727 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
728 if (!BaseRT) return false;
730 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
731 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
738 /// Determines if this is an instance member of a class.
739 static bool IsInstanceMember(NamedDecl *D) {
740 assert(D->isCXXClassMember() &&
741 "checking whether non-member is instance member");
743 if (isa<FieldDecl>(D)) return true;
745 if (isa<CXXMethodDecl>(D))
746 return !cast<CXXMethodDecl>(D)->isStatic();
748 if (isa<FunctionTemplateDecl>(D)) {
749 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
750 return !cast<CXXMethodDecl>(D)->isStatic();
757 /// The reference is definitely not an instance member access.
760 /// The reference may be an implicit instance member access.
763 /// The reference may be to an instance member, but it is invalid if
764 /// so, because the context is not an instance method.
765 IMA_Mixed_StaticContext,
767 /// The reference may be to an instance member, but it is invalid if
768 /// so, because the context is from an unrelated class.
771 /// The reference is definitely an implicit instance member access.
774 /// The reference may be to an unresolved using declaration.
777 /// The reference may be to an unresolved using declaration and the
778 /// context is not an instance method.
779 IMA_Unresolved_StaticContext,
781 /// The reference is to a member of an anonymous structure in a
782 /// non-class context.
785 /// All possible referrents are instance members and the current
786 /// context is not an instance method.
787 IMA_Error_StaticContext,
789 /// All possible referrents are instance members of an unrelated
794 /// The given lookup names class member(s) and is not being used for
795 /// an address-of-member expression. Classify the type of access
796 /// according to whether it's possible that this reference names an
797 /// instance member. This is best-effort; it is okay to
798 /// conservatively answer "yes", in which case some errors will simply
799 /// not be caught until template-instantiation.
800 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
801 const LookupResult &R) {
802 assert(!R.empty() && (*R.begin())->isCXXClassMember());
804 bool isStaticContext =
805 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
806 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
808 if (R.isUnresolvableResult())
809 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
811 // Collect all the declaring classes of instance members we find.
812 bool hasNonInstance = false;
813 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
814 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
815 NamedDecl *D = (*I)->getUnderlyingDecl();
816 if (IsInstanceMember(D)) {
817 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
819 // If this is a member of an anonymous record, move out to the
820 // innermost non-anonymous struct or union. If there isn't one,
821 // that's a special case.
822 while (R->isAnonymousStructOrUnion()) {
823 R = dyn_cast<CXXRecordDecl>(R->getParent());
824 if (!R) return IMA_AnonymousMember;
826 Classes.insert(R->getCanonicalDecl());
829 hasNonInstance = true;
832 // If we didn't find any instance members, it can't be an implicit
837 // If the current context is not an instance method, it can't be
838 // an implicit member reference.
840 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
842 // If we can prove that the current context is unrelated to all the
843 // declaring classes, it can't be an implicit member reference (in
844 // which case it's an error if any of those members are selected).
845 if (IsProvablyNotDerivedFrom(SemaRef,
846 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
848 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
850 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
853 /// Diagnose a reference to a field with no object available.
854 static void DiagnoseInstanceReference(Sema &SemaRef,
855 const CXXScopeSpec &SS,
856 const LookupResult &R) {
857 SourceLocation Loc = R.getNameLoc();
858 SourceRange Range(Loc);
859 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
861 if (R.getAsSingle<FieldDecl>()) {
862 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
863 if (MD->isStatic()) {
864 // "invalid use of member 'x' in static member function"
865 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
866 << Range << R.getLookupName();
871 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
872 << R.getLookupName() << Range;
876 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
879 /// Diagnose an empty lookup.
881 /// \return false if new lookup candidates were found
882 bool Sema::DiagnoseEmptyLookup(Scope *S, const CXXScopeSpec &SS,
884 DeclarationName Name = R.getLookupName();
886 unsigned diagnostic = diag::err_undeclared_var_use;
887 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
888 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
889 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
890 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
891 diagnostic = diag::err_undeclared_use;
892 diagnostic_suggest = diag::err_undeclared_use_suggest;
895 // If the original lookup was an unqualified lookup, fake an
896 // unqualified lookup. This is useful when (for example) the
897 // original lookup would not have found something because it was a
899 for (DeclContext *DC = SS.isEmpty()? CurContext : 0;
900 DC; DC = DC->getParent()) {
901 if (isa<CXXRecordDecl>(DC)) {
902 LookupQualifiedName(R, DC);
905 // Don't give errors about ambiguities in this lookup.
906 R.suppressDiagnostics();
908 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
909 bool isInstance = CurMethod &&
910 CurMethod->isInstance() &&
911 DC == CurMethod->getParent();
913 // Give a code modification hint to insert 'this->'.
914 // TODO: fixit for inserting 'Base<T>::' in the other cases.
915 // Actually quite difficult!
917 Diag(R.getNameLoc(), diagnostic) << Name
918 << CodeModificationHint::CreateInsertion(R.getNameLoc(),
921 Diag(R.getNameLoc(), diagnostic) << Name;
923 // Do we really want to note all of these?
924 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
925 Diag((*I)->getLocation(), diag::note_dependent_var_use);
927 // Tell the callee to try to recover.
933 // We didn't find anything, so try to correct for a typo.
934 if (S && CorrectTypo(R, S, &SS)) {
935 if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
937 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
938 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
939 R.getLookupName().getAsString());
941 Diag(R.getNameLoc(), diag::err_no_member_suggest)
942 << Name << computeDeclContext(SS, false) << R.getLookupName()
944 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
945 R.getLookupName().getAsString());
947 // Tell the callee to try to recover.
951 if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
952 // FIXME: If we ended up with a typo for a type name or
953 // Objective-C class name, we're in trouble because the parser
954 // is in the wrong place to recover. Suggest the typo
955 // correction, but don't make it a fix-it since we're not going
956 // to recover well anyway.
958 Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
960 Diag(R.getNameLoc(), diag::err_no_member_suggest)
961 << Name << computeDeclContext(SS, false) << R.getLookupName()
964 // Don't try to recover; it won't work.
971 // Emit a special diagnostic for failed member lookups.
972 // FIXME: computing the declaration context might fail here (?)
974 Diag(R.getNameLoc(), diag::err_no_member)
975 << Name << computeDeclContext(SS, false)
980 // Give up, we can't recover.
981 Diag(R.getNameLoc(), diagnostic) << Name;
985 Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
986 const CXXScopeSpec &SS,
988 bool HasTrailingLParen,
989 bool isAddressOfOperand) {
990 assert(!(isAddressOfOperand && HasTrailingLParen) &&
991 "cannot be direct & operand and have a trailing lparen");
996 TemplateArgumentListInfo TemplateArgsBuffer;
998 // Decompose the UnqualifiedId into the following data.
999 DeclarationName Name;
1000 SourceLocation NameLoc;
1001 const TemplateArgumentListInfo *TemplateArgs;
1002 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
1003 Name, NameLoc, TemplateArgs);
1005 IdentifierInfo *II = Name.getAsIdentifierInfo();
1007 // C++ [temp.dep.expr]p3:
1008 // An id-expression is type-dependent if it contains:
1009 // -- a nested-name-specifier that contains a class-name that
1010 // names a dependent type.
1011 // Determine whether this is a member of an unknown specialization;
1012 // we need to handle these differently.
1013 if (SS.isSet() && IsDependentIdExpression(*this, SS)) {
1014 return ActOnDependentIdExpression(SS, Name, NameLoc,
1019 // Perform the required lookup.
1020 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1022 // Just re-use the lookup done by isTemplateName.
1023 DecomposeTemplateName(R, Id);
1025 LookupParsedName(R, S, &SS, true);
1027 // If this reference is in an Objective-C method, then we need to do
1028 // some special Objective-C lookup, too.
1029 if (!SS.isSet() && II && getCurMethodDecl()) {
1030 OwningExprResult E(LookupInObjCMethod(R, S, II));
1034 Expr *Ex = E.takeAs<Expr>();
1035 if (Ex) return Owned(Ex);
1039 if (R.isAmbiguous())
1042 // Determine whether this name might be a candidate for
1043 // argument-dependent lookup.
1044 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1046 if (R.empty() && !ADL) {
1047 // Otherwise, this could be an implicitly declared function reference (legal
1048 // in C90, extension in C99, forbidden in C++).
1049 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1050 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1051 if (D) R.addDecl(D);
1054 // If this name wasn't predeclared and if this is not a function
1055 // call, diagnose the problem.
1057 if (DiagnoseEmptyLookup(S, SS, R))
1060 assert(!R.empty() &&
1061 "DiagnoseEmptyLookup returned false but added no results");
1065 // This is guaranteed from this point on.
1066 assert(!R.empty() || ADL);
1068 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
1069 // Warn about constructs like:
1070 // if (void *X = foo()) { ... } else { X }.
1071 // In the else block, the pointer is always false.
1073 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1075 while (CheckS && CheckS->getControlParent()) {
1076 if (CheckS->isWithinElse() &&
1077 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
1078 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
1079 << Var->getDeclName()
1080 << (Var->getType()->isPointerType()? 2 :
1081 Var->getType()->isBooleanType()? 1 : 0));
1085 // Move to the parent of this scope.
1086 CheckS = CheckS->getParent();
1089 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
1090 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1091 // C99 DR 316 says that, if a function type comes from a
1092 // function definition (without a prototype), that type is only
1093 // used for checking compatibility. Therefore, when referencing
1094 // the function, we pretend that we don't have the full function
1096 if (DiagnoseUseOfDecl(Func, NameLoc))
1099 QualType T = Func->getType();
1100 QualType NoProtoType = T;
1101 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
1102 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
1103 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
1107 // Check whether this might be a C++ implicit instance member access.
1108 // C++ [expr.prim.general]p6:
1109 // Within the definition of a non-static member function, an
1110 // identifier that names a non-static member is transformed to a
1111 // class member access expression.
1112 // But note that &SomeClass::foo is grammatically distinct, even
1113 // though we don't parse it that way.
1114 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1115 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
1116 if (!isAbstractMemberPointer)
1117 return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
1121 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
1123 return BuildDeclarationNameExpr(SS, R, ADL);
1126 /// Builds an expression which might be an implicit member expression.
1127 Sema::OwningExprResult
1128 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1130 const TemplateArgumentListInfo *TemplateArgs) {
1131 switch (ClassifyImplicitMemberAccess(*this, R)) {
1133 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1135 case IMA_AnonymousMember:
1136 assert(R.isSingleResult());
1137 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1138 R.getAsSingle<FieldDecl>());
1141 case IMA_Mixed_Unrelated:
1142 case IMA_Unresolved:
1143 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1146 case IMA_Mixed_StaticContext:
1147 case IMA_Unresolved_StaticContext:
1149 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1150 return BuildDeclarationNameExpr(SS, R, false);
1152 case IMA_Error_StaticContext:
1153 case IMA_Error_Unrelated:
1154 DiagnoseInstanceReference(*this, SS, R);
1158 llvm_unreachable("unexpected instance member access kind");
1162 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1163 /// declaration name, generally during template instantiation.
1164 /// There's a large number of things which don't need to be done along
1166 Sema::OwningExprResult
1167 Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1168 DeclarationName Name,
1169 SourceLocation NameLoc) {
1171 if (!(DC = computeDeclContext(SS, false)) ||
1172 DC->isDependentContext() ||
1173 RequireCompleteDeclContext(SS))
1174 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1176 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1177 LookupQualifiedName(R, DC);
1179 if (R.isAmbiguous())
1183 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1187 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1190 /// LookupInObjCMethod - The parser has read a name in, and Sema has
1191 /// detected that we're currently inside an ObjC method. Perform some
1192 /// additional lookup.
1194 /// Ideally, most of this would be done by lookup, but there's
1195 /// actually quite a lot of extra work involved.
1197 /// Returns a null sentinel to indicate trivial success.
1198 Sema::OwningExprResult
1199 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1200 IdentifierInfo *II) {
1201 SourceLocation Loc = Lookup.getNameLoc();
1203 // There are two cases to handle here. 1) scoped lookup could have failed,
1204 // in which case we should look for an ivar. 2) scoped lookup could have
1205 // found a decl, but that decl is outside the current instance method (i.e.
1206 // a global variable). In these two cases, we do a lookup for an ivar with
1207 // this name, if the lookup sucedes, we replace it our current decl.
1209 // If we're in a class method, we don't normally want to look for
1210 // ivars. But if we don't find anything else, and there's an
1211 // ivar, that's an error.
1212 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1216 LookForIvars = true;
1217 else if (IsClassMethod)
1218 LookForIvars = false;
1220 LookForIvars = (Lookup.isSingleResult() &&
1221 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1224 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1225 ObjCInterfaceDecl *ClassDeclared;
1226 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1227 // Diagnose using an ivar in a class method.
1229 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1230 << IV->getDeclName());
1232 // If we're referencing an invalid decl, just return this as a silent
1233 // error node. The error diagnostic was already emitted on the decl.
1234 if (IV->isInvalidDecl())
1237 // Check if referencing a field with __attribute__((deprecated)).
1238 if (DiagnoseUseOfDecl(IV, Loc))
1241 // Diagnose the use of an ivar outside of the declaring class.
1242 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1243 ClassDeclared != IFace)
1244 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1246 // FIXME: This should use a new expr for a direct reference, don't
1247 // turn this into Self->ivar, just return a BareIVarExpr or something.
1248 IdentifierInfo &II = Context.Idents.get("self");
1249 UnqualifiedId SelfName;
1250 SelfName.setIdentifier(&II, SourceLocation());
1251 CXXScopeSpec SelfScopeSpec;
1252 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1253 SelfName, false, false);
1254 MarkDeclarationReferenced(Loc, IV);
1255 return Owned(new (Context)
1256 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1257 SelfExpr.takeAs<Expr>(), true, true));
1259 } else if (getCurMethodDecl()->isInstanceMethod()) {
1260 // We should warn if a local variable hides an ivar.
1261 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1262 ObjCInterfaceDecl *ClassDeclared;
1263 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1264 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1265 IFace == ClassDeclared)
1266 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1270 // Needed to implement property "super.method" notation.
1271 if (Lookup.empty() && II->isStr("super")) {
1274 if (getCurMethodDecl()->isInstanceMethod())
1275 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1276 getCurMethodDecl()->getClassInterface()));
1278 T = Context.getObjCClassType();
1279 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1282 // Sentinel value saying that we didn't do anything special.
1283 return Owned((Expr*) 0);
1286 /// \brief Cast member's object to its own class if necessary.
1288 Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1289 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
1290 if (CXXRecordDecl *RD =
1291 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
1293 Context.getCanonicalType(Context.getTypeDeclType(RD));
1294 if (DestType->isDependentType() || From->getType()->isDependentType())
1296 QualType FromRecordType = From->getType();
1297 QualType DestRecordType = DestType;
1298 if (FromRecordType->getAs<PointerType>()) {
1299 DestType = Context.getPointerType(DestType);
1300 FromRecordType = FromRecordType->getPointeeType();
1302 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1303 CheckDerivedToBaseConversion(FromRecordType,
1305 From->getSourceRange().getBegin(),
1306 From->getSourceRange()))
1308 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1314 /// \brief Build a MemberExpr AST node.
1315 static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
1316 const CXXScopeSpec &SS, ValueDecl *Member,
1317 SourceLocation Loc, QualType Ty,
1318 const TemplateArgumentListInfo *TemplateArgs = 0) {
1319 NestedNameSpecifier *Qualifier = 0;
1320 SourceRange QualifierRange;
1322 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1323 QualifierRange = SS.getRange();
1326 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1327 Member, Loc, TemplateArgs, Ty);
1330 /// Builds an implicit member access expression. The current context
1331 /// is known to be an instance method, and the given unqualified lookup
1332 /// set is known to contain only instance members, at least one of which
1333 /// is from an appropriate type.
1334 Sema::OwningExprResult
1335 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1337 const TemplateArgumentListInfo *TemplateArgs,
1338 bool IsKnownInstance) {
1339 assert(!R.empty() && !R.isAmbiguous());
1341 SourceLocation Loc = R.getNameLoc();
1343 // We may have found a field within an anonymous union or struct
1344 // (C++ [class.union]).
1345 // FIXME: This needs to happen post-isImplicitMemberReference?
1346 // FIXME: template-ids inside anonymous structs?
1347 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
1348 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1349 return BuildAnonymousStructUnionMemberReference(Loc, FD);
1351 // If this is known to be an instance access, go ahead and build a
1352 // 'this' expression now.
1353 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1354 Expr *This = 0; // null signifies implicit access
1355 if (IsKnownInstance) {
1356 This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
1359 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1360 /*OpLoc*/ SourceLocation(),
1362 SS, R, TemplateArgs);
1365 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
1366 const LookupResult &R,
1367 bool HasTrailingLParen) {
1368 // Only when used directly as the postfix-expression of a call.
1369 if (!HasTrailingLParen)
1372 // Never if a scope specifier was provided.
1376 // Only in C++ or ObjC++.
1377 if (!getLangOptions().CPlusPlus)
1380 // Turn off ADL when we find certain kinds of declarations during
1382 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1385 // C++0x [basic.lookup.argdep]p3:
1386 // -- a declaration of a class member
1387 // Since using decls preserve this property, we check this on the
1389 if (D->isCXXClassMember())
1392 // C++0x [basic.lookup.argdep]p3:
1393 // -- a block-scope function declaration that is not a
1394 // using-declaration
1395 // NOTE: we also trigger this for function templates (in fact, we
1396 // don't check the decl type at all, since all other decl types
1397 // turn off ADL anyway).
1398 if (isa<UsingShadowDecl>(D))
1399 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1400 else if (D->getDeclContext()->isFunctionOrMethod())
1403 // C++0x [basic.lookup.argdep]p3:
1404 // -- a declaration that is neither a function or a function
1406 // And also for builtin functions.
1407 if (isa<FunctionDecl>(D)) {
1408 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1410 // But also builtin functions.
1411 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1413 } else if (!isa<FunctionTemplateDecl>(D))
1421 /// Diagnoses obvious problems with the use of the given declaration
1422 /// as an expression. This is only actually called for lookups that
1423 /// were not overloaded, and it doesn't promise that the declaration
1424 /// will in fact be used.
1425 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1426 if (isa<TypedefDecl>(D)) {
1427 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1431 if (isa<ObjCInterfaceDecl>(D)) {
1432 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1436 if (isa<NamespaceDecl>(D)) {
1437 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1444 Sema::OwningExprResult
1445 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
1448 // If this is a single, fully-resolved result and we don't need ADL,
1449 // just build an ordinary singleton decl ref.
1450 if (!NeedsADL && R.isSingleResult())
1451 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
1453 // We only need to check the declaration if there's exactly one
1454 // result, because in the overloaded case the results can only be
1455 // functions and function templates.
1456 if (R.isSingleResult() &&
1457 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
1461 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
1462 UnresolvedLookupExpr *ULE
1463 = UnresolvedLookupExpr::Create(Context, Dependent,
1464 (NestedNameSpecifier*) SS.getScopeRep(),
1466 R.getLookupName(), R.getNameLoc(),
1467 NeedsADL, R.isOverloadedResult());
1468 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1475 /// \brief Complete semantic analysis for a reference to the given declaration.
1476 Sema::OwningExprResult
1477 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
1478 SourceLocation Loc, NamedDecl *D) {
1479 assert(D && "Cannot refer to a NULL declaration");
1480 assert(!isa<FunctionTemplateDecl>(D) &&
1481 "Cannot refer unambiguously to a function template");
1483 if (CheckDeclInExpr(*this, Loc, D))
1486 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1487 // Specifically diagnose references to class templates that are missing
1488 // a template argument list.
1489 Diag(Loc, diag::err_template_decl_ref)
1490 << Template << SS.getRange();
1491 Diag(Template->getLocation(), diag::note_template_decl_here);
1495 // Make sure that we're referring to a value.
1496 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1498 Diag(Loc, diag::err_ref_non_value)
1499 << D << SS.getRange();
1500 Diag(D->getLocation(), diag::note_declared_at);
1504 // Check whether this declaration can be used. Note that we suppress
1505 // this check when we're going to perform argument-dependent lookup
1506 // on this function name, because this might not be the function
1507 // that overload resolution actually selects.
1508 if (DiagnoseUseOfDecl(VD, Loc))
1511 // Only create DeclRefExpr's for valid Decl's.
1512 if (VD->isInvalidDecl())
1515 // If the identifier reference is inside a block, and it refers to a value
1516 // that is outside the block, create a BlockDeclRefExpr instead of a
1517 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1518 // the block is formed.
1520 // We do not do this for things like enum constants, global variables, etc,
1521 // as they do not get snapshotted.
1523 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
1524 MarkDeclarationReferenced(Loc, VD);
1525 QualType ExprTy = VD->getType().getNonReferenceType();
1526 // The BlocksAttr indicates the variable is bound by-reference.
1527 if (VD->getAttr<BlocksAttr>())
1528 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
1529 // This is to record that a 'const' was actually synthesize and added.
1530 bool constAdded = !ExprTy.isConstQualified();
1531 // Variable will be bound by-copy, make it const within the closure.
1534 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1537 // If this reference is not in a block or if the referenced variable is
1538 // within the block, create a normal DeclRefExpr.
1540 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
1543 Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1544 tok::TokenKind Kind) {
1545 PredefinedExpr::IdentType IT;
1548 default: assert(0 && "Unknown simple primary expr!");
1549 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1550 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1551 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
1554 // Pre-defined identifiers are of type char[x], where x is the length of the
1557 Decl *currentDecl = getCurFunctionOrMethodDecl();
1559 Diag(Loc, diag::ext_predef_outside_function);
1560 currentDecl = Context.getTranslationUnitDecl();
1564 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1565 ResTy = Context.DependentTy;
1568 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
1570 llvm::APInt LengthI(32, Length + 1);
1571 ResTy = Context.CharTy.withConst();
1572 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1574 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
1577 Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
1578 llvm::SmallString<16> CharBuffer;
1579 CharBuffer.resize(Tok.getLength());
1580 const char *ThisTokBegin = &CharBuffer[0];
1581 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1583 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1584 Tok.getLocation(), PP);
1585 if (Literal.hadError())
1589 if (!getLangOptions().CPlusPlus)
1590 Ty = Context.IntTy; // 'x' and L'x' -> int in C.
1591 else if (Literal.isWide())
1592 Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
1594 Ty = Context.CharTy; // 'x' -> char in C++
1596 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1598 Ty, Tok.getLocation()));
1601 Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1602 // Fast path for a single digit (which is quite common). A single digit
1603 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1604 if (Tok.getLength() == 1) {
1605 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
1606 unsigned IntSize = Context.Target.getIntWidth();
1607 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
1608 Context.IntTy, Tok.getLocation()));
1611 llvm::SmallString<512> IntegerBuffer;
1612 // Add padding so that NumericLiteralParser can overread by one character.
1613 IntegerBuffer.resize(Tok.getLength()+1);
1614 const char *ThisTokBegin = &IntegerBuffer[0];
1616 // Get the spelling of the token, which eliminates trigraphs, etc.
1617 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1619 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1620 Tok.getLocation(), PP);
1621 if (Literal.hadError)
1626 if (Literal.isFloatingLiteral()) {
1628 if (Literal.isFloat)
1629 Ty = Context.FloatTy;
1630 else if (!Literal.isLong)
1631 Ty = Context.DoubleTy;
1633 Ty = Context.LongDoubleTy;
1635 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1637 using llvm::APFloat;
1638 APFloat Val(Format);
1640 APFloat::opStatus result = Literal.GetFloatValue(Val);
1642 // Overflow is always an error, but underflow is only an error if
1643 // we underflowed to zero (APFloat reports denormals as underflow).
1644 if ((result & APFloat::opOverflow) ||
1645 ((result & APFloat::opUnderflow) && Val.isZero())) {
1646 unsigned diagnostic;
1647 llvm::SmallVector<char, 20> buffer;
1648 if (result & APFloat::opOverflow) {
1649 diagnostic = diag::err_float_overflow;
1650 APFloat::getLargest(Format).toString(buffer);
1652 diagnostic = diag::err_float_underflow;
1653 APFloat::getSmallest(Format).toString(buffer);
1656 Diag(Tok.getLocation(), diagnostic)
1658 << llvm::StringRef(buffer.data(), buffer.size());
1661 bool isExact = (result == APFloat::opOK);
1662 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
1664 } else if (!Literal.isIntegerLiteral()) {
1669 // long long is a C99 feature.
1670 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
1672 Diag(Tok.getLocation(), diag::ext_longlong);
1674 // Get the value in the widest-possible width.
1675 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
1677 if (Literal.GetIntegerValue(ResultVal)) {
1678 // If this value didn't fit into uintmax_t, warn and force to ull.
1679 Diag(Tok.getLocation(), diag::warn_integer_too_large);
1680 Ty = Context.UnsignedLongLongTy;
1681 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
1682 "long long is not intmax_t?");
1684 // If this value fits into a ULL, try to figure out what else it fits into
1685 // according to the rules of C99 6.4.4.1p5.
1687 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1688 // be an unsigned int.
1689 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1691 // Check from smallest to largest, picking the smallest type we can.
1693 if (!Literal.isLong && !Literal.isLongLong) {
1694 // Are int/unsigned possibilities?
1695 unsigned IntSize = Context.Target.getIntWidth();
1697 // Does it fit in a unsigned int?
1698 if (ResultVal.isIntN(IntSize)) {
1699 // Does it fit in a signed int?
1700 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
1702 else if (AllowUnsigned)
1703 Ty = Context.UnsignedIntTy;
1708 // Are long/unsigned long possibilities?
1709 if (Ty.isNull() && !Literal.isLongLong) {
1710 unsigned LongSize = Context.Target.getLongWidth();
1712 // Does it fit in a unsigned long?
1713 if (ResultVal.isIntN(LongSize)) {
1714 // Does it fit in a signed long?
1715 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
1716 Ty = Context.LongTy;
1717 else if (AllowUnsigned)
1718 Ty = Context.UnsignedLongTy;
1723 // Finally, check long long if needed.
1725 unsigned LongLongSize = Context.Target.getLongLongWidth();
1727 // Does it fit in a unsigned long long?
1728 if (ResultVal.isIntN(LongLongSize)) {
1729 // Does it fit in a signed long long?
1730 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
1731 Ty = Context.LongLongTy;
1732 else if (AllowUnsigned)
1733 Ty = Context.UnsignedLongLongTy;
1734 Width = LongLongSize;
1738 // If we still couldn't decide a type, we probably have something that
1739 // does not fit in a signed long long, but has no U suffix.
1741 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
1742 Ty = Context.UnsignedLongLongTy;
1743 Width = Context.Target.getLongLongWidth();
1746 if (ResultVal.getBitWidth() != Width)
1747 ResultVal.trunc(Width);
1749 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
1752 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1753 if (Literal.isImaginary)
1754 Res = new (Context) ImaginaryLiteral(Res,
1755 Context.getComplexType(Res->getType()));
1760 Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1761 SourceLocation R, ExprArg Val) {
1762 Expr *E = Val.takeAs<Expr>();
1763 assert((E != 0) && "ActOnParenExpr() missing expr");
1764 return Owned(new (Context) ParenExpr(L, R, E));
1767 /// The UsualUnaryConversions() function is *not* called by this routine.
1768 /// See C99 6.3.2.1p[2-4] for more details.
1769 bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1770 SourceLocation OpLoc,
1771 const SourceRange &ExprRange,
1773 if (exprType->isDependentType())
1776 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1777 // the result is the size of the referenced type."
1778 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1779 // result shall be the alignment of the referenced type."
1780 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1781 exprType = Ref->getPointeeType();
1784 if (exprType->isFunctionType()) {
1785 // alignof(function) is allowed as an extension.
1787 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1791 // Allow sizeof(void)/alignof(void) as an extension.
1792 if (exprType->isVoidType()) {
1793 Diag(OpLoc, diag::ext_sizeof_void_type)
1794 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1798 if (RequireCompleteType(OpLoc, exprType,
1799 PDiag(diag::err_sizeof_alignof_incomplete_type)
1800 << int(!isSizeof) << ExprRange))
1803 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
1804 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
1805 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
1806 << exprType << isSizeof << ExprRange;
1813 bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1814 const SourceRange &ExprRange) {
1815 E = E->IgnoreParens();
1817 // alignof decl is always ok.
1818 if (isa<DeclRefExpr>(E))
1821 // Cannot know anything else if the expression is dependent.
1822 if (E->isTypeDependent())
1825 if (E->getBitField()) {
1826 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1830 // Alignment of a field access is always okay, so long as it isn't a
1832 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1833 if (isa<FieldDecl>(ME->getMemberDecl()))
1836 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1839 /// \brief Build a sizeof or alignof expression given a type operand.
1840 Action::OwningExprResult
1841 Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
1842 SourceLocation OpLoc,
1843 bool isSizeOf, SourceRange R) {
1847 QualType T = TInfo->getType();
1849 if (!T->isDependentType() &&
1850 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1853 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1854 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
1855 Context.getSizeType(), OpLoc,
1859 /// \brief Build a sizeof or alignof expression given an expression
1861 Action::OwningExprResult
1862 Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1863 bool isSizeOf, SourceRange R) {
1864 // Verify that the operand is valid.
1865 bool isInvalid = false;
1866 if (E->isTypeDependent()) {
1867 // Delay type-checking for type-dependent expressions.
1868 } else if (!isSizeOf) {
1869 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1870 } else if (E->getBitField()) { // C99 6.5.3.4p1.
1871 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1874 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1880 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1881 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1882 Context.getSizeType(), OpLoc,
1886 /// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1887 /// the same for @c alignof and @c __alignof
1888 /// Note that the ArgRange is invalid if isType is false.
1889 Action::OwningExprResult
1890 Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1891 void *TyOrEx, const SourceRange &ArgRange) {
1892 // If error parsing type, ignore.
1893 if (TyOrEx == 0) return ExprError();
1896 TypeSourceInfo *TInfo;
1897 (void) GetTypeFromParser(TyOrEx, &TInfo);
1898 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
1901 Expr *ArgEx = (Expr *)TyOrEx;
1902 Action::OwningExprResult Result
1903 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1905 if (Result.isInvalid())
1908 return move(Result);
1911 QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
1912 if (V->isTypeDependent())
1913 return Context.DependentTy;
1915 // These operators return the element type of a complex type.
1916 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
1917 return CT->getElementType();
1919 // Otherwise they pass through real integer and floating point types here.
1920 if (V->getType()->isArithmeticType())
1921 return V->getType();
1923 // Reject anything else.
1924 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1925 << (isReal ? "__real" : "__imag");
1931 Action::OwningExprResult
1932 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1933 tok::TokenKind Kind, ExprArg Input) {
1934 UnaryOperator::Opcode Opc;
1936 default: assert(0 && "Unknown unary op!");
1937 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1938 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1941 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
1944 Action::OwningExprResult
1945 Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1946 ExprArg Idx, SourceLocation RLoc) {
1947 // Since this might be a postfix expression, get rid of ParenListExprs.
1948 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1950 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1951 *RHSExp = static_cast<Expr*>(Idx.get());
1953 if (getLangOptions().CPlusPlus &&
1954 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1957 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1958 Context.DependentTy, RLoc));
1961 if (getLangOptions().CPlusPlus &&
1962 (LHSExp->getType()->isRecordType() ||
1963 LHSExp->getType()->isEnumeralType() ||
1964 RHSExp->getType()->isRecordType() ||
1965 RHSExp->getType()->isEnumeralType())) {
1966 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
1969 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1973 Action::OwningExprResult
1974 Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1975 ExprArg Idx, SourceLocation RLoc) {
1976 Expr *LHSExp = static_cast<Expr*>(Base.get());
1977 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1979 // Perform default conversions.
1980 DefaultFunctionArrayConversion(LHSExp);
1981 DefaultFunctionArrayConversion(RHSExp);
1983 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1985 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
1986 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
1987 // in the subscript position. As a result, we need to derive the array base
1988 // and index from the expression types.
1989 Expr *BaseExpr, *IndexExpr;
1990 QualType ResultType;
1991 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1994 ResultType = Context.DependentTy;
1995 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
1998 ResultType = PTy->getPointeeType();
1999 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
2000 // Handle the uncommon case of "123[Ptr]".
2003 ResultType = PTy->getPointeeType();
2004 } else if (const ObjCObjectPointerType *PTy =
2005 LHSTy->getAs<ObjCObjectPointerType>()) {
2008 ResultType = PTy->getPointeeType();
2009 } else if (const ObjCObjectPointerType *PTy =
2010 RHSTy->getAs<ObjCObjectPointerType>()) {
2011 // Handle the uncommon case of "123[Ptr]".
2014 ResultType = PTy->getPointeeType();
2015 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
2016 BaseExpr = LHSExp; // vectors: V[123]
2019 // FIXME: need to deal with const...
2020 ResultType = VTy->getElementType();
2021 } else if (LHSTy->isArrayType()) {
2022 // If we see an array that wasn't promoted by
2023 // DefaultFunctionArrayConversion, it must be an array that
2024 // wasn't promoted because of the C90 rule that doesn't
2025 // allow promoting non-lvalue arrays. Warn, then
2026 // force the promotion here.
2027 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2028 LHSExp->getSourceRange();
2029 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2030 CastExpr::CK_ArrayToPointerDecay);
2031 LHSTy = LHSExp->getType();
2035 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
2036 } else if (RHSTy->isArrayType()) {
2037 // Same as previous, except for 123[f().a] case
2038 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2039 RHSExp->getSourceRange();
2040 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2041 CastExpr::CK_ArrayToPointerDecay);
2042 RHSTy = RHSExp->getType();
2046 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
2048 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2049 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
2052 if (!(IndexExpr->getType()->isIntegerType() &&
2053 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
2054 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2055 << IndexExpr->getSourceRange());
2057 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
2058 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2059 && !IndexExpr->isTypeDependent())
2060 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2062 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
2063 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2064 // type. Note that Functions are not objects, and that (in C99 parlance)
2065 // incomplete types are not object types.
2066 if (ResultType->isFunctionType()) {
2067 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2068 << ResultType << BaseExpr->getSourceRange();
2072 if (!ResultType->isDependentType() &&
2073 RequireCompleteType(LLoc, ResultType,
2074 PDiag(diag::err_subscript_incomplete_type)
2075 << BaseExpr->getSourceRange()))
2078 // Diagnose bad cases where we step over interface counts.
2079 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
2080 Diag(LLoc, diag::err_subscript_nonfragile_interface)
2081 << ResultType << BaseExpr->getSourceRange();
2087 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2092 CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
2093 const IdentifierInfo *CompName,
2094 SourceLocation CompLoc) {
2095 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2098 // FIXME: This logic can be greatly simplified by splitting it along
2099 // halving/not halving and reworking the component checking.
2100 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
2102 // The vector accessor can't exceed the number of elements.
2103 const char *compStr = CompName->getNameStart();
2105 // This flag determines whether or not the component is one of the four
2106 // special names that indicate a subset of exactly half the elements are
2108 bool HalvingSwizzle = false;
2110 // This flag determines whether or not CompName has an 's' char prefix,
2111 // indicating that it is a string of hex values to be used as vector indices.
2112 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
2114 // Check that we've found one of the special components, or that the component
2115 // names must come from the same set.
2116 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
2117 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2118 HalvingSwizzle = true;
2119 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
2122 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
2123 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
2126 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
2129 if (!HalvingSwizzle && *compStr) {
2130 // We didn't get to the end of the string. This means the component names
2131 // didn't come from the same set *or* we encountered an illegal name.
2132 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2133 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
2137 // Ensure no component accessor exceeds the width of the vector type it
2139 if (!HalvingSwizzle) {
2140 compStr = CompName->getNameStart();
2146 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2147 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2148 << baseType << SourceRange(CompLoc);
2154 // The component accessor looks fine - now we need to compute the actual type.
2155 // The vector type is implied by the component accessor. For example,
2156 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
2157 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
2158 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
2159 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
2160 : CompName->getLength();
2165 return vecType->getElementType();
2167 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
2168 // Now look up the TypeDefDecl from the vector type. Without this,
2169 // diagostics look bad. We want extended vector types to appear built-in.
2170 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2171 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2172 return Context.getTypedefType(ExtVectorDecls[i]);
2174 return VT; // should never get here (a typedef type should always be found).
2177 static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
2178 IdentifierInfo *Member,
2179 const Selector &Sel,
2180 ASTContext &Context) {
2182 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
2184 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
2187 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2188 E = PDecl->protocol_end(); I != E; ++I) {
2189 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
2196 static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
2197 IdentifierInfo *Member,
2198 const Selector &Sel,
2199 ASTContext &Context) {
2200 // Check protocols on qualified interfaces.
2202 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
2203 E = QIdTy->qual_end(); I != E; ++I) {
2204 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
2208 // Also must look for a getter name which uses property syntax.
2209 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
2215 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
2216 E = QIdTy->qual_end(); I != E; ++I) {
2217 // Search in the protocol-qualifier list of current protocol.
2218 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
2226 Sema::OwningExprResult
2227 Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2228 bool IsArrow, SourceLocation OpLoc,
2229 const CXXScopeSpec &SS,
2230 NamedDecl *FirstQualifierInScope,
2231 DeclarationName Name, SourceLocation NameLoc,
2232 const TemplateArgumentListInfo *TemplateArgs) {
2233 Expr *BaseExpr = Base.takeAs<Expr>();
2235 // Even in dependent contexts, try to diagnose base expressions with
2236 // obviously wrong types, e.g.:
2241 // In Obj-C++, however, the above expression is valid, since it could be
2242 // accessing the 'f' property if T is an Obj-C interface. The extra check
2243 // allows this, while still reporting an error if T is a struct pointer.
2245 const PointerType *PT = BaseType->getAs<PointerType>();
2246 if (PT && (!getLangOptions().ObjC1 ||
2247 PT->getPointeeType()->isRecordType())) {
2248 assert(BaseExpr && "cannot happen with implicit member accesses");
2249 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
2250 << BaseType << BaseExpr->getSourceRange();
2255 assert(BaseType->isDependentType());
2257 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2258 // must have pointer type, and the accessed type is the pointee.
2259 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
2261 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2263 FirstQualifierInScope,
2268 /// We know that the given qualified member reference points only to
2269 /// declarations which do not belong to the static type of the base
2270 /// expression. Diagnose the problem.
2271 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2274 const CXXScopeSpec &SS,
2275 const LookupResult &R) {
2276 // If this is an implicit member access, use a different set of
2279 return DiagnoseInstanceReference(SemaRef, SS, R);
2281 // FIXME: this is an exceedingly lame diagnostic for some of the more
2282 // complicated cases here.
2283 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
2284 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
2285 << SS.getRange() << DC << BaseType;
2288 // Check whether the declarations we found through a nested-name
2289 // specifier in a member expression are actually members of the base
2290 // type. The restriction here is:
2292 // C++ [expr.ref]p2:
2293 // ... In these cases, the id-expression shall name a
2294 // member of the class or of one of its base classes.
2296 // So it's perfectly legitimate for the nested-name specifier to name
2297 // an unrelated class, and for us to find an overload set including
2298 // decls from classes which are not superclasses, as long as the decl
2299 // we actually pick through overload resolution is from a superclass.
2300 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2302 const CXXScopeSpec &SS,
2303 const LookupResult &R) {
2304 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2306 // We can't check this yet because the base type is still
2308 assert(BaseType->isDependentType());
2311 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
2313 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2314 // If this is an implicit member reference and we find a
2315 // non-instance member, it's not an error.
2316 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2319 // Note that we use the DC of the decl, not the underlying decl.
2320 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2321 while (RecordD->isAnonymousStructOrUnion())
2322 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2324 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2325 MemberRecord.insert(RecordD->getCanonicalDecl());
2327 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2331 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
2336 LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2337 SourceRange BaseRange, const RecordType *RTy,
2338 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2339 RecordDecl *RDecl = RTy->getDecl();
2340 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2341 PDiag(diag::err_typecheck_incomplete_tag)
2345 DeclContext *DC = RDecl;
2347 // If the member name was a qualified-id, look into the
2348 // nested-name-specifier.
2349 DC = SemaRef.computeDeclContext(SS, false);
2351 if (SemaRef.RequireCompleteDeclContext(SS)) {
2352 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2353 << SS.getRange() << DC;
2357 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2359 if (!isa<TypeDecl>(DC)) {
2360 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2361 << DC << SS.getRange();
2366 // The record definition is complete, now look up the member.
2367 SemaRef.LookupQualifiedName(R, DC);
2372 // We didn't find anything with the given name, so try to correct
2374 DeclarationName Name = R.getLookupName();
2375 if (SemaRef.CorrectTypo(R, 0, &SS, DC) &&
2376 (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2377 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2378 << Name << DC << R.getLookupName() << SS.getRange()
2379 << CodeModificationHint::CreateReplacement(R.getNameLoc(),
2380 R.getLookupName().getAsString());
2389 Sema::OwningExprResult
2390 Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
2391 SourceLocation OpLoc, bool IsArrow,
2392 const CXXScopeSpec &SS,
2393 NamedDecl *FirstQualifierInScope,
2394 DeclarationName Name, SourceLocation NameLoc,
2395 const TemplateArgumentListInfo *TemplateArgs) {
2396 Expr *Base = BaseArg.takeAs<Expr>();
2398 if (BaseType->isDependentType() ||
2399 (SS.isSet() && isDependentScopeSpecifier(SS)))
2400 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
2402 SS, FirstQualifierInScope,
2406 LookupResult R(*this, Name, NameLoc, LookupMemberName);
2408 // Implicit member accesses.
2410 QualType RecordTy = BaseType;
2411 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2412 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2413 RecordTy->getAs<RecordType>(),
2417 // Explicit member accesses.
2419 OwningExprResult Result =
2420 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2421 SS, FirstQualifierInScope,
2422 /*ObjCImpDecl*/ DeclPtrTy());
2424 if (Result.isInvalid()) {
2430 return move(Result);
2433 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2434 OpLoc, IsArrow, SS, R, TemplateArgs);
2437 Sema::OwningExprResult
2438 Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2439 SourceLocation OpLoc, bool IsArrow,
2440 const CXXScopeSpec &SS,
2442 const TemplateArgumentListInfo *TemplateArgs) {
2443 Expr *BaseExpr = Base.takeAs<Expr>();
2444 QualType BaseType = BaseExprType;
2446 assert(BaseType->isPointerType());
2447 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2450 NestedNameSpecifier *Qualifier =
2451 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2452 DeclarationName MemberName = R.getLookupName();
2453 SourceLocation MemberLoc = R.getNameLoc();
2455 if (R.isAmbiguous())
2459 // Rederive where we looked up.
2460 DeclContext *DC = (SS.isSet()
2461 ? computeDeclContext(SS, false)
2462 : BaseType->getAs<RecordType>()->getDecl());
2464 Diag(R.getNameLoc(), diag::err_no_member)
2466 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
2470 // Diagnose qualified lookups that find only declarations from a
2471 // non-base type. Note that it's okay for lookup to find
2472 // declarations from a non-base type as long as those aren't the
2473 // ones picked by overload resolution.
2474 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
2477 // Construct an unresolved result if we in fact got an unresolved
2479 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
2481 BaseExprType->isDependentType() ||
2482 R.isUnresolvableResult() ||
2483 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
2485 UnresolvedMemberExpr *MemExpr
2486 = UnresolvedMemberExpr::Create(Context, Dependent,
2487 R.isUnresolvableResult(),
2488 BaseExpr, BaseExprType,
2490 Qualifier, SS.getRange(),
2491 MemberName, MemberLoc,
2493 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2494 MemExpr->addDecl(*I);
2496 return Owned(MemExpr);
2499 assert(R.isSingleResult());
2500 NamedDecl *MemberDecl = R.getFoundDecl();
2502 // FIXME: diagnose the presence of template arguments now.
2504 // If the decl being referenced had an error, return an error for this
2505 // sub-expr without emitting another error, in order to avoid cascading
2507 if (MemberDecl->isInvalidDecl())
2510 // Handle the implicit-member-access case.
2512 // If this is not an instance member, convert to a non-member access.
2513 if (!IsInstanceMember(MemberDecl))
2514 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2516 BaseExpr = new (Context) CXXThisExpr(SourceLocation(), BaseExprType);
2519 bool ShouldCheckUse = true;
2520 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2521 // Don't diagnose the use of a virtual member function unless it's
2522 // explicitly qualified.
2523 if (MD->isVirtual() && !SS.isSet())
2524 ShouldCheckUse = false;
2527 // Check the use of this member.
2528 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2533 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2534 // We may have found a field within an anonymous union or struct
2535 // (C++ [class.union]).
2536 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2537 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
2538 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2541 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2542 QualType MemberType = FD->getType();
2543 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2544 MemberType = Ref->getPointeeType();
2546 Qualifiers BaseQuals = BaseType.getQualifiers();
2547 BaseQuals.removeObjCGCAttr();
2548 if (FD->isMutable()) BaseQuals.removeConst();
2550 Qualifiers MemberQuals
2551 = Context.getCanonicalType(MemberType).getQualifiers();
2553 Qualifiers Combined = BaseQuals + MemberQuals;
2554 if (Combined != MemberQuals)
2555 MemberType = Context.getQualifiedType(MemberType, Combined);
2558 MarkDeclarationReferenced(MemberLoc, FD);
2559 if (PerformObjectMemberConversion(BaseExpr, FD))
2561 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2562 FD, MemberLoc, MemberType));
2565 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2566 MarkDeclarationReferenced(MemberLoc, Var);
2567 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2569 Var->getType().getNonReferenceType()));
2572 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2573 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2574 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2575 MemberFn, MemberLoc,
2576 MemberFn->getType()));
2579 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2580 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2581 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2582 Enum, MemberLoc, Enum->getType()));
2587 if (isa<TypeDecl>(MemberDecl))
2588 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2589 << MemberName << int(IsArrow));
2591 // We found a declaration kind that we didn't expect. This is a
2592 // generic error message that tells the user that she can't refer
2593 // to this member with '.' or '->'.
2594 return ExprError(Diag(MemberLoc,
2595 diag::err_typecheck_member_reference_unknown)
2596 << MemberName << int(IsArrow));
2599 /// Look up the given member of the given non-type-dependent
2600 /// expression. This can return in one of two ways:
2601 /// * If it returns a sentinel null-but-valid result, the caller will
2602 /// assume that lookup was performed and the results written into
2603 /// the provided structure. It will take over from there.
2604 /// * Otherwise, the returned expression will be produced in place of
2605 /// an ordinary member expression.
2607 /// The ObjCImpDecl bit is a gross hack that will need to be properly
2608 /// fixed for ObjC++.
2609 Sema::OwningExprResult
2610 Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
2611 bool &IsArrow, SourceLocation OpLoc,
2612 const CXXScopeSpec &SS,
2613 NamedDecl *FirstQualifierInScope,
2614 DeclPtrTy ObjCImpDecl) {
2615 assert(BaseExpr && "no base expression");
2617 // Perform default conversions.
2618 DefaultFunctionArrayConversion(BaseExpr);
2620 QualType BaseType = BaseExpr->getType();
2621 assert(!BaseType->isDependentType());
2623 DeclarationName MemberName = R.getLookupName();
2624 SourceLocation MemberLoc = R.getNameLoc();
2626 // If the user is trying to apply -> or . to a function pointer
2627 // type, it's probably because they forgot parentheses to call that
2628 // function. Suggest the addition of those parentheses, build the
2629 // call, and continue on.
2630 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2631 if (const FunctionProtoType *Fun
2632 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2633 QualType ResultTy = Fun->getResultType();
2634 if (Fun->getNumArgs() == 0 &&
2635 ((!IsArrow && ResultTy->isRecordType()) ||
2636 (IsArrow && ResultTy->isPointerType() &&
2637 ResultTy->getAs<PointerType>()->getPointeeType()
2638 ->isRecordType()))) {
2639 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2640 Diag(Loc, diag::err_member_reference_needs_call)
2642 << CodeModificationHint::CreateInsertion(Loc, "()");
2644 OwningExprResult NewBase
2645 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
2646 MultiExprArg(*this, 0, 0), 0, Loc);
2647 if (NewBase.isInvalid())
2650 BaseExpr = NewBase.takeAs<Expr>();
2651 DefaultFunctionArrayConversion(BaseExpr);
2652 BaseType = BaseExpr->getType();
2657 // If this is an Objective-C pseudo-builtin and a definition is provided then
2659 if (BaseType->isObjCIdType()) {
2661 // Handle the following exceptional case PObj->isa.
2662 if (const ObjCObjectPointerType *OPT =
2663 BaseType->getAs<ObjCObjectPointerType>()) {
2664 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2665 MemberName.getAsIdentifierInfo()->isStr("isa"))
2666 return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2667 Context.getObjCClassType()));
2670 // We have an 'id' type. Rather than fall through, we check if this
2671 // is a reference to 'isa'.
2672 if (BaseType != Context.ObjCIdRedefinitionType) {
2673 BaseType = Context.ObjCIdRedefinitionType;
2674 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2678 // If this is an Objective-C pseudo-builtin and a definition is provided then
2680 if (Context.isObjCSelType(BaseType)) {
2681 // We have an 'SEL' type. Rather than fall through, we check if this
2682 // is a reference to 'sel_id'.
2683 if (BaseType != Context.ObjCSelRedefinitionType) {
2684 BaseType = Context.ObjCSelRedefinitionType;
2685 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2689 assert(!BaseType.isNull() && "no type for member expression");
2691 // Handle properties on ObjC 'Class' types.
2692 if (!IsArrow && BaseType->isObjCClassType()) {
2693 // Also must look for a getter name which uses property syntax.
2694 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2695 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2696 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2697 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2698 ObjCMethodDecl *Getter;
2699 // FIXME: need to also look locally in the implementation.
2700 if ((Getter = IFace->lookupClassMethod(Sel))) {
2701 // Check the use of this method.
2702 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2705 // If we found a getter then this may be a valid dot-reference, we
2706 // will look for the matching setter, in case it is needed.
2707 Selector SetterSel =
2708 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2709 PP.getSelectorTable(), Member);
2710 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2712 // If this reference is in an @implementation, also check for 'private'
2714 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
2716 // Look through local category implementations associated with the class.
2718 Setter = IFace->getCategoryClassMethod(SetterSel);
2720 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2723 if (Getter || Setter) {
2727 PType = Getter->getResultType();
2729 // Get the expression type from Setter's incoming parameter.
2730 PType = (*(Setter->param_end() -1))->getType();
2731 // FIXME: we must check that the setter has property type.
2732 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2734 Setter, MemberLoc, BaseExpr));
2736 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2737 << MemberName << BaseType);
2741 if (BaseType->isObjCClassType() &&
2742 BaseType != Context.ObjCClassRedefinitionType) {
2743 BaseType = Context.ObjCClassRedefinitionType;
2744 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2748 if (const PointerType *PT = BaseType->getAs<PointerType>())
2749 BaseType = PT->getPointeeType();
2750 else if (BaseType->isObjCObjectPointerType())
2752 else if (BaseType->isRecordType()) {
2753 // Recover from arrow accesses to records, e.g.:
2754 // struct MyRecord foo;
2756 // This is actually well-formed in C++ if MyRecord has an
2757 // overloaded operator->, but that should have been dealt with
2759 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2760 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2761 << CodeModificationHint::CreateReplacement(OpLoc, ".");
2764 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2765 << BaseType << BaseExpr->getSourceRange();
2769 // Recover from dot accesses to pointers, e.g.:
2772 // This is actually well-formed in two cases:
2773 // - 'type' is an Objective C type
2774 // - 'bar' is a pseudo-destructor name which happens to refer to
2775 // the appropriate pointer type
2776 if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
2777 const PointerType *PT = BaseType->getAs<PointerType>();
2778 if (PT && PT->getPointeeType()->isRecordType()) {
2779 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
2780 << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
2781 << CodeModificationHint::CreateReplacement(OpLoc, "->");
2782 BaseType = PT->getPointeeType();
2788 // Handle field access to simple records. This also handles access
2789 // to fields of the ObjC 'id' struct.
2790 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
2791 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2794 return Owned((Expr*) 0);
2797 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2798 // into a record type was handled above, any destructor we see here is a
2799 // pseudo-destructor.
2800 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2801 // C++ [expr.pseudo]p2:
2802 // The left hand side of the dot operator shall be of scalar type. The
2803 // left hand side of the arrow operator shall be of pointer to scalar
2805 if (!BaseType->isScalarType())
2806 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2807 << BaseType << BaseExpr->getSourceRange());
2809 // [...] The type designated by the pseudo-destructor-name shall be the
2810 // same as the object type.
2811 if (!MemberName.getCXXNameType()->isDependentType() &&
2812 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2813 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2814 << BaseType << MemberName.getCXXNameType()
2815 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
2817 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
2820 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2822 // shall designate the same scalar type.
2824 // FIXME: DPG can't see any way to trigger this particular clause, so it
2825 // isn't checked here.
2827 // FIXME: We've lost the precise spelling of the type by going through
2828 // DeclarationName. Can we do better?
2829 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
2831 (NestedNameSpecifier *) SS.getScopeRep(),
2833 MemberName.getCXXNameType(),
2837 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2839 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2840 (!IsArrow && BaseType->isObjCInterfaceType())) {
2841 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
2842 const ObjCInterfaceType *IFaceT =
2843 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
2845 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2847 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2848 ObjCInterfaceDecl *ClassDeclared;
2849 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
2852 // If the decl being referenced had an error, return an error for this
2853 // sub-expr without emitting another error, in order to avoid cascading
2855 if (IV->isInvalidDecl())
2858 // Check whether we can reference this field.
2859 if (DiagnoseUseOfDecl(IV, MemberLoc))
2861 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2862 IV->getAccessControl() != ObjCIvarDecl::Package) {
2863 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2864 if (ObjCMethodDecl *MD = getCurMethodDecl())
2865 ClassOfMethodDecl = MD->getClassInterface();
2866 else if (ObjCImpDecl && getCurFunctionDecl()) {
2867 // Case of a c-function declared inside an objc implementation.
2868 // FIXME: For a c-style function nested inside an objc implementation
2869 // class, there is no implementation context available, so we pass
2870 // down the context as argument to this routine. Ideally, this context
2871 // need be passed down in the AST node and somehow calculated from the
2872 // AST for a function decl.
2873 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2874 if (ObjCImplementationDecl *IMPD =
2875 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2876 ClassOfMethodDecl = IMPD->getClassInterface();
2877 else if (ObjCCategoryImplDecl* CatImplClass =
2878 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2879 ClassOfMethodDecl = CatImplClass->getClassInterface();
2882 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2883 if (ClassDeclared != IDecl ||
2884 ClassOfMethodDecl != ClassDeclared)
2885 Diag(MemberLoc, diag::error_private_ivar_access)
2886 << IV->getDeclName();
2887 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2889 Diag(MemberLoc, diag::error_protected_ivar_access)
2890 << IV->getDeclName();
2893 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2894 MemberLoc, BaseExpr,
2897 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2898 << IDecl->getDeclName() << MemberName
2899 << BaseExpr->getSourceRange());
2902 // Handle properties on 'id' and qualified "id".
2903 if (!IsArrow && (BaseType->isObjCIdType() ||
2904 BaseType->isObjCQualifiedIdType())) {
2905 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
2906 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2908 // Check protocols on qualified interfaces.
2909 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2910 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2911 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2912 // Check the use of this declaration
2913 if (DiagnoseUseOfDecl(PD, MemberLoc))
2916 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2917 MemberLoc, BaseExpr));
2919 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2920 // Check the use of this method.
2921 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2924 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2925 OMD->getResultType(),
2926 OMD, OpLoc, MemberLoc,
2931 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2932 << MemberName << BaseType);
2934 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2935 // pointer to a (potentially qualified) interface type.
2936 const ObjCObjectPointerType *OPT;
2937 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
2938 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2939 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
2940 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2942 // Search for a declared property first.
2943 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
2944 // Check whether we can reference this property.
2945 if (DiagnoseUseOfDecl(PD, MemberLoc))
2947 QualType ResTy = PD->getType();
2948 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2949 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2950 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2951 ResTy = Getter->getResultType();
2952 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
2953 MemberLoc, BaseExpr));
2955 // Check protocols on qualified interfaces.
2956 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2957 E = OPT->qual_end(); I != E; ++I)
2958 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
2959 // Check whether we can reference this property.
2960 if (DiagnoseUseOfDecl(PD, MemberLoc))
2963 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2964 MemberLoc, BaseExpr));
2966 // If that failed, look for an "implicit" property by seeing if the nullary
2967 // selector is implemented.
2969 // FIXME: The logic for looking up nullary and unary selectors should be
2970 // shared with the code in ActOnInstanceMessage.
2972 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2973 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2975 // If this reference is in an @implementation, check for 'private' methods.
2977 Getter = IFace->lookupPrivateInstanceMethod(Sel);
2979 // Look through local category implementations associated with the class.
2981 Getter = IFace->getCategoryInstanceMethod(Sel);
2983 // Check if we can reference this property.
2984 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2987 // If we found a getter then this may be a valid dot-reference, we
2988 // will look for the matching setter, in case it is needed.
2989 Selector SetterSel =
2990 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2991 PP.getSelectorTable(), Member);
2992 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
2994 // If this reference is in an @implementation, also check for 'private'
2996 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
2998 // Look through local category implementations associated with the class.
3000 Setter = IFace->getCategoryInstanceMethod(SetterSel);
3002 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
3005 if (Getter || Setter) {
3009 PType = Getter->getResultType();
3011 // Get the expression type from Setter's incoming parameter.
3012 PType = (*(Setter->param_end() -1))->getType();
3013 // FIXME: we must check that the setter has property type.
3014 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
3015 Setter, MemberLoc, BaseExpr));
3017 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3018 << MemberName << BaseType);
3021 // Handle the following exceptional case (*Obj).isa.
3023 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
3024 MemberName.getAsIdentifierInfo()->isStr("isa"))
3025 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
3026 Context.getObjCClassType()));
3028 // Handle 'field access' to vectors, such as 'V.xx'.
3029 if (BaseType->isExtVectorType()) {
3030 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3031 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3034 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
3038 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3039 << BaseType << BaseExpr->getSourceRange();
3044 static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
3045 SourceLocation NameLoc,
3046 Sema::ExprArg MemExpr) {
3047 Expr *E = (Expr *) MemExpr.get();
3048 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
3049 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
3050 << isa<CXXPseudoDestructorExpr>(E)
3051 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
3053 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
3055 /*LPLoc*/ ExpectedLParenLoc,
3056 Sema::MultiExprArg(SemaRef, 0, 0),
3058 /*RPLoc*/ ExpectedLParenLoc);
3061 /// The main callback when the parser finds something like
3062 /// expression . [nested-name-specifier] identifier
3063 /// expression -> [nested-name-specifier] identifier
3064 /// where 'identifier' encompasses a fairly broad spectrum of
3065 /// possibilities, including destructor and operator references.
3067 /// \param OpKind either tok::arrow or tok::period
3068 /// \param HasTrailingLParen whether the next token is '(', which
3069 /// is used to diagnose mis-uses of special members that can
3071 /// \param ObjCImpDecl the current ObjC @implementation decl;
3072 /// this is an ugly hack around the fact that ObjC @implementations
3073 /// aren't properly put in the context chain
3074 Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3075 SourceLocation OpLoc,
3076 tok::TokenKind OpKind,
3077 const CXXScopeSpec &SS,
3079 DeclPtrTy ObjCImpDecl,
3080 bool HasTrailingLParen) {
3081 if (SS.isSet() && SS.isInvalid())
3084 TemplateArgumentListInfo TemplateArgsBuffer;
3086 // Decompose the name into its component parts.
3087 DeclarationName Name;
3088 SourceLocation NameLoc;
3089 const TemplateArgumentListInfo *TemplateArgs;
3090 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3091 Name, NameLoc, TemplateArgs);
3093 bool IsArrow = (OpKind == tok::arrow);
3095 NamedDecl *FirstQualifierInScope
3096 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3097 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3099 // This is a postfix expression, so get rid of ParenListExprs.
3100 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3102 Expr *Base = BaseArg.takeAs<Expr>();
3103 OwningExprResult Result(*this);
3104 if (Base->getType()->isDependentType()) {
3105 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
3107 SS, FirstQualifierInScope,
3111 LookupResult R(*this, Name, NameLoc, LookupMemberName);
3113 // Re-use the lookup done for the template name.
3114 DecomposeTemplateName(R, Id);
3116 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3117 SS, FirstQualifierInScope,
3120 if (Result.isInvalid()) {
3126 // The only way a reference to a destructor can be used is to
3127 // immediately call it, which falls into this case. If the
3128 // next token is not a '(', produce a diagnostic and build the
3130 if (!HasTrailingLParen &&
3131 Id.getKind() == UnqualifiedId::IK_DestructorName)
3132 return DiagnoseDtorReference(*this, NameLoc, move(Result));
3134 return move(Result);
3138 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
3139 OpLoc, IsArrow, SS, R, TemplateArgs);
3142 return move(Result);
3145 Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3147 ParmVarDecl *Param) {
3148 if (Param->hasUnparsedDefaultArg()) {
3150 diag::err_use_of_default_argument_to_function_declared_later) <<
3151 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3152 Diag(UnparsedDefaultArgLocs[Param],
3153 diag::note_default_argument_declared_here);
3155 if (Param->hasUninstantiatedDefaultArg()) {
3156 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3158 // Instantiate the expression.
3159 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
3161 InstantiatingTemplate Inst(*this, CallLoc, Param,
3162 ArgList.getInnermost().getFlatArgumentList(),
3163 ArgList.getInnermost().flat_size());
3165 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
3166 if (Result.isInvalid())
3169 // Check the expression as an initializer for the parameter.
3170 InitializedEntity Entity
3171 = InitializedEntity::InitializeParameter(Param);
3172 InitializationKind Kind
3173 = InitializationKind::CreateCopy(Param->getLocation(),
3174 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3175 Expr *ResultE = Result.takeAs<Expr>();
3177 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3178 Result = InitSeq.Perform(*this, Entity, Kind,
3179 MultiExprArg(*this, (void**)&ResultE, 1));
3180 if (Result.isInvalid())
3183 // Build the default argument expression.
3184 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3185 Result.takeAs<Expr>()));
3188 // If the default expression creates temporaries, we need to
3189 // push them to the current stack of expression temporaries so they'll
3190 // be properly destroyed.
3191 // FIXME: We should really be rebuilding the default argument with new
3192 // bound temporaries; see the comment in PR5810.
3193 for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3194 ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
3197 // We already type-checked the argument, so we know it works.
3198 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3201 /// ConvertArgumentsForCall - Converts the arguments specified in
3202 /// Args/NumArgs to the parameter types of the function FDecl with
3203 /// function prototype Proto. Call is the call expression itself, and
3204 /// Fn is the function expression. For a C++ member function, this
3205 /// routine does not attempt to convert the object argument. Returns
3206 /// true if the call is ill-formed.
3208 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3209 FunctionDecl *FDecl,
3210 const FunctionProtoType *Proto,
3211 Expr **Args, unsigned NumArgs,
3212 SourceLocation RParenLoc) {
3213 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3214 // assignment, to the types of the corresponding parameter, ...
3215 unsigned NumArgsInProto = Proto->getNumArgs();
3216 bool Invalid = false;
3218 // If too few arguments are available (and we don't have default
3219 // arguments for the remaining parameters), don't make the call.
3220 if (NumArgs < NumArgsInProto) {
3221 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3222 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3223 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
3224 Call->setNumArgs(Context, NumArgsInProto);
3227 // If too many are passed and not variadic, error on the extras and drop
3229 if (NumArgs > NumArgsInProto) {
3230 if (!Proto->isVariadic()) {
3231 Diag(Args[NumArgsInProto]->getLocStart(),
3232 diag::err_typecheck_call_too_many_args)
3233 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3234 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3235 Args[NumArgs-1]->getLocEnd());
3236 // This deletes the extra arguments.
3237 Call->setNumArgs(Context, NumArgsInProto);
3241 llvm::SmallVector<Expr *, 8> AllArgs;
3242 VariadicCallType CallType =
3243 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3244 if (Fn->getType()->isBlockPointerType())
3245 CallType = VariadicBlock; // Block
3246 else if (isa<MemberExpr>(Fn))
3247 CallType = VariadicMethod;
3248 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
3249 Proto, 0, Args, NumArgs, AllArgs, CallType);
3252 unsigned TotalNumArgs = AllArgs.size();
3253 for (unsigned i = 0; i < TotalNumArgs; ++i)
3254 Call->setArg(i, AllArgs[i]);
3259 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3260 FunctionDecl *FDecl,
3261 const FunctionProtoType *Proto,
3262 unsigned FirstProtoArg,
3263 Expr **Args, unsigned NumArgs,
3264 llvm::SmallVector<Expr *, 8> &AllArgs,
3265 VariadicCallType CallType) {
3266 unsigned NumArgsInProto = Proto->getNumArgs();
3267 unsigned NumArgsToCheck = NumArgs;
3268 bool Invalid = false;
3269 if (NumArgs != NumArgsInProto)
3270 // Use default arguments for missing arguments
3271 NumArgsToCheck = NumArgsInProto;
3273 // Continue to check argument types (even if we have too few/many args).
3274 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3275 QualType ProtoArgType = Proto->getArgType(i);
3278 if (ArgIx < NumArgs) {
3279 Arg = Args[ArgIx++];
3281 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3283 PDiag(diag::err_call_incomplete_argument)
3284 << Arg->getSourceRange()))
3287 // Pass the argument
3288 ParmVarDecl *Param = 0;
3289 if (FDecl && i < FDecl->getNumParams())
3290 Param = FDecl->getParamDecl(i);
3293 InitializedEntity Entity =
3294 Param? InitializedEntity::InitializeParameter(Param)
3295 : InitializedEntity::InitializeParameter(ProtoArgType);
3296 OwningExprResult ArgE = PerformCopyInitialization(Entity,
3299 if (ArgE.isInvalid())
3302 Arg = ArgE.takeAs<Expr>();
3304 ParmVarDecl *Param = FDecl->getParamDecl(i);
3306 OwningExprResult ArgExpr =
3307 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3308 if (ArgExpr.isInvalid())
3311 Arg = ArgExpr.takeAs<Expr>();
3313 AllArgs.push_back(Arg);
3316 // If this is a variadic call, handle args passed through "...".
3317 if (CallType != VariadicDoesNotApply) {
3318 // Promote the arguments (C99 6.5.2.2p7).
3319 for (unsigned i = ArgIx; i < NumArgs; i++) {
3320 Expr *Arg = Args[i];
3321 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
3322 AllArgs.push_back(Arg);
3328 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3329 /// This provides the location of the left/right parens and a list of comma
3331 Action::OwningExprResult
3332 Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3334 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
3335 unsigned NumArgs = args.size();
3337 // Since this might be a postfix expression, get rid of ParenListExprs.
3338 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
3340 Expr *Fn = fn.takeAs<Expr>();
3341 Expr **Args = reinterpret_cast<Expr**>(args.release());
3342 assert(Fn && "no function call expression");
3344 if (getLangOptions().CPlusPlus) {
3345 // If this is a pseudo-destructor expression, build the call immediately.
3346 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3348 // Pseudo-destructor calls should not have any arguments.
3349 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3350 << CodeModificationHint::CreateRemoval(
3351 SourceRange(Args[0]->getLocStart(),
3352 Args[NumArgs-1]->getLocEnd()));
3354 for (unsigned I = 0; I != NumArgs; ++I)
3355 Args[I]->Destroy(Context);
3360 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3364 // Determine whether this is a dependent call inside a C++ template,
3365 // in which case we won't do any semantic analysis now.
3366 // FIXME: Will need to cache the results of name lookup (including ADL) in
3368 bool Dependent = false;
3369 if (Fn->isTypeDependent())
3371 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3375 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3376 Context.DependentTy, RParenLoc));
3378 // Determine whether this is a call to an object (C++ [over.call.object]).
3379 if (Fn->getType()->isRecordType())
3380 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3381 CommaLocs, RParenLoc));
3383 Expr *NakedFn = Fn->IgnoreParens();
3385 // Determine whether this is a call to an unresolved member function.
3386 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3387 // If lookup was unresolved but not dependent (i.e. didn't find
3388 // an unresolved using declaration), it has to be an overloaded
3389 // function set, which means it must contain either multiple
3390 // declarations (all methods or method templates) or a single
3392 assert((MemE->getNumDecls() > 1) ||
3393 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
3396 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3397 CommaLocs, RParenLoc);
3400 // Determine whether this is a call to a member function.
3401 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
3402 NamedDecl *MemDecl = MemExpr->getMemberDecl();
3403 if (isa<CXXMethodDecl>(MemDecl))
3404 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3405 CommaLocs, RParenLoc);
3408 // Determine whether this is a call to a pointer-to-member function.
3409 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
3410 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3411 BO->getOpcode() == BinaryOperator::PtrMemI) {
3412 if (const FunctionProtoType *FPT =
3413 dyn_cast<FunctionProtoType>(BO->getType())) {
3414 QualType ResultTy = FPT->getResultType().getNonReferenceType();
3416 ExprOwningPtr<CXXMemberCallExpr>
3417 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3421 if (CheckCallReturnType(FPT->getResultType(),
3422 BO->getRHS()->getSourceRange().getBegin(),
3426 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3430 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3432 return ExprError(Diag(Fn->getLocStart(),
3433 diag::err_typecheck_call_not_function)
3434 << Fn->getType() << Fn->getSourceRange());
3439 // If we're directly calling a function, get the appropriate declaration.
3440 // Also, in C++, keep track of whether we should perform argument-dependent
3441 // lookup and whether there were any explicitly-specified template arguments.
3443 Expr *NakedFn = Fn->IgnoreParens();
3444 if (isa<UnresolvedLookupExpr>(NakedFn)) {
3445 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
3446 return BuildOverloadedCallExpr(Fn, ULE, LParenLoc, Args, NumArgs,
3447 CommaLocs, RParenLoc);
3450 NamedDecl *NDecl = 0;
3451 if (isa<DeclRefExpr>(NakedFn))
3452 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3454 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3457 /// BuildResolvedCallExpr - Build a call to a resolved expression,
3458 /// i.e. an expression not of \p OverloadTy. The expression should
3459 /// unary-convert to an expression of function-pointer or
3460 /// block-pointer type.
3462 /// \param NDecl the declaration being called, if available
3463 Sema::OwningExprResult
3464 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3465 SourceLocation LParenLoc,
3466 Expr **Args, unsigned NumArgs,
3467 SourceLocation RParenLoc) {
3468 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3470 // Promote the function operand.
3471 UsualUnaryConversions(Fn);
3473 // Make the call expr early, before semantic checks. This guarantees cleanup
3474 // of arguments and function on error.
3475 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3480 const FunctionType *FuncT;
3481 if (!Fn->getType()->isBlockPointerType()) {
3482 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3483 // have type pointer to function".
3484 const PointerType *PT = Fn->getType()->getAs<PointerType>();
3486 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3487 << Fn->getType() << Fn->getSourceRange());
3488 FuncT = PT->getPointeeType()->getAs<FunctionType>();
3489 } else { // This is a block call.
3490 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
3491 getAs<FunctionType>();
3494 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3495 << Fn->getType() << Fn->getSourceRange());
3497 // Check for a valid return type
3498 if (CheckCallReturnType(FuncT->getResultType(),
3499 Fn->getSourceRange().getBegin(), TheCall.get(),
3503 // We know the result type of the call, set it.
3504 TheCall->setType(FuncT->getResultType().getNonReferenceType());
3506 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
3507 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
3511 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
3514 // Check if we have too few/too many template arguments, based
3515 // on our knowledge of the function definition.
3516 const FunctionDecl *Def = 0;
3517 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
3518 const FunctionProtoType *Proto =
3519 Def->getType()->getAs<FunctionProtoType>();
3520 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3521 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3522 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3527 // Promote the arguments (C99 6.5.2.2p6).
3528 for (unsigned i = 0; i != NumArgs; i++) {
3529 Expr *Arg = Args[i];
3530 DefaultArgumentPromotion(Arg);
3531 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3533 PDiag(diag::err_call_incomplete_argument)
3534 << Arg->getSourceRange()))
3536 TheCall->setArg(i, Arg);
3540 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3541 if (!Method->isStatic())
3542 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3543 << Fn->getSourceRange());
3545 // Check for sentinels
3547 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
3549 // Do special checking on direct calls to functions.
3551 if (CheckFunctionCall(FDecl, TheCall.get()))
3554 if (unsigned BuiltinID = FDecl->getBuiltinID())
3555 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3557 if (CheckBlockCall(NDecl, TheCall.get()))
3561 return MaybeBindToTemporary(TheCall.take());
3564 Action::OwningExprResult
3565 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3566 SourceLocation RParenLoc, ExprArg InitExpr) {
3567 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
3569 QualType literalType = GetTypeFromParser(Ty);
3571 // FIXME: put back this assert when initializers are worked out.
3572 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
3573 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
3575 if (literalType->isArrayType()) {
3576 if (literalType->isVariableArrayType())
3577 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3578 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
3579 } else if (!literalType->isDependentType() &&
3580 RequireCompleteType(LParenLoc, literalType,
3581 PDiag(diag::err_typecheck_decl_incomplete_type)
3582 << SourceRange(LParenLoc,
3583 literalExpr->getSourceRange().getEnd())))
3586 InitializedEntity Entity
3587 = InitializedEntity::InitializeTemporary(literalType);
3588 InitializationKind Kind
3589 = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3590 /*IsCStyleCast=*/true);
3591 InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3592 OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3593 MultiExprArg(*this, (void**)&literalExpr, 1),
3595 if (Result.isInvalid())
3598 literalExpr = static_cast<Expr*>(Result.get());
3600 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
3601 if (isFileScope) { // 6.5.2.5p3
3602 if (CheckForConstantInitializer(literalExpr, literalType))
3608 // FIXME: Store the TInfo to preserve type information better.
3609 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
3610 literalExpr, isFileScope));
3613 Action::OwningExprResult
3614 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
3615 SourceLocation RBraceLoc) {
3616 unsigned NumInit = initlist.size();
3617 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
3619 // Semantic analysis for initializers is done by ActOnDeclarator() and
3620 // CheckInitializer() - it requires knowledge of the object being intialized.
3622 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
3624 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
3628 static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3629 QualType SrcTy, QualType DestTy) {
3630 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
3631 return CastExpr::CK_NoOp;
3633 if (SrcTy->hasPointerRepresentation()) {
3634 if (DestTy->hasPointerRepresentation())
3635 return DestTy->isObjCObjectPointerType() ?
3636 CastExpr::CK_AnyPointerToObjCPointerCast :
3637 CastExpr::CK_BitCast;
3638 if (DestTy->isIntegerType())
3639 return CastExpr::CK_PointerToIntegral;
3642 if (SrcTy->isIntegerType()) {
3643 if (DestTy->isIntegerType())
3644 return CastExpr::CK_IntegralCast;
3645 if (DestTy->hasPointerRepresentation())
3646 return CastExpr::CK_IntegralToPointer;
3647 if (DestTy->isRealFloatingType())
3648 return CastExpr::CK_IntegralToFloating;
3651 if (SrcTy->isRealFloatingType()) {
3652 if (DestTy->isRealFloatingType())
3653 return CastExpr::CK_FloatingCast;
3654 if (DestTy->isIntegerType())
3655 return CastExpr::CK_FloatingToIntegral;
3658 // FIXME: Assert here.
3659 // assert(false && "Unhandled cast combination!");
3660 return CastExpr::CK_Unknown;
3663 /// CheckCastTypes - Check type constraints for casting between types.
3664 bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
3665 CastExpr::CastKind& Kind,
3666 CXXMethodDecl *& ConversionDecl,
3667 bool FunctionalStyle) {
3668 if (getLangOptions().CPlusPlus)
3669 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3672 DefaultFunctionArrayConversion(castExpr);
3674 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3675 // type needs to be scalar.
3676 if (castType->isVoidType()) {
3677 // Cast to void allows any expr type.
3678 Kind = CastExpr::CK_ToVoid;
3682 if (!castType->isScalarType() && !castType->isVectorType()) {
3683 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
3684 (castType->isStructureType() || castType->isUnionType())) {
3685 // GCC struct/union extension: allow cast to self.
3686 // FIXME: Check that the cast destination type is complete.
3687 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3688 << castType << castExpr->getSourceRange();
3689 Kind = CastExpr::CK_NoOp;
3693 if (castType->isUnionType()) {
3694 // GCC cast to union extension
3695 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
3696 RecordDecl::field_iterator Field, FieldEnd;
3697 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
3698 Field != FieldEnd; ++Field) {
3699 if (Context.hasSameUnqualifiedType(Field->getType(),
3700 castExpr->getType())) {
3701 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3702 << castExpr->getSourceRange();
3706 if (Field == FieldEnd)
3707 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3708 << castExpr->getType() << castExpr->getSourceRange();
3709 Kind = CastExpr::CK_ToUnion;
3713 // Reject any other conversions to non-scalar types.
3714 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3715 << castType << castExpr->getSourceRange();
3718 if (!castExpr->getType()->isScalarType() &&
3719 !castExpr->getType()->isVectorType()) {
3720 return Diag(castExpr->getLocStart(),
3721 diag::err_typecheck_expect_scalar_operand)
3722 << castExpr->getType() << castExpr->getSourceRange();
3725 if (castType->isExtVectorType())
3726 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3728 if (castType->isVectorType())
3729 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3730 if (castExpr->getType()->isVectorType())
3731 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3733 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
3734 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
3736 if (isa<ObjCSelectorExpr>(castExpr))
3737 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3739 if (!castType->isArithmeticType()) {
3740 QualType castExprType = castExpr->getType();
3741 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3742 return Diag(castExpr->getLocStart(),
3743 diag::err_cast_pointer_from_non_pointer_int)
3744 << castExprType << castExpr->getSourceRange();
3745 } else if (!castExpr->getType()->isArithmeticType()) {
3746 if (!castType->isIntegralType() && castType->isArithmeticType())
3747 return Diag(castExpr->getLocStart(),
3748 diag::err_cast_pointer_to_non_pointer_int)
3749 << castType << castExpr->getSourceRange();
3752 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
3756 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3757 CastExpr::CastKind &Kind) {
3758 assert(VectorTy->isVectorType() && "Not a vector type!");
3760 if (Ty->isVectorType() || Ty->isIntegerType()) {
3761 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
3762 return Diag(R.getBegin(),
3763 Ty->isVectorType() ?
3764 diag::err_invalid_conversion_between_vectors :
3765 diag::err_invalid_conversion_between_vector_and_integer)
3766 << VectorTy << Ty << R;
3768 return Diag(R.getBegin(),
3769 diag::err_invalid_conversion_between_vector_and_scalar)
3770 << VectorTy << Ty << R;
3772 Kind = CastExpr::CK_BitCast;
3776 bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3777 CastExpr::CastKind &Kind) {
3778 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3780 QualType SrcTy = CastExpr->getType();
3782 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3783 // an ExtVectorType.
3784 if (SrcTy->isVectorType()) {
3785 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3786 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3787 << DestTy << SrcTy << R;
3788 Kind = CastExpr::CK_BitCast;
3792 // All non-pointer scalars can be cast to ExtVector type. The appropriate
3793 // conversion will take place first from scalar to elt type, and then
3794 // splat from elt type to vector.
3795 if (SrcTy->isPointerType())
3796 return Diag(R.getBegin(),
3797 diag::err_invalid_conversion_between_vector_and_scalar)
3798 << DestTy << SrcTy << R;
3800 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3801 ImpCastExprToType(CastExpr, DestElemTy,
3802 getScalarCastKind(Context, SrcTy, DestElemTy));
3804 Kind = CastExpr::CK_VectorSplat;
3808 Action::OwningExprResult
3809 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
3810 SourceLocation RParenLoc, ExprArg Op) {
3811 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3813 assert((Ty != 0) && (Op.get() != 0) &&
3814 "ActOnCastExpr(): missing type or expr");
3816 Expr *castExpr = (Expr *)Op.get();
3817 //FIXME: Preserve type source info.
3818 QualType castType = GetTypeFromParser(Ty);
3820 // If the Expr being casted is a ParenListExpr, handle it specially.
3821 if (isa<ParenListExpr>(castExpr))
3822 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
3823 CXXMethodDecl *Method = 0;
3824 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
3829 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
3832 if (CastArg.isInvalid())
3835 castExpr = CastArg.takeAs<Expr>();
3840 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
3841 Kind, castExpr, castType,
3842 LParenLoc, RParenLoc));
3845 /// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3846 /// of comma binary operators.
3847 Action::OwningExprResult
3848 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3849 Expr *expr = EA.takeAs<Expr>();
3850 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3854 OwningExprResult Result(*this, E->getExpr(0));
3856 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3857 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3858 Owned(E->getExpr(i)));
3860 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3863 Action::OwningExprResult
3864 Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3865 SourceLocation RParenLoc, ExprArg Op,
3867 ParenListExpr *PE = (ParenListExpr *)Op.get();
3869 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3870 // then handle it as such.
3871 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3872 if (PE->getNumExprs() == 0) {
3873 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3877 llvm::SmallVector<Expr *, 8> initExprs;
3878 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3879 initExprs.push_back(PE->getExpr(i));
3881 // FIXME: This means that pretty-printing the final AST will produce curly
3882 // braces instead of the original commas.
3884 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3885 initExprs.size(), RParenLoc);
3887 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3890 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3891 // sequence of BinOp comma operators.
3892 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3893 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3897 Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
3900 TypeTy *TypeOfCast) {
3901 unsigned nexprs = Val.size();
3902 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3903 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3905 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3906 expr = new (Context) ParenExpr(L, R, exprs[0]);
3908 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3912 /// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3913 /// In that case, lhs = cond.
3915 QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3916 SourceLocation QuestionLoc) {
3917 // C++ is sufficiently different to merit its own checker.
3918 if (getLangOptions().CPlusPlus)
3919 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3921 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3923 UsualUnaryConversions(Cond);
3924 UsualUnaryConversions(LHS);
3925 UsualUnaryConversions(RHS);
3926 QualType CondTy = Cond->getType();
3927 QualType LHSTy = LHS->getType();
3928 QualType RHSTy = RHS->getType();
3930 // first, check the condition.
3931 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3932 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3937 // Now check the two expressions.
3938 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3939 return CheckVectorOperands(QuestionLoc, LHS, RHS);
3941 // If both operands have arithmetic type, do the usual arithmetic conversions
3942 // to find a common type: C99 6.5.15p3,5.
3943 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3944 UsualArithmeticConversions(LHS, RHS);
3945 return LHS->getType();
3948 // If both operands are the same structure or union type, the result is that
3950 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3951 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
3952 if (LHSRT->getDecl() == RHSRT->getDecl())
3953 // "If both the operands have structure or union type, the result has
3954 // that type." This implies that CV qualifiers are dropped.
3955 return LHSTy.getUnqualifiedType();
3956 // FIXME: Type of conditional expression must be complete in C mode.
3959 // C99 6.5.15p5: "If both operands have void type, the result has void type."
3960 // The following || allows only one side to be void (a GCC-ism).
3961 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3962 if (!LHSTy->isVoidType())
3963 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3964 << RHS->getSourceRange();
3965 if (!RHSTy->isVoidType())
3966 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3967 << LHS->getSourceRange();
3968 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3969 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
3970 return Context.VoidTy;
3972 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3973 // the type of the other operand."
3974 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
3975 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3976 // promote the null to a pointer.
3977 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
3980 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
3981 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3982 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
3986 // All objective-c pointer type analysis is done here.
3987 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
3989 if (!compositeType.isNull())
3990 return compositeType;
3993 // Handle block pointer types.
3994 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3995 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3996 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3997 QualType destType = Context.getPointerType(Context.VoidTy);
3998 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3999 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4002 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4003 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4006 // We have 2 block pointer types.
4007 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4008 // Two identical block pointer types are always compatible.
4011 // The block pointer types aren't identical, continue checking.
4012 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4013 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
4015 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4016 rhptee.getUnqualifiedType())) {
4017 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4018 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4019 // In this situation, we assume void* type. No especially good
4020 // reason, but this is what gcc does, and we do have to pick
4021 // to get a consistent AST.
4022 QualType incompatTy = Context.getPointerType(Context.VoidTy);
4023 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4024 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4027 // The block pointer types are compatible.
4028 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4029 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4033 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4034 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4035 // get the "pointed to" types
4036 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4037 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4039 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4040 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4041 // Figure out necessary qualifiers (C99 6.5.15p6)
4042 QualType destPointee
4043 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4044 QualType destType = Context.getPointerType(destPointee);
4045 // Add qualifiers if necessary.
4046 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4047 // Promote to void*.
4048 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4051 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4052 QualType destPointee
4053 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4054 QualType destType = Context.getPointerType(destPointee);
4055 // Add qualifiers if necessary.
4056 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4057 // Promote to void*.
4058 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4062 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4063 // Two identical pointer types are always compatible.
4066 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4067 rhptee.getUnqualifiedType())) {
4068 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4069 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4070 // In this situation, we assume void* type. No especially good
4071 // reason, but this is what gcc does, and we do have to pick
4072 // to get a consistent AST.
4073 QualType incompatTy = Context.getPointerType(Context.VoidTy);
4074 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4075 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4078 // The pointer types are compatible.
4079 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4080 // differently qualified versions of compatible types, the result type is
4081 // a pointer to an appropriately qualified version of the *composite*
4083 // FIXME: Need to calculate the composite type.
4084 // FIXME: Need to add qualifiers
4085 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4086 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4090 // GCC compatibility: soften pointer/integer mismatch.
4091 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4092 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4093 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4094 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
4097 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4098 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4099 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4100 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
4104 // Otherwise, the operands are not compatible.
4105 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4106 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4110 /// FindCompositeObjCPointerType - Helper method to find composite type of
4111 /// two objective-c pointer types of the two input expressions.
4112 QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4113 SourceLocation QuestionLoc) {
4114 QualType LHSTy = LHS->getType();
4115 QualType RHSTy = RHS->getType();
4117 // Handle things like Class and struct objc_class*. Here we case the result
4118 // to the pseudo-builtin, because that will be implicitly cast back to the
4119 // redefinition type if an attempt is made to access its fields.
4120 if (LHSTy->isObjCClassType() &&
4121 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4122 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4125 if (RHSTy->isObjCClassType() &&
4126 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4127 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4130 // And the same for struct objc_object* / id
4131 if (LHSTy->isObjCIdType() &&
4132 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4133 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4136 if (RHSTy->isObjCIdType() &&
4137 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4138 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4141 // And the same for struct objc_selector* / SEL
4142 if (Context.isObjCSelType(LHSTy) &&
4143 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4144 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4147 if (Context.isObjCSelType(RHSTy) &&
4148 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4149 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4152 // Check constraints for Objective-C object pointers types.
4153 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4155 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4156 // Two identical object pointer types are always compatible.
4159 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4160 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4161 QualType compositeType = LHSTy;
4163 // If both operands are interfaces and either operand can be
4164 // assigned to the other, use that type as the composite
4165 // type. This allows
4166 // xxx ? (A*) a : (B*) b
4167 // where B is a subclass of A.
4169 // Additionally, as for assignment, if either type is 'id'
4170 // allow silent coercion. Finally, if the types are
4171 // incompatible then make sure to use 'id' as the composite
4172 // type so the result is acceptable for sending messages to.
4174 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4175 // It could return the composite type.
4176 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4177 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4178 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4179 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4180 } else if ((LHSTy->isObjCQualifiedIdType() ||
4181 RHSTy->isObjCQualifiedIdType()) &&
4182 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4183 // Need to handle "id<xx>" explicitly.
4184 // GCC allows qualified id and any Objective-C type to devolve to
4185 // id. Currently localizing to here until clear this should be
4186 // part of ObjCQualifiedIdTypesAreCompatible.
4187 compositeType = Context.getObjCIdType();
4188 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4189 compositeType = Context.getObjCIdType();
4190 } else if (!(compositeType =
4191 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4194 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4196 << LHS->getSourceRange() << RHS->getSourceRange();
4197 QualType incompatTy = Context.getObjCIdType();
4198 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4199 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4202 // The object pointer types are compatible.
4203 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4204 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4205 return compositeType;
4207 // Check Objective-C object pointer types and 'void *'
4208 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4209 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4210 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4211 QualType destPointee
4212 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4213 QualType destType = Context.getPointerType(destPointee);
4214 // Add qualifiers if necessary.
4215 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4216 // Promote to void*.
4217 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4220 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4221 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4222 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4223 QualType destPointee
4224 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4225 QualType destType = Context.getPointerType(destPointee);
4226 // Add qualifiers if necessary.
4227 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4228 // Promote to void*.
4229 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4235 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
4236 /// in the case of a the GNU conditional expr extension.
4237 Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4238 SourceLocation ColonLoc,
4239 ExprArg Cond, ExprArg LHS,
4241 Expr *CondExpr = (Expr *) Cond.get();
4242 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
4244 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4245 // was the condition.
4246 bool isLHSNull = LHSExpr == 0;
4250 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
4251 RHSExpr, QuestionLoc);
4252 if (result.isNull())
4258 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
4259 isLHSNull ? 0 : LHSExpr,
4260 ColonLoc, RHSExpr, result));
4263 // CheckPointerTypesForAssignment - This is a very tricky routine (despite
4264 // being closely modeled after the C99 spec:-). The odd characteristic of this
4265 // routine is it effectively iqnores the qualifiers on the top level pointee.
4266 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4267 // FIXME: add a couple examples in this comment.
4268 Sema::AssignConvertType
4269 Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4270 QualType lhptee, rhptee;
4272 if ((lhsType->isObjCClassType() &&
4273 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4274 (rhsType->isObjCClassType() &&
4275 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4279 // get the "pointed to" type (ignoring qualifiers at the top level)
4280 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4281 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
4283 // make sure we operate on the canonical type
4284 lhptee = Context.getCanonicalType(lhptee);
4285 rhptee = Context.getCanonicalType(rhptee);
4287 AssignConvertType ConvTy = Compatible;
4289 // C99 6.5.16.1p1: This following citation is common to constraints
4290 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4291 // qualifiers of the type *pointed to* by the right;
4292 // FIXME: Handle ExtQualType
4293 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4294 ConvTy = CompatiblePointerDiscardsQualifiers;
4296 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4297 // incomplete type and the other is a pointer to a qualified or unqualified
4298 // version of void...
4299 if (lhptee->isVoidType()) {
4300 if (rhptee->isIncompleteOrObjectType())
4303 // As an extension, we allow cast to/from void* to function pointer.
4304 assert(rhptee->isFunctionType());
4305 return FunctionVoidPointer;
4308 if (rhptee->isVoidType()) {
4309 if (lhptee->isIncompleteOrObjectType())
4312 // As an extension, we allow cast to/from void* to function pointer.
4313 assert(lhptee->isFunctionType());
4314 return FunctionVoidPointer;
4316 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
4317 // unqualified versions of compatible types, ...
4318 lhptee = lhptee.getUnqualifiedType();
4319 rhptee = rhptee.getUnqualifiedType();
4320 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4321 // Check if the pointee types are compatible ignoring the sign.
4322 // We explicitly check for char so that we catch "char" vs
4323 // "unsigned char" on systems where "char" is unsigned.
4324 if (lhptee->isCharType())
4325 lhptee = Context.UnsignedCharTy;
4326 else if (lhptee->isSignedIntegerType())
4327 lhptee = Context.getCorrespondingUnsignedType(lhptee);
4329 if (rhptee->isCharType())
4330 rhptee = Context.UnsignedCharTy;
4331 else if (rhptee->isSignedIntegerType())
4332 rhptee = Context.getCorrespondingUnsignedType(rhptee);
4334 if (lhptee == rhptee) {
4335 // Types are compatible ignoring the sign. Qualifier incompatibility
4336 // takes priority over sign incompatibility because the sign
4337 // warning can be disabled.
4338 if (ConvTy != Compatible)
4340 return IncompatiblePointerSign;
4343 // If we are a multi-level pointer, it's possible that our issue is simply
4344 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4345 // the eventual target type is the same and the pointers have the same
4346 // level of indirection, this must be the issue.
4347 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4349 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4350 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4352 lhptee = Context.getCanonicalType(lhptee);
4353 rhptee = Context.getCanonicalType(rhptee);
4354 } while (lhptee->isPointerType() && rhptee->isPointerType());
4356 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
4357 return IncompatibleNestedPointerQualifiers;
4360 // General pointer incompatibility takes priority over qualifiers.
4361 return IncompatiblePointer;
4366 /// CheckBlockPointerTypesForAssignment - This routine determines whether two
4367 /// block pointer types are compatible or whether a block and normal pointer
4368 /// are compatible. It is more restrict than comparing two function pointer
4370 Sema::AssignConvertType
4371 Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
4373 QualType lhptee, rhptee;
4375 // get the "pointed to" type (ignoring qualifiers at the top level)
4376 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4377 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
4379 // make sure we operate on the canonical type
4380 lhptee = Context.getCanonicalType(lhptee);
4381 rhptee = Context.getCanonicalType(rhptee);
4383 AssignConvertType ConvTy = Compatible;
4385 // For blocks we enforce that qualifiers are identical.
4386 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
4387 ConvTy = CompatiblePointerDiscardsQualifiers;
4389 if (!Context.typesAreCompatible(lhptee, rhptee))
4390 return IncompatibleBlockPointer;
4394 /// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4395 /// for assignment compatibility.
4396 Sema::AssignConvertType
4397 Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4398 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4401 lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4403 rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4404 // make sure we operate on the canonical type
4405 lhptee = Context.getCanonicalType(lhptee);
4406 rhptee = Context.getCanonicalType(rhptee);
4407 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4408 return CompatiblePointerDiscardsQualifiers;
4410 if (Context.typesAreCompatible(lhsType, rhsType))
4412 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4413 return IncompatibleObjCQualifiedId;
4414 return IncompatiblePointer;
4417 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4418 /// has code to accommodate several GCC extensions when type checking
4419 /// pointers. Here are some objectionable examples that GCC considers warnings:
4423 /// struct foo *pfoo;
4425 /// pint = pshort; // warning: assignment from incompatible pointer type
4426 /// a = pint; // warning: assignment makes integer from pointer without a cast
4427 /// pint = a; // warning: assignment makes pointer from integer without a cast
4428 /// pint = pfoo; // warning: assignment from incompatible pointer type
4430 /// As a result, the code for dealing with pointers is more complex than the
4431 /// C99 spec dictates.
4433 Sema::AssignConvertType
4434 Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
4435 // Get canonical types. We're not formatting these types, just comparing
4437 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4438 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
4440 if (lhsType == rhsType)
4441 return Compatible; // Common case: fast path an exact match.
4443 if ((lhsType->isObjCClassType() &&
4444 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4445 (rhsType->isObjCClassType() &&
4446 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4450 // If the left-hand side is a reference type, then we are in a
4451 // (rare!) case where we've allowed the use of references in C,
4452 // e.g., as a parameter type in a built-in function. In this case,
4453 // just make sure that the type referenced is compatible with the
4454 // right-hand side type. The caller is responsible for adjusting
4455 // lhsType so that the resulting expression does not have reference
4457 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
4458 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
4460 return Incompatible;
4462 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4463 // to the same ExtVector type.
4464 if (lhsType->isExtVectorType()) {
4465 if (rhsType->isExtVectorType())
4466 return lhsType == rhsType ? Compatible : Incompatible;
4467 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4471 if (lhsType->isVectorType() || rhsType->isVectorType()) {
4472 // If we are allowing lax vector conversions, and LHS and RHS are both
4473 // vectors, the total size only needs to be the same. This is a bitcast;
4474 // no bits are changed but the result type is different.
4475 if (getLangOptions().LaxVectorConversions &&
4476 lhsType->isVectorType() && rhsType->isVectorType()) {
4477 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
4478 return IncompatibleVectors;
4480 return Incompatible;
4483 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
4486 if (isa<PointerType>(lhsType)) {
4487 if (rhsType->isIntegerType())
4488 return IntToPointer;
4490 if (isa<PointerType>(rhsType))
4491 return CheckPointerTypesForAssignment(lhsType, rhsType);
4493 // In general, C pointers are not compatible with ObjC object pointers.
4494 if (isa<ObjCObjectPointerType>(rhsType)) {
4495 if (lhsType->isVoidPointerType()) // an exception to the rule.
4497 return IncompatiblePointer;
4499 if (rhsType->getAs<BlockPointerType>()) {
4500 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
4503 // Treat block pointers as objects.
4504 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
4507 return Incompatible;
4510 if (isa<BlockPointerType>(lhsType)) {
4511 if (rhsType->isIntegerType())
4512 return IntToBlockPointer;
4514 // Treat block pointers as objects.
4515 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
4518 if (rhsType->isBlockPointerType())
4519 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
4521 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
4522 if (RHSPT->getPointeeType()->isVoidType())
4525 return Incompatible;
4528 if (isa<ObjCObjectPointerType>(lhsType)) {
4529 if (rhsType->isIntegerType())
4530 return IntToPointer;
4532 // In general, C pointers are not compatible with ObjC object pointers.
4533 if (isa<PointerType>(rhsType)) {
4534 if (rhsType->isVoidPointerType()) // an exception to the rule.
4536 return IncompatiblePointer;
4538 if (rhsType->isObjCObjectPointerType()) {
4539 return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
4541 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
4542 if (RHSPT->getPointeeType()->isVoidType())
4545 // Treat block pointers as objects.
4546 if (rhsType->isBlockPointerType())
4548 return Incompatible;
4550 if (isa<PointerType>(rhsType)) {
4551 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4552 if (lhsType == Context.BoolTy)
4555 if (lhsType->isIntegerType())
4556 return PointerToInt;
4558 if (isa<PointerType>(lhsType))
4559 return CheckPointerTypesForAssignment(lhsType, rhsType);
4561 if (isa<BlockPointerType>(lhsType) &&
4562 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
4564 return Incompatible;
4566 if (isa<ObjCObjectPointerType>(rhsType)) {
4567 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4568 if (lhsType == Context.BoolTy)
4571 if (lhsType->isIntegerType())
4572 return PointerToInt;
4574 // In general, C pointers are not compatible with ObjC object pointers.
4575 if (isa<PointerType>(lhsType)) {
4576 if (lhsType->isVoidPointerType()) // an exception to the rule.
4578 return IncompatiblePointer;
4580 if (isa<BlockPointerType>(lhsType) &&
4581 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
4583 return Incompatible;
4586 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
4587 if (Context.typesAreCompatible(lhsType, rhsType))
4590 return Incompatible;
4593 /// \brief Constructs a transparent union from an expression that is
4594 /// used to initialize the transparent union.
4595 static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
4596 QualType UnionType, FieldDecl *Field) {
4597 // Build an initializer list that designates the appropriate member
4598 // of the transparent union.
4599 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4602 Initializer->setType(UnionType);
4603 Initializer->setInitializedFieldInUnion(Field);
4605 // Build a compound literal constructing a value of the transparent
4606 // union type from this initializer list.
4607 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4611 Sema::AssignConvertType
4612 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4613 QualType FromType = rExpr->getType();
4615 // If the ArgType is a Union type, we want to handle a potential
4616 // transparent_union GCC extension.
4617 const RecordType *UT = ArgType->getAsUnionType();
4618 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
4619 return Incompatible;
4621 // The field to initialize within the transparent union.
4622 RecordDecl *UD = UT->getDecl();
4623 FieldDecl *InitField = 0;
4624 // It's compatible if the expression matches any of the fields.
4625 for (RecordDecl::field_iterator it = UD->field_begin(),
4626 itend = UD->field_end();
4627 it != itend; ++it) {
4628 if (it->getType()->isPointerType()) {
4629 // If the transparent union contains a pointer type, we allow:
4631 // 2) null pointer constant
4632 if (FromType->isPointerType())
4633 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
4634 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
4639 if (rExpr->isNullPointerConstant(Context,
4640 Expr::NPC_ValueDependentIsNull)) {
4641 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
4647 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4655 return Incompatible;
4657 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4661 Sema::AssignConvertType
4662 Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
4663 if (getLangOptions().CPlusPlus) {
4664 if (!lhsType->isRecordType()) {
4665 // C++ 5.17p3: If the left operand is not of class type, the
4666 // expression is implicitly converted (C++ 4) to the
4667 // cv-unqualified type of the left operand.
4668 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4670 return Incompatible;
4674 // FIXME: Currently, we fall through and treat C++ classes like C
4678 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4679 // a null pointer constant.
4680 if ((lhsType->isPointerType() ||
4681 lhsType->isObjCObjectPointerType() ||
4682 lhsType->isBlockPointerType())
4683 && rExpr->isNullPointerConstant(Context,
4684 Expr::NPC_ValueDependentIsNull)) {
4685 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
4689 // This check seems unnatural, however it is necessary to ensure the proper
4690 // conversion of functions/arrays. If the conversion were done for all
4691 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
4692 // expressions that surpress this implicit conversion (&, sizeof).
4694 // Suppress this for references: C++ 8.5.3p5.
4695 if (!lhsType->isReferenceType())
4696 DefaultFunctionArrayConversion(rExpr);
4698 Sema::AssignConvertType result =
4699 CheckAssignmentConstraints(lhsType, rExpr->getType());
4701 // C99 6.5.16.1p2: The value of the right operand is converted to the
4702 // type of the assignment expression.
4703 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4704 // so that we can use references in built-in functions even in C.
4705 // The getNonReferenceType() call makes sure that the resulting expression
4706 // does not have reference type.
4707 if (result != Incompatible && rExpr->getType() != lhsType)
4708 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4709 CastExpr::CK_Unknown);
4713 QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
4714 Diag(Loc, diag::err_typecheck_invalid_operands)
4715 << lex->getType() << rex->getType()
4716 << lex->getSourceRange() << rex->getSourceRange();
4720 inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
4722 // For conversion purposes, we ignore any qualifiers.
4723 // For example, "const float" and "float" are equivalent.
4725 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4727 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
4729 // If the vector types are identical, return.
4730 if (lhsType == rhsType)
4733 // Handle the case of a vector & extvector type of the same size and element
4734 // type. It would be nice if we only had one vector type someday.
4735 if (getLangOptions().LaxVectorConversions) {
4736 // FIXME: Should we warn here?
4737 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4738 if (const VectorType *RV = rhsType->getAs<VectorType>())
4739 if (LV->getElementType() == RV->getElementType() &&
4740 LV->getNumElements() == RV->getNumElements()) {
4741 return lhsType->isExtVectorType() ? lhsType : rhsType;
4746 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4747 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4748 bool swapped = false;
4749 if (rhsType->isExtVectorType()) {
4751 std::swap(rex, lex);
4752 std::swap(rhsType, lhsType);
4755 // Handle the case of an ext vector and scalar.
4756 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
4757 QualType EltTy = LV->getElementType();
4758 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4759 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
4760 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
4761 if (swapped) std::swap(rex, lex);
4765 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4766 rhsType->isRealFloatingType()) {
4767 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
4768 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
4769 if (swapped) std::swap(rex, lex);
4775 // Vectors of different size or scalar and non-ext-vector are errors.
4776 Diag(Loc, diag::err_typecheck_vector_not_convertable)
4777 << lex->getType() << rex->getType()
4778 << lex->getSourceRange() << rex->getSourceRange();
4782 inline QualType Sema::CheckMultiplyDivideOperands(
4783 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4784 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4785 return CheckVectorOperands(Loc, lex, rex);
4787 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4789 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4791 return InvalidOperands(Loc, lex, rex);
4794 inline QualType Sema::CheckRemainderOperands(
4795 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4796 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4797 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4798 return CheckVectorOperands(Loc, lex, rex);
4799 return InvalidOperands(Loc, lex, rex);
4802 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4804 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4806 return InvalidOperands(Loc, lex, rex);
4809 inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
4810 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
4811 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4812 QualType compType = CheckVectorOperands(Loc, lex, rex);
4813 if (CompLHSTy) *CompLHSTy = compType;
4817 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
4819 // handle the common case first (both operands are arithmetic).
4820 if (lex->getType()->isArithmeticType() &&
4821 rex->getType()->isArithmeticType()) {
4822 if (CompLHSTy) *CompLHSTy = compType;
4826 // Put any potential pointer into PExp
4827 Expr* PExp = lex, *IExp = rex;
4828 if (IExp->getType()->isAnyPointerType())
4829 std::swap(PExp, IExp);
4831 if (PExp->getType()->isAnyPointerType()) {
4833 if (IExp->getType()->isIntegerType()) {
4834 QualType PointeeTy = PExp->getType()->getPointeeType();
4836 // Check for arithmetic on pointers to incomplete types.
4837 if (PointeeTy->isVoidType()) {
4838 if (getLangOptions().CPlusPlus) {
4839 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4840 << lex->getSourceRange() << rex->getSourceRange();
4844 // GNU extension: arithmetic on pointer to void
4845 Diag(Loc, diag::ext_gnu_void_ptr)
4846 << lex->getSourceRange() << rex->getSourceRange();
4847 } else if (PointeeTy->isFunctionType()) {
4848 if (getLangOptions().CPlusPlus) {
4849 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4850 << lex->getType() << lex->getSourceRange();
4854 // GNU extension: arithmetic on pointer to function
4855 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4856 << lex->getType() << lex->getSourceRange();
4858 // Check if we require a complete type.
4859 if (((PExp->getType()->isPointerType() &&
4860 !PExp->getType()->isDependentType()) ||
4861 PExp->getType()->isObjCObjectPointerType()) &&
4862 RequireCompleteType(Loc, PointeeTy,
4863 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4864 << PExp->getSourceRange()
4865 << PExp->getType()))
4868 // Diagnose bad cases where we step over interface counts.
4869 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4870 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4871 << PointeeTy << PExp->getSourceRange();
4876 QualType LHSTy = Context.isPromotableBitField(lex);
4877 if (LHSTy.isNull()) {
4878 LHSTy = lex->getType();
4879 if (LHSTy->isPromotableIntegerType())
4880 LHSTy = Context.getPromotedIntegerType(LHSTy);
4884 return PExp->getType();
4888 return InvalidOperands(Loc, lex, rex);
4892 QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
4893 SourceLocation Loc, QualType* CompLHSTy) {
4894 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4895 QualType compType = CheckVectorOperands(Loc, lex, rex);
4896 if (CompLHSTy) *CompLHSTy = compType;
4900 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
4902 // Enforce type constraints: C99 6.5.6p3.
4904 // Handle the common case first (both operands are arithmetic).
4905 if (lex->getType()->isArithmeticType()
4906 && rex->getType()->isArithmeticType()) {
4907 if (CompLHSTy) *CompLHSTy = compType;
4911 // Either ptr - int or ptr - ptr.
4912 if (lex->getType()->isAnyPointerType()) {
4913 QualType lpointee = lex->getType()->getPointeeType();
4915 // The LHS must be an completely-defined object type.
4917 bool ComplainAboutVoid = false;
4918 Expr *ComplainAboutFunc = 0;
4919 if (lpointee->isVoidType()) {
4920 if (getLangOptions().CPlusPlus) {
4921 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4922 << lex->getSourceRange() << rex->getSourceRange();
4926 // GNU C extension: arithmetic on pointer to void
4927 ComplainAboutVoid = true;
4928 } else if (lpointee->isFunctionType()) {
4929 if (getLangOptions().CPlusPlus) {
4930 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4931 << lex->getType() << lex->getSourceRange();
4935 // GNU C extension: arithmetic on pointer to function
4936 ComplainAboutFunc = lex;
4937 } else if (!lpointee->isDependentType() &&
4938 RequireCompleteType(Loc, lpointee,
4939 PDiag(diag::err_typecheck_sub_ptr_object)
4940 << lex->getSourceRange()
4944 // Diagnose bad cases where we step over interface counts.
4945 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4946 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4947 << lpointee << lex->getSourceRange();
4951 // The result type of a pointer-int computation is the pointer type.
4952 if (rex->getType()->isIntegerType()) {
4953 if (ComplainAboutVoid)
4954 Diag(Loc, diag::ext_gnu_void_ptr)
4955 << lex->getSourceRange() << rex->getSourceRange();
4956 if (ComplainAboutFunc)
4957 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4958 << ComplainAboutFunc->getType()
4959 << ComplainAboutFunc->getSourceRange();
4961 if (CompLHSTy) *CompLHSTy = lex->getType();
4962 return lex->getType();
4965 // Handle pointer-pointer subtractions.
4966 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
4967 QualType rpointee = RHSPTy->getPointeeType();
4969 // RHS must be a completely-type object type.
4970 // Handle the GNU void* extension.
4971 if (rpointee->isVoidType()) {
4972 if (getLangOptions().CPlusPlus) {
4973 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4974 << lex->getSourceRange() << rex->getSourceRange();
4978 ComplainAboutVoid = true;
4979 } else if (rpointee->isFunctionType()) {
4980 if (getLangOptions().CPlusPlus) {
4981 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4982 << rex->getType() << rex->getSourceRange();
4986 // GNU extension: arithmetic on pointer to function
4987 if (!ComplainAboutFunc)
4988 ComplainAboutFunc = rex;
4989 } else if (!rpointee->isDependentType() &&
4990 RequireCompleteType(Loc, rpointee,
4991 PDiag(diag::err_typecheck_sub_ptr_object)
4992 << rex->getSourceRange()
4996 if (getLangOptions().CPlusPlus) {
4997 // Pointee types must be the same: C++ [expr.add]
4998 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4999 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5000 << lex->getType() << rex->getType()
5001 << lex->getSourceRange() << rex->getSourceRange();
5005 // Pointee types must be compatible C99 6.5.6p3
5006 if (!Context.typesAreCompatible(
5007 Context.getCanonicalType(lpointee).getUnqualifiedType(),
5008 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5009 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5010 << lex->getType() << rex->getType()
5011 << lex->getSourceRange() << rex->getSourceRange();
5016 if (ComplainAboutVoid)
5017 Diag(Loc, diag::ext_gnu_void_ptr)
5018 << lex->getSourceRange() << rex->getSourceRange();
5019 if (ComplainAboutFunc)
5020 Diag(Loc, diag::ext_gnu_ptr_func_arith)
5021 << ComplainAboutFunc->getType()
5022 << ComplainAboutFunc->getSourceRange();
5024 if (CompLHSTy) *CompLHSTy = lex->getType();
5025 return Context.getPointerDiffType();
5029 return InvalidOperands(Loc, lex, rex);
5033 QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
5034 bool isCompAssign) {
5035 // C99 6.5.7p2: Each of the operands shall have integer type.
5036 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
5037 return InvalidOperands(Loc, lex, rex);
5039 // Vector shifts promote their scalar inputs to vector type.
5040 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5041 return CheckVectorOperands(Loc, lex, rex);
5043 // Shifts don't perform usual arithmetic conversions, they just do integer
5044 // promotions on each operand. C99 6.5.7p3
5045 QualType LHSTy = Context.isPromotableBitField(lex);
5046 if (LHSTy.isNull()) {
5047 LHSTy = lex->getType();
5048 if (LHSTy->isPromotableIntegerType())
5049 LHSTy = Context.getPromotedIntegerType(LHSTy);
5052 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
5054 UsualUnaryConversions(rex);
5056 // Sanity-check shift operands
5058 // Check right/shifter operand
5059 if (!rex->isValueDependent() &&
5060 rex->isIntegerConstantExpr(Right, Context)) {
5061 if (Right.isNegative())
5062 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5064 llvm::APInt LeftBits(Right.getBitWidth(),
5065 Context.getTypeSize(lex->getType()));
5066 if (Right.uge(LeftBits))
5067 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5071 // "The type of the result is that of the promoted left operand."
5075 /// \brief Implements -Wsign-compare.
5077 /// \param lex the left-hand expression
5078 /// \param rex the right-hand expression
5079 /// \param OpLoc the location of the joining operator
5080 /// \param Equality whether this is an "equality-like" join, which
5081 /// suppresses the warning in some cases
5082 void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
5083 const PartialDiagnostic &PD, bool Equality) {
5084 // Don't warn if we're in an unevaluated context.
5085 if (ExprEvalContexts.back().Context == Unevaluated)
5088 QualType lt = lex->getType(), rt = rex->getType();
5090 // Only warn if both operands are integral.
5091 if (!lt->isIntegerType() || !rt->isIntegerType())
5094 // If either expression is value-dependent, don't warn. We'll get another
5095 // chance at instantiation time.
5096 if (lex->isValueDependent() || rex->isValueDependent())
5099 // The rule is that the signed operand becomes unsigned, so isolate the
5101 Expr *signedOperand, *unsignedOperand;
5102 if (lt->isSignedIntegerType()) {
5103 if (rt->isSignedIntegerType()) return;
5104 signedOperand = lex;
5105 unsignedOperand = rex;
5107 if (!rt->isSignedIntegerType()) return;
5108 signedOperand = rex;
5109 unsignedOperand = lex;
5112 // If the unsigned type is strictly smaller than the signed type,
5113 // then (1) the result type will be signed and (2) the unsigned
5114 // value will fit fully within the signed type, and thus the result
5115 // of the comparison will be exact.
5116 if (Context.getIntWidth(signedOperand->getType()) >
5117 Context.getIntWidth(unsignedOperand->getType()))
5120 // If the value is a non-negative integer constant, then the
5121 // signed->unsigned conversion won't change it.
5123 if (signedOperand->isIntegerConstantExpr(value, Context)) {
5124 assert(value.isSigned() && "result of signed expression not signed");
5126 if (value.isNonNegative())
5131 // For (in)equality comparisons, if the unsigned operand is a
5132 // constant which cannot collide with a overflowed signed operand,
5133 // then reinterpreting the signed operand as unsigned will not
5134 // change the result of the comparison.
5135 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
5136 assert(!value.isSigned() && "result of unsigned expression is signed");
5138 // 2's complement: test the top bit.
5139 if (value.isNonNegative())
5145 << lex->getType() << rex->getType()
5146 << lex->getSourceRange() << rex->getSourceRange();
5149 // C99 6.5.8, C++ [expr.rel]
5150 QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
5151 unsigned OpaqueOpc, bool isRelational) {
5152 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5154 // Handle vector comparisons separately.
5155 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5156 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
5158 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5159 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
5161 // C99 6.5.8p3 / C99 6.5.9p4
5162 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5163 UsualArithmeticConversions(lex, rex);
5165 UsualUnaryConversions(lex);
5166 UsualUnaryConversions(rex);
5168 QualType lType = lex->getType();
5169 QualType rType = rex->getType();
5171 if (!lType->isFloatingType()
5172 && !(lType->isBlockPointerType() && isRelational)) {
5173 // For non-floating point types, check for self-comparisons of the form
5174 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5175 // often indicate logic errors in the program.
5176 // NOTE: Don't warn about comparisons of enum constants. These can arise
5177 // from macro expansions, and are usually quite deliberate.
5178 Expr *LHSStripped = lex->IgnoreParens();
5179 Expr *RHSStripped = rex->IgnoreParens();
5180 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5181 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
5182 if (DRL->getDecl() == DRR->getDecl() &&
5183 !isa<EnumConstantDecl>(DRL->getDecl()))
5184 Diag(Loc, diag::warn_selfcomparison);
5186 if (isa<CastExpr>(LHSStripped))
5187 LHSStripped = LHSStripped->IgnoreParenCasts();
5188 if (isa<CastExpr>(RHSStripped))
5189 RHSStripped = RHSStripped->IgnoreParenCasts();
5191 // Warn about comparisons against a string constant (unless the other
5192 // operand is null), the user probably wants strcmp.
5193 Expr *literalString = 0;
5194 Expr *literalStringStripped = 0;
5195 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
5196 !RHSStripped->isNullPointerConstant(Context,
5197 Expr::NPC_ValueDependentIsNull)) {
5198 literalString = lex;
5199 literalStringStripped = LHSStripped;
5200 } else if ((isa<StringLiteral>(RHSStripped) ||
5201 isa<ObjCEncodeExpr>(RHSStripped)) &&
5202 !LHSStripped->isNullPointerConstant(Context,
5203 Expr::NPC_ValueDependentIsNull)) {
5204 literalString = rex;
5205 literalStringStripped = RHSStripped;
5208 if (literalString) {
5209 std::string resultComparison;
5211 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5212 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5213 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5214 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5215 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5216 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5217 default: assert(false && "Invalid comparison operator");
5219 Diag(Loc, diag::warn_stringcompare)
5220 << isa<ObjCEncodeExpr>(literalStringStripped)
5221 << literalString->getSourceRange()
5222 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5223 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5225 << CodeModificationHint::CreateInsertion(
5226 PP.getLocForEndOfToken(rex->getLocEnd()),
5231 // The result of comparisons is 'bool' in C++, 'int' in C.
5232 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
5235 if (lType->isRealType() && rType->isRealType())
5238 // Check for comparisons of floating point operands using != and ==.
5239 if (lType->isFloatingType() && rType->isFloatingType())
5240 CheckFloatComparison(Loc,lex,rex);
5242 if (lType->isArithmeticType() && rType->isArithmeticType())
5246 bool LHSIsNull = lex->isNullPointerConstant(Context,
5247 Expr::NPC_ValueDependentIsNull);
5248 bool RHSIsNull = rex->isNullPointerConstant(Context,
5249 Expr::NPC_ValueDependentIsNull);
5251 // All of the following pointer related warnings are GCC extensions, except
5252 // when handling null pointer constants. One day, we can consider making them
5253 // errors (when -pedantic-errors is enabled).
5254 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
5255 QualType LCanPointeeTy =
5256 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
5257 QualType RCanPointeeTy =
5258 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
5260 if (getLangOptions().CPlusPlus) {
5261 if (LCanPointeeTy == RCanPointeeTy)
5263 if (!isRelational &&
5264 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5265 // Valid unless comparison between non-null pointer and function pointer
5266 // This is a gcc extension compatibility comparison.
5267 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5268 && !LHSIsNull && !RHSIsNull) {
5269 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5270 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5271 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5275 // C++ [expr.rel]p2:
5276 // [...] Pointer conversions (4.10) and qualification
5277 // conversions (4.4) are performed on pointer operands (or on
5278 // a pointer operand and a null pointer constant) to bring
5279 // them to their composite pointer type. [...]
5281 // C++ [expr.eq]p1 uses the same notion for (in)equality
5282 // comparisons of pointers.
5283 QualType T = FindCompositePointerType(lex, rex);
5285 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5286 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5290 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5291 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
5294 // C99 6.5.9p2 and C99 6.5.8p2
5295 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5296 RCanPointeeTy.getUnqualifiedType())) {
5297 // Valid unless a relational comparison of function pointers
5298 if (isRelational && LCanPointeeTy->isFunctionType()) {
5299 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5300 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5302 } else if (!isRelational &&
5303 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5304 // Valid unless comparison between non-null pointer and function pointer
5305 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5306 && !LHSIsNull && !RHSIsNull) {
5307 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5308 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5312 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5313 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5315 if (LCanPointeeTy != RCanPointeeTy)
5316 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5320 if (getLangOptions().CPlusPlus) {
5321 // Comparison of pointers with null pointer constants and equality
5322 // comparisons of member pointers to null pointer constants.
5324 (lType->isPointerType() ||
5325 (!isRelational && lType->isMemberPointerType()))) {
5326 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
5330 (rType->isPointerType() ||
5331 (!isRelational && rType->isMemberPointerType()))) {
5332 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
5336 // Comparison of member pointers.
5337 if (!isRelational &&
5338 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5340 // In addition, pointers to members can be compared, or a pointer to
5341 // member and a null pointer constant. Pointer to member conversions
5342 // (4.11) and qualification conversions (4.4) are performed to bring
5343 // them to a common type. If one operand is a null pointer constant,
5344 // the common type is the type of the other operand. Otherwise, the
5345 // common type is a pointer to member type similar (4.4) to the type
5346 // of one of the operands, with a cv-qualification signature (4.4)
5347 // that is the union of the cv-qualification signatures of the operand
5349 QualType T = FindCompositePointerType(lex, rex);
5351 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5352 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5356 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5357 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
5361 // Comparison of nullptr_t with itself.
5362 if (lType->isNullPtrType() && rType->isNullPtrType())
5366 // Handle block pointer types.
5367 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
5368 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5369 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
5371 if (!LHSIsNull && !RHSIsNull &&
5372 !Context.typesAreCompatible(lpointee, rpointee)) {
5373 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5374 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5376 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5379 // Allow block pointers to be compared with null pointer constants.
5381 && ((lType->isBlockPointerType() && rType->isPointerType())
5382 || (lType->isPointerType() && rType->isBlockPointerType()))) {
5383 if (!LHSIsNull && !RHSIsNull) {
5384 if (!((rType->isPointerType() && rType->getAs<PointerType>()
5385 ->getPointeeType()->isVoidType())
5386 || (lType->isPointerType() && lType->getAs<PointerType>()
5387 ->getPointeeType()->isVoidType())))
5388 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5389 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5391 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5395 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
5396 if (lType->isPointerType() || rType->isPointerType()) {
5397 const PointerType *LPT = lType->getAs<PointerType>();
5398 const PointerType *RPT = rType->getAs<PointerType>();
5399 bool LPtrToVoid = LPT ?
5400 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
5401 bool RPtrToVoid = RPT ?
5402 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
5404 if (!LPtrToVoid && !RPtrToVoid &&
5405 !Context.typesAreCompatible(lType, rType)) {
5406 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5407 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5409 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5412 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
5413 if (!Context.areComparableObjCPointerTypes(lType, rType))
5414 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5415 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5416 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5420 if (lType->isAnyPointerType() && rType->isIntegerType()) {
5421 unsigned DiagID = 0;
5424 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5425 } else if (isRelational)
5426 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5428 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
5432 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5434 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
5437 if (lType->isIntegerType() && rType->isAnyPointerType()) {
5438 unsigned DiagID = 0;
5441 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5442 } else if (isRelational)
5443 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5445 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
5449 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5451 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
5454 // Handle block pointers.
5455 if (!isRelational && RHSIsNull
5456 && lType->isBlockPointerType() && rType->isIntegerType()) {
5457 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
5460 if (!isRelational && LHSIsNull
5461 && lType->isIntegerType() && rType->isBlockPointerType()) {
5462 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
5465 return InvalidOperands(Loc, lex, rex);
5468 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
5469 /// operates on extended vector types. Instead of producing an IntTy result,
5470 /// like a scalar comparison, a vector comparison produces a vector of integer
5472 QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
5474 bool isRelational) {
5475 // Check to make sure we're operating on vectors of the same type and width,
5476 // Allowing one side to be a scalar of element type.
5477 QualType vType = CheckVectorOperands(Loc, lex, rex);
5481 QualType lType = lex->getType();
5482 QualType rType = rex->getType();
5484 // For non-floating point types, check for self-comparisons of the form
5485 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5486 // often indicate logic errors in the program.
5487 if (!lType->isFloatingType()) {
5488 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5489 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5490 if (DRL->getDecl() == DRR->getDecl())
5491 Diag(Loc, diag::warn_selfcomparison);
5494 // Check for comparisons of floating point operands using != and ==.
5495 if (!isRelational && lType->isFloatingType()) {
5496 assert (rType->isFloatingType());
5497 CheckFloatComparison(Loc,lex,rex);
5500 // Return the type for the comparison, which is the same as vector type for
5501 // integer vectors, or an integer type of identical size and number of
5502 // elements for floating point vectors.
5503 if (lType->isIntegerType())
5506 const VectorType *VTy = lType->getAs<VectorType>();
5507 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
5508 if (TypeSize == Context.getTypeSize(Context.IntTy))
5509 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
5510 if (TypeSize == Context.getTypeSize(Context.LongTy))
5511 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5513 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
5514 "Unhandled vector element size in vector compare");
5515 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5518 inline QualType Sema::CheckBitwiseOperands(
5519 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
5520 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5521 return CheckVectorOperands(Loc, lex, rex);
5523 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
5525 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
5527 return InvalidOperands(Loc, lex, rex);
5530 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
5531 Expr *&lex, Expr *&rex, SourceLocation Loc) {
5532 if (!Context.getLangOptions().CPlusPlus) {
5533 UsualUnaryConversions(lex);
5534 UsualUnaryConversions(rex);
5536 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5537 return InvalidOperands(Loc, lex, rex);
5539 return Context.IntTy;
5542 // C++ [expr.log.and]p1
5543 // C++ [expr.log.or]p1
5544 // The operands are both implicitly converted to type bool (clause 4).
5545 StandardConversionSequence LHS;
5546 if (!IsStandardConversion(lex, Context.BoolTy,
5547 /*InOverloadResolution=*/false, LHS))
5548 return InvalidOperands(Loc, lex, rex);
5550 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
5551 AA_Passing, /*IgnoreBaseAccess=*/false))
5552 return InvalidOperands(Loc, lex, rex);
5554 StandardConversionSequence RHS;
5555 if (!IsStandardConversion(rex, Context.BoolTy,
5556 /*InOverloadResolution=*/false, RHS))
5557 return InvalidOperands(Loc, lex, rex);
5559 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
5560 AA_Passing, /*IgnoreBaseAccess=*/false))
5561 return InvalidOperands(Loc, lex, rex);
5563 // C++ [expr.log.and]p2
5564 // C++ [expr.log.or]p2
5565 // The result is a bool.
5566 return Context.BoolTy;
5569 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5570 /// is a read-only property; return true if so. A readonly property expression
5571 /// depends on various declarations and thus must be treated specially.
5573 static bool IsReadonlyProperty(Expr *E, Sema &S) {
5574 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5575 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5576 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5577 QualType BaseType = PropExpr->getBase()->getType();
5578 if (const ObjCObjectPointerType *OPT =
5579 BaseType->getAsObjCInterfacePointerType())
5580 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5581 if (S.isPropertyReadonly(PDecl, IFace))
5588 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5589 /// emit an error and return true. If so, return false.
5590 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
5591 SourceLocation OrigLoc = Loc;
5592 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
5594 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5595 IsLV = Expr::MLV_ReadonlyProperty;
5596 if (IsLV == Expr::MLV_Valid)
5600 bool NeedType = false;
5601 switch (IsLV) { // C99 6.5.16p2
5602 default: assert(0 && "Unknown result from isModifiableLvalue!");
5603 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
5604 case Expr::MLV_ArrayType:
5605 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5608 case Expr::MLV_NotObjectType:
5609 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5612 case Expr::MLV_LValueCast:
5613 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5615 case Expr::MLV_InvalidExpression:
5616 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5618 case Expr::MLV_IncompleteType:
5619 case Expr::MLV_IncompleteVoidType:
5620 return S.RequireCompleteType(Loc, E->getType(),
5621 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5622 << E->getSourceRange());
5623 case Expr::MLV_DuplicateVectorComponents:
5624 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5626 case Expr::MLV_NotBlockQualified:
5627 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5629 case Expr::MLV_ReadonlyProperty:
5630 Diag = diag::error_readonly_property_assignment;
5632 case Expr::MLV_NoSetterProperty:
5633 Diag = diag::error_nosetter_property_assignment;
5635 case Expr::MLV_SubObjCPropertySetting:
5636 Diag = diag::error_no_subobject_property_setting;
5642 Assign = SourceRange(OrigLoc, OrigLoc);
5644 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
5646 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
5653 QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5655 QualType CompoundType) {
5656 // Verify that LHS is a modifiable lvalue, and emit error if not.
5657 if (CheckForModifiableLvalue(LHS, Loc, *this))
5660 QualType LHSType = LHS->getType();
5661 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
5663 AssignConvertType ConvTy;
5664 if (CompoundType.isNull()) {
5665 // Simple assignment "x = y".
5666 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
5667 // Special case of NSObject attributes on c-style pointer types.
5668 if (ConvTy == IncompatiblePointer &&
5669 ((Context.isObjCNSObjectType(LHSType) &&
5670 RHSType->isObjCObjectPointerType()) ||
5671 (Context.isObjCNSObjectType(RHSType) &&
5672 LHSType->isObjCObjectPointerType())))
5673 ConvTy = Compatible;
5675 // If the RHS is a unary plus or minus, check to see if they = and + are
5676 // right next to each other. If so, the user may have typo'd "x =+ 4"
5677 // instead of "x += 4".
5678 Expr *RHSCheck = RHS;
5679 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5680 RHSCheck = ICE->getSubExpr();
5681 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5682 if ((UO->getOpcode() == UnaryOperator::Plus ||
5683 UO->getOpcode() == UnaryOperator::Minus) &&
5684 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
5685 // Only if the two operators are exactly adjacent.
5686 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5687 // And there is a space or other character before the subexpr of the
5688 // unary +/-. We don't want to warn on "x=-1".
5689 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5690 UO->getSubExpr()->getLocStart().isFileID()) {
5691 Diag(Loc, diag::warn_not_compound_assign)
5692 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5693 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
5697 // Compound assignment "x += y"
5698 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
5701 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5705 // C99 6.5.16p3: The type of an assignment expression is the type of the
5706 // left operand unless the left operand has qualified type, in which case
5707 // it is the unqualified version of the type of the left operand.
5708 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5709 // is converted to the type of the assignment expression (above).
5710 // C++ 5.17p1: the type of the assignment expression is that of its left
5712 return LHSType.getUnqualifiedType();
5716 QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
5717 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
5718 DefaultFunctionArrayConversion(RHS);
5720 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5721 // incomplete in C++).
5723 return RHS->getType();
5726 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5727 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
5728 QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5730 if (Op->isTypeDependent())
5731 return Context.DependentTy;
5733 QualType ResType = Op->getType();
5734 assert(!ResType.isNull() && "no type for increment/decrement expression");
5736 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5737 // Decrement of bool is not allowed.
5739 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5742 // Increment of bool sets it to true, but is deprecated.
5743 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5744 } else if (ResType->isRealType()) {
5746 } else if (ResType->isAnyPointerType()) {
5747 QualType PointeeTy = ResType->getPointeeType();
5749 // C99 6.5.2.4p2, 6.5.6p2
5750 if (PointeeTy->isVoidType()) {
5751 if (getLangOptions().CPlusPlus) {
5752 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5753 << Op->getSourceRange();
5757 // Pointer to void is a GNU extension in C.
5758 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
5759 } else if (PointeeTy->isFunctionType()) {
5760 if (getLangOptions().CPlusPlus) {
5761 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5762 << Op->getType() << Op->getSourceRange();
5766 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
5767 << ResType << Op->getSourceRange();
5768 } else if (RequireCompleteType(OpLoc, PointeeTy,
5769 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5770 << Op->getSourceRange()
5773 // Diagnose bad cases where we step over interface counts.
5774 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5775 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5776 << PointeeTy << Op->getSourceRange();
5779 } else if (ResType->isComplexType()) {
5780 // C99 does not support ++/-- on complex types, we allow as an extension.
5781 Diag(OpLoc, diag::ext_integer_increment_complex)
5782 << ResType << Op->getSourceRange();
5784 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
5785 << ResType << int(isInc) << Op->getSourceRange();
5788 // At this point, we know we have a real, complex or pointer type.
5789 // Now make sure the operand is a modifiable lvalue.
5790 if (CheckForModifiableLvalue(Op, OpLoc, *this))
5795 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
5796 /// This routine allows us to typecheck complex/recursive expressions
5797 /// where the declaration is needed for type checking. We only need to
5798 /// handle cases when the expression references a function designator
5799 /// or is an lvalue. Here are some examples:
5801 /// - &*****f => f for f a function designator.
5803 /// - &s.zz[1].yy -> s, if zz is an array
5804 /// - *(x + 1) -> x, if x is an array
5805 /// - &"123"[2] -> 0
5806 /// - & __real__ x -> x
5807 static NamedDecl *getPrimaryDecl(Expr *E) {
5808 switch (E->getStmtClass()) {
5809 case Stmt::DeclRefExprClass:
5810 return cast<DeclRefExpr>(E)->getDecl();
5811 case Stmt::MemberExprClass:
5812 // If this is an arrow operator, the address is an offset from
5813 // the base's value, so the object the base refers to is
5815 if (cast<MemberExpr>(E)->isArrow())
5817 // Otherwise, the expression refers to a part of the base
5818 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
5819 case Stmt::ArraySubscriptExprClass: {
5820 // FIXME: This code shouldn't be necessary! We should catch the implicit
5821 // promotion of register arrays earlier.
5822 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5823 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5824 if (ICE->getSubExpr()->getType()->isArrayType())
5825 return getPrimaryDecl(ICE->getSubExpr());
5829 case Stmt::UnaryOperatorClass: {
5830 UnaryOperator *UO = cast<UnaryOperator>(E);
5832 switch(UO->getOpcode()) {
5833 case UnaryOperator::Real:
5834 case UnaryOperator::Imag:
5835 case UnaryOperator::Extension:
5836 return getPrimaryDecl(UO->getSubExpr());
5841 case Stmt::ParenExprClass:
5842 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
5843 case Stmt::ImplicitCastExprClass:
5844 // If the result of an implicit cast is an l-value, we care about
5845 // the sub-expression; otherwise, the result here doesn't matter.
5846 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
5852 /// CheckAddressOfOperand - The operand of & must be either a function
5853 /// designator or an lvalue designating an object. If it is an lvalue, the
5854 /// object cannot be declared with storage class register or be a bit field.
5855 /// Note: The usual conversions are *not* applied to the operand of the &
5856 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
5857 /// In C++, the operand might be an overloaded function name, in which case
5858 /// we allow the '&' but retain the overloaded-function type.
5859 QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
5860 // Make sure to ignore parentheses in subsequent checks
5861 op = op->IgnoreParens();
5863 if (op->isTypeDependent())
5864 return Context.DependentTy;
5866 if (getLangOptions().C99) {
5867 // Implement C99-only parts of addressof rules.
5868 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5869 if (uOp->getOpcode() == UnaryOperator::Deref)
5870 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5871 // (assuming the deref expression is valid).
5872 return uOp->getSubExpr()->getType();
5874 // Technically, there should be a check for array subscript
5875 // expressions here, but the result of one is always an lvalue anyway.
5877 NamedDecl *dcl = getPrimaryDecl(op);
5878 Expr::isLvalueResult lval = op->isLvalue(Context);
5880 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5882 // The operand must be either an l-value or a function designator
5883 if (!op->getType()->isFunctionType()) {
5884 // FIXME: emit more specific diag...
5885 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5886 << op->getSourceRange();
5889 } else if (op->getBitField()) { // C99 6.5.3.2p1
5890 // The operand cannot be a bit-field
5891 Diag(OpLoc, diag::err_typecheck_address_of)
5892 << "bit-field" << op->getSourceRange();
5894 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5895 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
5896 // The operand cannot be an element of a vector
5897 Diag(OpLoc, diag::err_typecheck_address_of)
5898 << "vector element" << op->getSourceRange();
5900 } else if (isa<ObjCPropertyRefExpr>(op)) {
5901 // cannot take address of a property expression.
5902 Diag(OpLoc, diag::err_typecheck_address_of)
5903 << "property expression" << op->getSourceRange();
5905 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5906 // FIXME: Can LHS ever be null here?
5907 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5908 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
5909 } else if (isa<UnresolvedLookupExpr>(op)) {
5910 return Context.OverloadTy;
5911 } else if (dcl) { // C99 6.5.3.2p1
5912 // We have an lvalue with a decl. Make sure the decl is not declared
5913 // with the register storage-class specifier.
5914 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5915 if (vd->getStorageClass() == VarDecl::Register) {
5916 Diag(OpLoc, diag::err_typecheck_address_of)
5917 << "register variable" << op->getSourceRange();
5920 } else if (isa<FunctionTemplateDecl>(dcl)) {
5921 return Context.OverloadTy;
5922 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
5923 // Okay: we can take the address of a field.
5924 // Could be a pointer to member, though, if there is an explicit
5925 // scope qualifier for the class.
5926 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
5927 DeclContext *Ctx = dcl->getDeclContext();
5928 if (Ctx && Ctx->isRecord()) {
5929 if (FD->getType()->isReferenceType()) {
5931 diag::err_cannot_form_pointer_to_member_of_reference_type)
5932 << FD->getDeclName() << FD->getType();
5936 return Context.getMemberPointerType(op->getType(),
5937 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
5940 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
5941 // Okay: we can take the address of a function.
5943 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5945 return Context.getMemberPointerType(op->getType(),
5946 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5947 } else if (!isa<FunctionDecl>(dcl))
5948 assert(0 && "Unknown/unexpected decl type");
5951 if (lval == Expr::LV_IncompleteVoidType) {
5952 // Taking the address of a void variable is technically illegal, but we
5953 // allow it in cases which are otherwise valid.
5954 // Example: "extern void x; void* y = &x;".
5955 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5958 // If the operand has type "type", the result has type "pointer to type".
5959 return Context.getPointerType(op->getType());
5962 QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
5963 if (Op->isTypeDependent())
5964 return Context.DependentTy;
5966 UsualUnaryConversions(Op);
5967 QualType Ty = Op->getType();
5969 // Note that per both C89 and C99, this is always legal, even if ptype is an
5970 // incomplete type or void. It would be possible to warn about dereferencing
5971 // a void pointer, but it's completely well-defined, and such a warning is
5972 // unlikely to catch any mistakes.
5973 if (const PointerType *PT = Ty->getAs<PointerType>())
5974 return PT->getPointeeType();
5976 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
5977 return OPT->getPointeeType();
5979 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
5980 << Ty << Op->getSourceRange();
5984 static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5985 tok::TokenKind Kind) {
5986 BinaryOperator::Opcode Opc;
5988 default: assert(0 && "Unknown binop!");
5989 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5990 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
5991 case tok::star: Opc = BinaryOperator::Mul; break;
5992 case tok::slash: Opc = BinaryOperator::Div; break;
5993 case tok::percent: Opc = BinaryOperator::Rem; break;
5994 case tok::plus: Opc = BinaryOperator::Add; break;
5995 case tok::minus: Opc = BinaryOperator::Sub; break;
5996 case tok::lessless: Opc = BinaryOperator::Shl; break;
5997 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5998 case tok::lessequal: Opc = BinaryOperator::LE; break;
5999 case tok::less: Opc = BinaryOperator::LT; break;
6000 case tok::greaterequal: Opc = BinaryOperator::GE; break;
6001 case tok::greater: Opc = BinaryOperator::GT; break;
6002 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
6003 case tok::equalequal: Opc = BinaryOperator::EQ; break;
6004 case tok::amp: Opc = BinaryOperator::And; break;
6005 case tok::caret: Opc = BinaryOperator::Xor; break;
6006 case tok::pipe: Opc = BinaryOperator::Or; break;
6007 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
6008 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
6009 case tok::equal: Opc = BinaryOperator::Assign; break;
6010 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
6011 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
6012 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
6013 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
6014 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
6015 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
6016 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
6017 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
6018 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
6019 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
6020 case tok::comma: Opc = BinaryOperator::Comma; break;
6025 static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6026 tok::TokenKind Kind) {
6027 UnaryOperator::Opcode Opc;
6029 default: assert(0 && "Unknown unary op!");
6030 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
6031 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
6032 case tok::amp: Opc = UnaryOperator::AddrOf; break;
6033 case tok::star: Opc = UnaryOperator::Deref; break;
6034 case tok::plus: Opc = UnaryOperator::Plus; break;
6035 case tok::minus: Opc = UnaryOperator::Minus; break;
6036 case tok::tilde: Opc = UnaryOperator::Not; break;
6037 case tok::exclaim: Opc = UnaryOperator::LNot; break;
6038 case tok::kw___real: Opc = UnaryOperator::Real; break;
6039 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
6040 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
6045 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
6046 /// operator @p Opc at location @c TokLoc. This routine only supports
6047 /// built-in operations; ActOnBinOp handles overloaded operators.
6048 Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6050 Expr *lhs, Expr *rhs) {
6051 QualType ResultTy; // Result type of the binary operator.
6052 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
6053 // The following two variables are used for compound assignment operators
6054 QualType CompLHSTy; // Type of LHS after promotions for computation
6055 QualType CompResultTy; // Type of computation result
6058 case BinaryOperator::Assign:
6059 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6061 case BinaryOperator::PtrMemD:
6062 case BinaryOperator::PtrMemI:
6063 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6064 Opc == BinaryOperator::PtrMemI);
6066 case BinaryOperator::Mul:
6067 case BinaryOperator::Div:
6068 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
6070 case BinaryOperator::Rem:
6071 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6073 case BinaryOperator::Add:
6074 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6076 case BinaryOperator::Sub:
6077 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6079 case BinaryOperator::Shl:
6080 case BinaryOperator::Shr:
6081 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6083 case BinaryOperator::LE:
6084 case BinaryOperator::LT:
6085 case BinaryOperator::GE:
6086 case BinaryOperator::GT:
6087 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
6089 case BinaryOperator::EQ:
6090 case BinaryOperator::NE:
6091 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
6093 case BinaryOperator::And:
6094 case BinaryOperator::Xor:
6095 case BinaryOperator::Or:
6096 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6098 case BinaryOperator::LAnd:
6099 case BinaryOperator::LOr:
6100 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6102 case BinaryOperator::MulAssign:
6103 case BinaryOperator::DivAssign:
6104 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
6105 CompLHSTy = CompResultTy;
6106 if (!CompResultTy.isNull())
6107 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6109 case BinaryOperator::RemAssign:
6110 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6111 CompLHSTy = CompResultTy;
6112 if (!CompResultTy.isNull())
6113 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6115 case BinaryOperator::AddAssign:
6116 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6117 if (!CompResultTy.isNull())
6118 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6120 case BinaryOperator::SubAssign:
6121 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6122 if (!CompResultTy.isNull())
6123 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6125 case BinaryOperator::ShlAssign:
6126 case BinaryOperator::ShrAssign:
6127 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6128 CompLHSTy = CompResultTy;
6129 if (!CompResultTy.isNull())
6130 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6132 case BinaryOperator::AndAssign:
6133 case BinaryOperator::XorAssign:
6134 case BinaryOperator::OrAssign:
6135 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6136 CompLHSTy = CompResultTy;
6137 if (!CompResultTy.isNull())
6138 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6140 case BinaryOperator::Comma:
6141 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6144 if (ResultTy.isNull())
6146 if (CompResultTy.isNull())
6147 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6149 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
6150 CompLHSTy, CompResultTy,
6154 /// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6155 /// ParenRange in parentheses.
6156 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6157 const PartialDiagnostic &PD,
6158 SourceRange ParenRange)
6160 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6161 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6162 // We can't display the parentheses, so just dig the
6163 // warning/error and return.
6169 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6170 << CodeModificationHint::CreateInsertion(EndLoc, ")");
6173 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6174 /// operators are mixed in a way that suggests that the programmer forgot that
6175 /// comparison operators have higher precedence. The most typical example of
6176 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
6177 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6178 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
6179 typedef BinaryOperator BinOp;
6180 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6181 rhsopc = static_cast<BinOp::Opcode>(-1);
6182 if (BinOp *BO = dyn_cast<BinOp>(lhs))
6183 lhsopc = BO->getOpcode();
6184 if (BinOp *BO = dyn_cast<BinOp>(rhs))
6185 rhsopc = BO->getOpcode();
6187 // Subs are not binary operators.
6188 if (lhsopc == -1 && rhsopc == -1)
6191 // Bitwise operations are sometimes used as eager logical ops.
6192 // Don't diagnose this.
6193 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6194 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
6197 if (BinOp::isComparisonOp(lhsopc))
6198 SuggestParentheses(Self, OpLoc,
6199 PDiag(diag::warn_precedence_bitwise_rel)
6200 << SourceRange(lhs->getLocStart(), OpLoc)
6201 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
6202 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6203 else if (BinOp::isComparisonOp(rhsopc))
6204 SuggestParentheses(Self, OpLoc,
6205 PDiag(diag::warn_precedence_bitwise_rel)
6206 << SourceRange(OpLoc, rhs->getLocEnd())
6207 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
6208 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
6211 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6212 /// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6213 /// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6214 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6215 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
6216 if (BinaryOperator::isBitwiseOp(Opc))
6217 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6220 // Binary Operators. 'Tok' is the token for the operator.
6221 Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6222 tok::TokenKind Kind,
6223 ExprArg LHS, ExprArg RHS) {
6224 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
6225 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
6227 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6228 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
6230 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6231 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6233 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6236 Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6237 BinaryOperator::Opcode Opc,
6238 Expr *lhs, Expr *rhs) {
6239 if (getLangOptions().CPlusPlus &&
6240 (lhs->getType()->isOverloadableType() ||
6241 rhs->getType()->isOverloadableType())) {
6242 // Find all of the overloaded operators visible from this
6243 // point. We perform both an operator-name lookup from the local
6244 // scope and an argument-dependent lookup based on the types of
6246 FunctionSet Functions;
6247 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6248 if (OverOp != OO_None) {
6250 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6252 Expr *Args[2] = { lhs, rhs };
6253 DeclarationName OpName
6254 = Context.DeclarationNames.getCXXOperatorName(OverOp);
6255 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
6258 // Build the (potentially-overloaded, potentially-dependent)
6259 // binary operation.
6260 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
6263 // Build a built-in binary operation.
6264 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
6267 Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
6270 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6272 // FIXME: Input is modified below, but InputArg is not updated appropriately.
6273 Expr *Input = (Expr *)InputArg.get();
6274 QualType resultType;
6276 case UnaryOperator::OffsetOf:
6277 assert(false && "Invalid unary operator");
6280 case UnaryOperator::PreInc:
6281 case UnaryOperator::PreDec:
6282 case UnaryOperator::PostInc:
6283 case UnaryOperator::PostDec:
6284 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
6285 Opc == UnaryOperator::PreInc ||
6286 Opc == UnaryOperator::PostInc);
6288 case UnaryOperator::AddrOf:
6289 resultType = CheckAddressOfOperand(Input, OpLoc);
6291 case UnaryOperator::Deref:
6292 DefaultFunctionArrayConversion(Input);
6293 resultType = CheckIndirectionOperand(Input, OpLoc);
6295 case UnaryOperator::Plus:
6296 case UnaryOperator::Minus:
6297 UsualUnaryConversions(Input);
6298 resultType = Input->getType();
6299 if (resultType->isDependentType())
6301 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6303 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6304 resultType->isEnumeralType())
6306 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6307 Opc == UnaryOperator::Plus &&
6308 resultType->isPointerType())
6311 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6312 << resultType << Input->getSourceRange());
6313 case UnaryOperator::Not: // bitwise complement
6314 UsualUnaryConversions(Input);
6315 resultType = Input->getType();
6316 if (resultType->isDependentType())
6318 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6319 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6320 // C99 does not support '~' for complex conjugation.
6321 Diag(OpLoc, diag::ext_integer_complement_complex)
6322 << resultType << Input->getSourceRange();
6323 else if (!resultType->isIntegerType())
6324 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6325 << resultType << Input->getSourceRange());
6327 case UnaryOperator::LNot: // logical negation
6328 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
6329 DefaultFunctionArrayConversion(Input);
6330 resultType = Input->getType();
6331 if (resultType->isDependentType())
6333 if (!resultType->isScalarType()) // C99 6.5.3.3p1
6334 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6335 << resultType << Input->getSourceRange());
6336 // LNot always has type int. C99 6.5.3.3p5.
6337 // In C++, it's bool. C++ 5.3.1p8
6338 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
6340 case UnaryOperator::Real:
6341 case UnaryOperator::Imag:
6342 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
6344 case UnaryOperator::Extension:
6345 resultType = Input->getType();
6348 if (resultType.isNull())
6352 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
6355 Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6356 UnaryOperator::Opcode Opc,
6358 Expr *Input = (Expr*)input.get();
6359 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6360 Opc != UnaryOperator::Extension) {
6361 // Find all of the overloaded operators visible from this
6362 // point. We perform both an operator-name lookup from the local
6363 // scope and an argument-dependent lookup based on the types of
6365 FunctionSet Functions;
6366 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6367 if (OverOp != OO_None) {
6369 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6371 DeclarationName OpName
6372 = Context.DeclarationNames.getCXXOperatorName(OverOp);
6373 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
6376 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6379 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6382 // Unary Operators. 'Tok' is the token for the operator.
6383 Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6384 tok::TokenKind Op, ExprArg input) {
6385 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6388 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
6389 Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6390 SourceLocation LabLoc,
6391 IdentifierInfo *LabelII) {
6392 // Look up the record for this label identifier.
6393 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
6395 // If we haven't seen this label yet, create a forward reference. It
6396 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
6398 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
6400 // Create the AST node. The address of a label always has type 'void*'.
6401 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6402 Context.getPointerType(Context.VoidTy)));
6405 Sema::OwningExprResult
6406 Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6407 SourceLocation RPLoc) { // "({..})"
6408 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
6409 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6410 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6412 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
6414 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
6416 // FIXME: there are a variety of strange constraints to enforce here, for
6417 // example, it is not possible to goto into a stmt expression apparently.
6418 // More semantic analysis is needed.
6420 // If there are sub stmts in the compound stmt, take the type of the last one
6421 // as the type of the stmtexpr.
6422 QualType Ty = Context.VoidTy;
6424 if (!Compound->body_empty()) {
6425 Stmt *LastStmt = Compound->body_back();
6426 // If LastStmt is a label, skip down through into the body.
6427 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6428 LastStmt = Label->getSubStmt();
6430 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
6431 Ty = LastExpr->getType();
6434 // FIXME: Check that expression type is complete/non-abstract; statement
6435 // expressions are not lvalues.
6438 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
6441 Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6442 SourceLocation BuiltinLoc,
6443 SourceLocation TypeLoc,
6445 OffsetOfComponent *CompPtr,
6446 unsigned NumComponents,
6447 SourceLocation RPLoc) {
6448 // FIXME: This function leaks all expressions in the offset components on
6450 // FIXME: Preserve type source info.
6451 QualType ArgTy = GetTypeFromParser(argty);
6452 assert(!ArgTy.isNull() && "Missing type argument!");
6454 bool Dependent = ArgTy->isDependentType();
6456 // We must have at least one component that refers to the type, and the first
6457 // one is known to be a field designator. Verify that the ArgTy represents
6458 // a struct/union/class.
6459 if (!Dependent && !ArgTy->isRecordType())
6460 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
6462 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6463 // with an incomplete type would be illegal.
6465 // Otherwise, create a null pointer as the base, and iteratively process
6466 // the offsetof designators.
6467 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6468 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
6469 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
6470 ArgTy, SourceLocation());
6472 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6473 // GCC extension, diagnose them.
6474 // FIXME: This diagnostic isn't actually visible because the location is in
6476 if (NumComponents != 1)
6477 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6478 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
6481 bool DidWarnAboutNonPOD = false;
6483 if (RequireCompleteType(TypeLoc, Res->getType(),
6484 diag::err_offsetof_incomplete_type))
6487 // FIXME: Dependent case loses a lot of information here. And probably
6488 // leaks like a sieve.
6489 for (unsigned i = 0; i != NumComponents; ++i) {
6490 const OffsetOfComponent &OC = CompPtr[i];
6491 if (OC.isBrackets) {
6492 // Offset of an array sub-field. TODO: Should we allow vector elements?
6493 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6495 Res->Destroy(Context);
6496 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6500 // FIXME: C++: Verify that operator[] isn't overloaded.
6502 // Promote the array so it looks more like a normal array subscript
6504 DefaultFunctionArrayConversion(Res);
6507 Expr *Idx = static_cast<Expr*>(OC.U.E);
6509 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
6510 return ExprError(Diag(Idx->getLocStart(),
6511 diag::err_typecheck_subscript_not_integer)
6512 << Idx->getSourceRange());
6514 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6519 const RecordType *RC = Res->getType()->getAs<RecordType>();
6521 Res->Destroy(Context);
6522 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6526 // Get the decl corresponding to this.
6527 RecordDecl *RD = RC->getDecl();
6528 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6529 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6530 DiagRuntimeBehavior(BuiltinLoc,
6531 PDiag(diag::warn_offsetof_non_pod_type)
6532 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6534 DidWarnAboutNonPOD = true;
6537 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6538 LookupQualifiedName(R, RD);
6540 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
6543 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6544 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
6546 // FIXME: C++: Verify that MemberDecl isn't a static field.
6547 // FIXME: Verify that MemberDecl isn't a bitfield.
6548 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
6549 Res = BuildAnonymousStructUnionMemberReference(
6550 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
6552 PerformObjectMemberConversion(Res, MemberDecl);
6553 // MemberDecl->getType() doesn't get the right qualifiers, but it
6554 // doesn't matter here.
6555 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6556 MemberDecl->getType().getNonReferenceType());
6561 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6562 Context.getSizeType(), BuiltinLoc));
6566 Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6567 TypeTy *arg1,TypeTy *arg2,
6568 SourceLocation RPLoc) {
6569 // FIXME: Preserve type source info.
6570 QualType argT1 = GetTypeFromParser(arg1);
6571 QualType argT2 = GetTypeFromParser(arg2);
6573 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
6575 if (getLangOptions().CPlusPlus) {
6576 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6577 << SourceRange(BuiltinLoc, RPLoc);
6581 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6582 argT1, argT2, RPLoc));
6585 Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6587 ExprArg expr1, ExprArg expr2,
6588 SourceLocation RPLoc) {
6589 Expr *CondExpr = static_cast<Expr*>(cond.get());
6590 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6591 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
6593 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6596 bool ValueDependent = false;
6597 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
6598 resType = Context.DependentTy;
6599 ValueDependent = true;
6601 // The conditional expression is required to be a constant expression.
6602 llvm::APSInt condEval(32);
6603 SourceLocation ExpLoc;
6604 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
6605 return ExprError(Diag(ExpLoc,
6606 diag::err_typecheck_choose_expr_requires_constant)
6607 << CondExpr->getSourceRange());
6609 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6610 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
6611 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6612 : RHSExpr->isValueDependent();
6615 cond.release(); expr1.release(); expr2.release();
6616 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
6618 resType->isDependentType(),
6622 //===----------------------------------------------------------------------===//
6623 // Clang Extensions.
6624 //===----------------------------------------------------------------------===//
6626 /// ActOnBlockStart - This callback is invoked when a block literal is started.
6627 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
6628 // Analyze block parameters.
6629 BlockSemaInfo *BSI = new BlockSemaInfo();
6631 // Add BSI to CurBlock.
6632 BSI->PrevBlockInfo = CurBlock;
6635 BSI->ReturnType = QualType();
6636 BSI->TheScope = BlockScope;
6637 BSI->hasBlockDeclRefExprs = false;
6638 BSI->hasPrototype = false;
6639 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6640 CurFunctionNeedsScopeChecking = false;
6642 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
6643 CurContext->addDecl(BSI->TheDecl);
6644 PushDeclContext(BlockScope, BSI->TheDecl);
6647 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
6648 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
6650 if (ParamInfo.getNumTypeObjects() == 0
6651 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
6652 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
6653 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6655 if (T->isArrayType()) {
6656 Diag(ParamInfo.getSourceRange().getBegin(),
6657 diag::err_block_returns_array);
6661 // The parameter list is optional, if there was none, assume ().
6662 if (!T->isFunctionType())
6663 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6665 CurBlock->hasPrototype = true;
6666 CurBlock->isVariadic = false;
6667 // Check for a valid sentinel attribute on this block.
6668 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
6669 Diag(ParamInfo.getAttributes()->getLoc(),
6670 diag::warn_attribute_sentinel_not_variadic) << 1;
6671 // FIXME: remove the attribute.
6673 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
6675 // Do not allow returning a objc interface by-value.
6676 if (RetTy->isObjCInterfaceType()) {
6677 Diag(ParamInfo.getSourceRange().getBegin(),
6678 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6684 // Analyze arguments to block.
6685 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6686 "Not a function declarator!");
6687 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
6689 CurBlock->hasPrototype = FTI.hasPrototype;
6690 CurBlock->isVariadic = true;
6692 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6693 // no arguments, not a function that takes a single void argument.
6694 if (FTI.hasPrototype &&
6695 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
6696 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6697 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
6698 // empty arg list, don't push any params.
6699 CurBlock->isVariadic = false;
6700 } else if (FTI.hasPrototype) {
6701 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
6702 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
6703 CurBlock->isVariadic = FTI.isVariadic;
6705 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
6706 CurBlock->Params.size());
6707 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
6708 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
6709 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6710 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6711 // If this has an identifier, add it to the scope stack.
6712 if ((*AI)->getIdentifier())
6713 PushOnScopeChains(*AI, CurBlock->TheScope);
6715 // Check for a valid sentinel attribute on this block.
6716 if (!CurBlock->isVariadic &&
6717 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
6718 Diag(ParamInfo.getAttributes()->getLoc(),
6719 diag::warn_attribute_sentinel_not_variadic) << 1;
6720 // FIXME: remove the attribute.
6723 // Analyze the return type.
6724 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6725 QualType RetTy = T->getAs<FunctionType>()->getResultType();
6727 // Do not allow returning a objc interface by-value.
6728 if (RetTy->isObjCInterfaceType()) {
6729 Diag(ParamInfo.getSourceRange().getBegin(),
6730 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6731 } else if (!RetTy->isDependentType())
6732 CurBlock->ReturnType = RetTy;
6735 /// ActOnBlockError - If there is an error parsing a block, this callback
6736 /// is invoked to pop the information about the block from the action impl.
6737 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6738 // Ensure that CurBlock is deleted.
6739 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
6741 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6743 // Pop off CurBlock, handle nested blocks.
6745 CurBlock = CurBlock->PrevBlockInfo;
6746 // FIXME: Delete the ParmVarDecl objects as well???
6749 /// ActOnBlockStmtExpr - This is called when the body of a block statement
6750 /// literal was successfully completed. ^(int x){...}
6751 Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6752 StmtArg body, Scope *CurScope) {
6753 // If blocks are disabled, emit an error.
6754 if (!LangOpts.Blocks)
6755 Diag(CaretLoc, diag::err_blocks_disable);
6757 // Ensure that CurBlock is deleted.
6758 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
6762 // Pop off CurBlock, handle nested blocks.
6763 CurBlock = CurBlock->PrevBlockInfo;
6765 QualType RetTy = Context.VoidTy;
6766 if (!BSI->ReturnType.isNull())
6767 RetTy = BSI->ReturnType;
6769 llvm::SmallVector<QualType, 8> ArgTypes;
6770 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6771 ArgTypes.push_back(BSI->Params[i]->getType());
6773 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
6775 if (!BSI->hasPrototype)
6776 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6779 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
6780 BSI->isVariadic, 0, false, false, 0, 0,
6783 // FIXME: Check that return/parameter types are complete/non-abstract
6784 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
6785 BlockTy = Context.getBlockPointerType(BlockTy);
6787 // If needed, diagnose invalid gotos and switches in the block.
6788 if (CurFunctionNeedsScopeChecking)
6789 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6790 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
6792 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
6793 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
6794 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6795 BSI->hasBlockDeclRefExprs));
6798 Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6799 ExprArg expr, TypeTy *type,
6800 SourceLocation RPLoc) {
6801 QualType T = GetTypeFromParser(type);
6802 Expr *E = static_cast<Expr*>(expr.get());
6805 InitBuiltinVaListType();
6807 // Get the va_list type
6808 QualType VaListType = Context.getBuiltinVaListType();
6809 if (VaListType->isArrayType()) {
6810 // Deal with implicit array decay; for example, on x86-64,
6811 // va_list is an array, but it's supposed to decay to
6812 // a pointer for va_arg.
6813 VaListType = Context.getArrayDecayedType(VaListType);
6814 // Make sure the input expression also decays appropriately.
6815 UsualUnaryConversions(E);
6817 // Otherwise, the va_list argument must be an l-value because
6818 // it is modified by va_arg.
6819 if (!E->isTypeDependent() &&
6820 CheckForModifiableLvalue(E, BuiltinLoc, *this))
6824 if (!E->isTypeDependent() &&
6825 !Context.hasSameType(VaListType, E->getType())) {
6826 return ExprError(Diag(E->getLocStart(),
6827 diag::err_first_argument_to_va_arg_not_of_type_va_list)
6828 << OrigExpr->getType() << E->getSourceRange());
6831 // FIXME: Check that type is complete/non-abstract
6832 // FIXME: Warn if a non-POD type is passed in.
6835 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6839 Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
6840 // The type of __null will be int or long, depending on the size of
6841 // pointers on the target.
6843 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6846 Ty = Context.LongTy;
6848 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
6852 MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6855 CodeModificationHint &Hint) {
6856 if (!SemaRef.getLangOptions().ObjC1)
6859 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6863 // Check if the destination is of type 'id'.
6864 if (!PT->isObjCIdType()) {
6865 // Check if the destination is the 'NSString' interface.
6866 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6867 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6871 // Strip off any parens and casts.
6872 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6873 if (!SL || SL->isWide())
6876 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6879 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6881 QualType DstType, QualType SrcType,
6882 Expr *SrcExpr, AssignmentAction Action) {
6883 // Decode the result (notice that AST's are still created for extensions).
6884 bool isInvalid = false;
6886 CodeModificationHint Hint;
6889 default: assert(0 && "Unknown conversion type");
6890 case Compatible: return false;
6892 DiagKind = diag::ext_typecheck_convert_pointer_int;
6895 DiagKind = diag::ext_typecheck_convert_int_pointer;
6897 case IncompatiblePointer:
6898 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
6899 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6901 case IncompatiblePointerSign:
6902 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6904 case FunctionVoidPointer:
6905 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6907 case CompatiblePointerDiscardsQualifiers:
6908 // If the qualifiers lost were because we were applying the
6909 // (deprecated) C++ conversion from a string literal to a char*
6910 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6911 // Ideally, this check would be performed in
6912 // CheckPointerTypesForAssignment. However, that would require a
6913 // bit of refactoring (so that the second argument is an
6914 // expression, rather than a type), which should be done as part
6915 // of a larger effort to fix CheckPointerTypesForAssignment for
6917 if (getLangOptions().CPlusPlus &&
6918 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6920 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6922 case IncompatibleNestedPointerQualifiers:
6923 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
6925 case IntToBlockPointer:
6926 DiagKind = diag::err_int_to_block_pointer;
6928 case IncompatibleBlockPointer:
6929 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
6931 case IncompatibleObjCQualifiedId:
6932 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
6933 // it can give a more specific diagnostic.
6934 DiagKind = diag::warn_incompatible_qualified_id;
6936 case IncompatibleVectors:
6937 DiagKind = diag::warn_incompatible_vectors;
6940 DiagKind = diag::err_typecheck_convert_incompatible;
6945 Diag(Loc, DiagKind) << DstType << SrcType << Action
6946 << SrcExpr->getSourceRange() << Hint;
6950 bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
6951 llvm::APSInt ICEResult;
6952 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6954 *Result = ICEResult;
6958 Expr::EvalResult EvalResult;
6960 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
6961 EvalResult.HasSideEffects) {
6962 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6964 if (EvalResult.Diag) {
6965 // We only show the note if it's not the usual "invalid subexpression"
6966 // or if it's actually in a subexpression.
6967 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6968 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6969 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6975 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6976 E->getSourceRange();
6978 if (EvalResult.Diag &&
6979 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6980 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6983 *Result = EvalResult.Val.getInt();
6988 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
6989 ExprEvalContexts.push_back(
6990 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
6994 Sema::PopExpressionEvaluationContext() {
6995 // Pop the current expression evaluation context off the stack.
6996 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
6997 ExprEvalContexts.pop_back();
6999 if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7000 if (Rec.PotentiallyReferenced) {
7001 // Mark any remaining declarations in the current position of the stack
7002 // as "referenced". If they were not meant to be referenced, semantic
7003 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
7004 for (PotentiallyReferencedDecls::iterator
7005 I = Rec.PotentiallyReferenced->begin(),
7006 IEnd = Rec.PotentiallyReferenced->end();
7008 MarkDeclarationReferenced(I->first, I->second);
7011 if (Rec.PotentiallyDiagnosed) {
7012 // Emit any pending diagnostics.
7013 for (PotentiallyEmittedDiagnostics::iterator
7014 I = Rec.PotentiallyDiagnosed->begin(),
7015 IEnd = Rec.PotentiallyDiagnosed->end();
7017 Diag(I->first, I->second);
7021 // When are coming out of an unevaluated context, clear out any
7022 // temporaries that we may have created as part of the evaluation of
7023 // the expression in that context: they aren't relevant because they
7024 // will never be constructed.
7025 if (Rec.Context == Unevaluated &&
7026 ExprTemporaries.size() > Rec.NumTemporaries)
7027 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7028 ExprTemporaries.end());
7030 // Destroy the popped expression evaluation record.
7034 /// \brief Note that the given declaration was referenced in the source code.
7036 /// This routine should be invoke whenever a given declaration is referenced
7037 /// in the source code, and where that reference occurred. If this declaration
7038 /// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7039 /// C99 6.9p3), then the declaration will be marked as used.
7041 /// \param Loc the location where the declaration was referenced.
7043 /// \param D the declaration that has been referenced by the source code.
7044 void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7045 assert(D && "No declaration?");
7050 // Mark a parameter or variable declaration "used", regardless of whether we're in a
7051 // template or not. The reason for this is that unevaluated expressions
7052 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7053 // -Wunused-parameters)
7054 if (isa<ParmVarDecl>(D) ||
7055 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
7058 // Do not mark anything as "used" within a dependent context; wait for
7059 // an instantiation.
7060 if (CurContext->isDependentContext())
7063 switch (ExprEvalContexts.back().Context) {
7065 // We are in an expression that is not potentially evaluated; do nothing.
7068 case PotentiallyEvaluated:
7069 // We are in a potentially-evaluated expression, so this declaration is
7070 // "used"; handle this below.
7073 case PotentiallyPotentiallyEvaluated:
7074 // We are in an expression that may be potentially evaluated; queue this
7075 // declaration reference until we know whether the expression is
7076 // potentially evaluated.
7077 ExprEvalContexts.back().addReferencedDecl(Loc, D);
7081 // Note that this declaration has been used.
7082 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
7084 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7085 if (!Constructor->isUsed())
7086 DefineImplicitDefaultConstructor(Loc, Constructor);
7087 } else if (Constructor->isImplicit() &&
7088 Constructor->isCopyConstructor(TypeQuals)) {
7089 if (!Constructor->isUsed())
7090 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7093 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
7094 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7095 if (Destructor->isImplicit() && !Destructor->isUsed())
7096 DefineImplicitDestructor(Loc, Destructor);
7098 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7099 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7100 MethodDecl->getOverloadedOperator() == OO_Equal) {
7101 if (!MethodDecl->isUsed())
7102 DefineImplicitOverloadedAssign(Loc, MethodDecl);
7105 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
7106 // Implicit instantiation of function templates and member functions of
7108 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
7109 bool AlreadyInstantiated = false;
7110 if (FunctionTemplateSpecializationInfo *SpecInfo
7111 = Function->getTemplateSpecializationInfo()) {
7112 if (SpecInfo->getPointOfInstantiation().isInvalid())
7113 SpecInfo->setPointOfInstantiation(Loc);
7114 else if (SpecInfo->getTemplateSpecializationKind()
7115 == TSK_ImplicitInstantiation)
7116 AlreadyInstantiated = true;
7117 } else if (MemberSpecializationInfo *MSInfo
7118 = Function->getMemberSpecializationInfo()) {
7119 if (MSInfo->getPointOfInstantiation().isInvalid())
7120 MSInfo->setPointOfInstantiation(Loc);
7121 else if (MSInfo->getTemplateSpecializationKind()
7122 == TSK_ImplicitInstantiation)
7123 AlreadyInstantiated = true;
7126 if (!AlreadyInstantiated)
7127 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
7130 // FIXME: keep track of references to static functions
7131 Function->setUsed(true);
7135 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
7136 // Implicit instantiation of static data members of class templates.
7137 if (Var->isStaticDataMember() &&
7138 Var->getInstantiatedFromStaticDataMember()) {
7139 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7140 assert(MSInfo && "Missing member specialization information?");
7141 if (MSInfo->getPointOfInstantiation().isInvalid() &&
7142 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7143 MSInfo->setPointOfInstantiation(Loc);
7144 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7148 // FIXME: keep track of references to static data?
7155 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
7156 /// of the program being compiled.
7158 /// This routine emits the given diagnostic when the code currently being
7159 /// type-checked is "potentially evaluated", meaning that there is a
7160 /// possibility that the code will actually be executable. Code in sizeof()
7161 /// expressions, code used only during overload resolution, etc., are not
7162 /// potentially evaluated. This routine will suppress such diagnostics or,
7163 /// in the absolutely nutty case of potentially potentially evaluated
7164 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
7167 /// This routine should be used for all diagnostics that describe the run-time
7168 /// behavior of a program, such as passing a non-POD value through an ellipsis.
7169 /// Failure to do so will likely result in spurious diagnostics or failures
7170 /// during overload resolution or within sizeof/alignof/typeof/typeid.
7171 bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
7172 const PartialDiagnostic &PD) {
7173 switch (ExprEvalContexts.back().Context ) {
7175 // The argument will never be evaluated, so don't complain.
7178 case PotentiallyEvaluated:
7182 case PotentiallyPotentiallyEvaluated:
7183 ExprEvalContexts.back().addDiagnostic(Loc, PD);
7190 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7191 CallExpr *CE, FunctionDecl *FD) {
7192 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7195 PartialDiagnostic Note =
7196 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7197 << FD->getDeclName() : PDiag();
7198 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7200 if (RequireCompleteType(Loc, ReturnType,
7202 PDiag(diag::err_call_function_incomplete_return)
7203 << CE->getSourceRange() << FD->getDeclName() :
7204 PDiag(diag::err_call_incomplete_return)
7205 << CE->getSourceRange(),
7206 std::make_pair(NoteLoc, Note)))
7212 // Diagnose the common s/=/==/ typo. Note that adding parentheses
7213 // will prevent this condition from triggering, which is what we want.
7214 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7217 unsigned diagnostic = diag::warn_condition_is_assignment;
7219 if (isa<BinaryOperator>(E)) {
7220 BinaryOperator *Op = cast<BinaryOperator>(E);
7221 if (Op->getOpcode() != BinaryOperator::Assign)
7224 // Greylist some idioms by putting them into a warning subcategory.
7225 if (ObjCMessageExpr *ME
7226 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7227 Selector Sel = ME->getSelector();
7229 // self = [<foo> init...]
7230 if (isSelfExpr(Op->getLHS())
7231 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7232 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7234 // <foo> = [<bar> nextObject]
7235 else if (Sel.isUnarySelector() &&
7236 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7237 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7240 Loc = Op->getOperatorLoc();
7241 } else if (isa<CXXOperatorCallExpr>(E)) {
7242 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7243 if (Op->getOperator() != OO_Equal)
7246 Loc = Op->getOperatorLoc();
7248 // Not an assignment.
7252 SourceLocation Open = E->getSourceRange().getBegin();
7253 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
7255 Diag(Loc, diagnostic)
7256 << E->getSourceRange()
7257 << CodeModificationHint::CreateInsertion(Open, "(")
7258 << CodeModificationHint::CreateInsertion(Close, ")");
7261 bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7262 DiagnoseAssignmentAsCondition(E);
7264 if (!E->isTypeDependent()) {
7265 DefaultFunctionArrayConversion(E);
7267 QualType T = E->getType();
7269 if (getLangOptions().CPlusPlus) {
7270 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7272 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7273 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7274 << T << E->getSourceRange();