blob: b3c5c9fc20bc925113cab5dab430c8315680f224 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000018#include "clang/AST/DeclTemplate.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000019#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000020#include "clang/AST/ExprObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000021#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000022#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000023#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000024#include "clang/Lex/LiteralSupport.h"
25#include "clang/Lex/Preprocessor.h"
Steve Naroffc540d662008-09-03 18:15:37 +000026#include "clang/Parse/DeclSpec.h"
Chris Lattner07d754a2008-10-26 23:43:26 +000027#include "clang/Parse/Designator.h"
Steve Naroffc540d662008-09-03 18:15:37 +000028#include "clang/Parse/Scope.h"
Douglas Gregorb53edfb2009-11-10 19:49:08 +000029#include "clang/Parse/Template.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000030using namespace clang;
31
David Chisnall9f57c292009-08-17 16:35:33 +000032
Douglas Gregor171c45a2009-02-18 21:56:37 +000033/// \brief Determine whether the use of this declaration is valid, and
34/// emit any corresponding diagnostics.
35///
36/// This routine diagnoses various problems with referencing
37/// declarations that can occur when using a declaration. For example,
38/// it might warn if a deprecated or unavailable declaration is being
39/// used, or produce an error (and return true) if a C++0x deleted
40/// function is being used.
41///
Chris Lattnerb7df3c62009-10-25 22:31:57 +000042/// If IgnoreDeprecated is set to true, this should not want about deprecated
43/// decls.
44///
Douglas Gregor171c45a2009-02-18 21:56:37 +000045/// \returns true if there was an error (this declaration cannot be
46/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +000047///
John McCall28a6aea2009-11-04 02:18:39 +000048bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000049 // See if the decl is deprecated.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000050 if (D->getAttr<DeprecatedAttr>()) {
John McCall28a6aea2009-11-04 02:18:39 +000051 EmitDeprecationWarning(D, Loc);
Chris Lattner4bf74fd2009-02-15 22:43:40 +000052 }
53
Chris Lattnera27dd592009-10-25 17:21:40 +000054 // See if the decl is unavailable
55 if (D->getAttr<UnavailableAttr>()) {
56 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
57 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
58 }
59
Douglas Gregor171c45a2009-02-18 21:56:37 +000060 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000061 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000062 if (FD->isDeleted()) {
63 Diag(Loc, diag::err_deleted_function_use);
64 Diag(D->getLocation(), diag::note_unavailable_here) << true;
65 return true;
66 }
Douglas Gregorde681d42009-02-24 04:26:15 +000067 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000068
Douglas Gregor171c45a2009-02-18 21:56:37 +000069 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +000070}
71
Fariborz Jahanian027b8862009-05-13 18:09:35 +000072/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +000073/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +000074/// attribute. It warns if call does not have the sentinel argument.
75///
76void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +000077 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000078 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000079 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +000080 return;
Fariborz Jahanian9e877212009-05-13 23:20:50 +000081 int sentinelPos = attr->getSentinel();
82 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +000083
Mike Stump87c57ac2009-05-16 07:39:55 +000084 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
85 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +000086 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +000087 bool warnNotEnoughArgs = false;
88 int isMethod = 0;
89 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
90 // skip over named parameters.
91 ObjCMethodDecl::param_iterator P, E = MD->param_end();
92 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
93 if (nullPos)
94 --nullPos;
95 else
96 ++i;
97 }
98 warnNotEnoughArgs = (P != E || i >= NumArgs);
99 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000100 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000101 // skip over named parameters.
102 ObjCMethodDecl::param_iterator P, E = FD->param_end();
103 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
104 if (nullPos)
105 --nullPos;
106 else
107 ++i;
108 }
109 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000110 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000111 // block or function pointer call.
112 QualType Ty = V->getType();
113 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000114 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000115 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
116 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000117 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
118 unsigned NumArgsInProto = Proto->getNumArgs();
119 unsigned k;
120 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
121 if (nullPos)
122 --nullPos;
123 else
124 ++i;
125 }
126 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
127 }
128 if (Ty->isBlockPointerType())
129 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000130 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000131 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000132 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000133 return;
134
135 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000136 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000137 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000138 return;
139 }
140 int sentinel = i;
141 while (sentinelPos > 0 && i < NumArgs-1) {
142 --sentinelPos;
143 ++i;
144 }
145 if (sentinelPos > 0) {
146 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000147 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000148 return;
149 }
150 while (i < NumArgs-1) {
151 ++i;
152 ++sentinel;
153 }
154 Expr *sentinelExpr = Args[sentinel];
Anders Carlsson0b11a3e2009-11-24 17:24:21 +0000155 if (sentinelExpr && (!isa<GNUNullExpr>(sentinelExpr) &&
156 (!sentinelExpr->getType()->isPointerType() ||
157 !sentinelExpr->isNullPointerConstant(Context,
158 Expr::NPC_ValueDependentIsNull)))) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000159 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000160 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000161 }
162 return;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000163}
164
Douglas Gregor87f95b02009-02-26 21:00:50 +0000165SourceRange Sema::getExprRange(ExprTy *E) const {
166 Expr *Ex = (Expr *)E;
167 return Ex? Ex->getSourceRange() : SourceRange();
168}
169
Chris Lattner513165e2008-07-25 21:10:04 +0000170//===----------------------------------------------------------------------===//
171// Standard Promotions and Conversions
172//===----------------------------------------------------------------------===//
173
Chris Lattner513165e2008-07-25 21:10:04 +0000174/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
175void Sema::DefaultFunctionArrayConversion(Expr *&E) {
176 QualType Ty = E->getType();
177 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
178
Chris Lattner513165e2008-07-25 21:10:04 +0000179 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000180 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlsson6904f642009-09-01 20:37:18 +0000181 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000182 else if (Ty->isArrayType()) {
183 // In C90 mode, arrays only promote to pointers if the array expression is
184 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
185 // type 'array of type' is converted to an expression that has type 'pointer
186 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
187 // that has type 'array of type' ...". The relevant change is "an lvalue"
188 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000189 //
190 // C++ 4.2p1:
191 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
192 // T" can be converted to an rvalue of type "pointer to T".
193 //
194 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
195 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000196 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
197 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000198 }
Chris Lattner513165e2008-07-25 21:10:04 +0000199}
200
201/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000202/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000203/// sometimes surpressed. For example, the array->pointer conversion doesn't
204/// apply if the array is an argument to the sizeof or address (&) operators.
205/// In these instances, this routine should *not* be called.
206Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
207 QualType Ty = Expr->getType();
208 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000209
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000210 // C99 6.3.1.1p2:
211 //
212 // The following may be used in an expression wherever an int or
213 // unsigned int may be used:
214 // - an object or expression with an integer type whose integer
215 // conversion rank is less than or equal to the rank of int
216 // and unsigned int.
217 // - A bit-field of type _Bool, int, signed int, or unsigned int.
218 //
219 // If an int can represent all values of the original type, the
220 // value is converted to an int; otherwise, it is converted to an
221 // unsigned int. These are called the integer promotions. All
222 // other types are unchanged by the integer promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000223 QualType PTy = Context.isPromotableBitField(Expr);
224 if (!PTy.isNull()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +0000225 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman629ffb92009-08-20 04:21:42 +0000226 return Expr;
227 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000228 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000229 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman06ed2a52009-10-20 08:27:19 +0000230 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000231 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000232 }
233
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000234 DefaultFunctionArrayConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000235 return Expr;
236}
237
Chris Lattner2ce500f2008-07-25 22:25:12 +0000238/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000239/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000240/// double. All other argument types are converted by UsualUnaryConversions().
241void Sema::DefaultArgumentPromotion(Expr *&Expr) {
242 QualType Ty = Expr->getType();
243 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000244
Chris Lattner2ce500f2008-07-25 22:25:12 +0000245 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall9dd450b2009-09-21 23:43:11 +0000246 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner2ce500f2008-07-25 22:25:12 +0000247 if (BT->getKind() == BuiltinType::Float)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000248 return ImpCastExprToType(Expr, Context.DoubleTy,
249 CastExpr::CK_FloatingCast);
Mike Stump11289f42009-09-09 15:08:12 +0000250
Chris Lattner2ce500f2008-07-25 22:25:12 +0000251 UsualUnaryConversions(Expr);
252}
253
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000254/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
255/// will warn if the resulting type is not a POD type, and rejects ObjC
256/// interfaces passed by value. This returns true if the argument type is
257/// completely illegal.
258bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000259 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000260
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000261 if (Expr->getType()->isObjCInterfaceType()) {
262 Diag(Expr->getLocStart(),
263 diag::err_cannot_pass_objc_interface_to_vararg)
264 << Expr->getType() << CT;
265 return true;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000266 }
Mike Stump11289f42009-09-09 15:08:12 +0000267
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000268 if (!Expr->getType()->isPODType())
269 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
270 << Expr->getType() << CT;
271
272 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000273}
274
275
Chris Lattner513165e2008-07-25 21:10:04 +0000276/// UsualArithmeticConversions - Performs various conversions that are common to
277/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000278/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000279/// responsible for emitting appropriate error diagnostics.
280/// FIXME: verify the conversion rules for "complex int" are consistent with
281/// GCC.
282QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
283 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000284 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000285 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000286
287 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000288
Mike Stump11289f42009-09-09 15:08:12 +0000289 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000290 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000291 QualType lhs =
292 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000293 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000294 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000295
296 // If both types are identical, no conversion is needed.
297 if (lhs == rhs)
298 return lhs;
299
300 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
301 // The caller can deal with this (e.g. pointer + int).
302 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
303 return lhs;
304
Douglas Gregord2c2d172009-05-02 00:36:19 +0000305 // Perform bitfield promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000306 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000307 if (!LHSBitfieldPromoteTy.isNull())
308 lhs = LHSBitfieldPromoteTy;
Eli Friedman629ffb92009-08-20 04:21:42 +0000309 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000310 if (!RHSBitfieldPromoteTy.isNull())
311 rhs = RHSBitfieldPromoteTy;
312
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000313 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000314 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000315 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
316 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregora11693b2008-11-12 17:17:38 +0000317 return destType;
318}
319
Chris Lattner513165e2008-07-25 21:10:04 +0000320//===----------------------------------------------------------------------===//
321// Semantic Analysis for various Expression Types
322//===----------------------------------------------------------------------===//
323
324
Steve Naroff83895f72007-09-16 03:34:24 +0000325/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000326/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
327/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
328/// multiple tokens. However, the common case is that StringToks points to one
329/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000330///
331Action::OwningExprResult
Steve Naroff83895f72007-09-16 03:34:24 +0000332Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000333 assert(NumStringToks && "Must have at least one string!");
334
Chris Lattner8a24e582009-01-16 18:51:42 +0000335 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000336 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000337 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000338
Chris Lattner23b7eb62007-06-15 23:05:46 +0000339 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000340 for (unsigned i = 0; i != NumStringToks; ++i)
341 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000342
Chris Lattner36fc8792008-02-11 00:02:17 +0000343 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000344 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000345 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000346
347 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
348 if (getLangOptions().CPlusPlus)
349 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000350
Chris Lattner36fc8792008-02-11 00:02:17 +0000351 // Get an array type for the string, according to C99 6.4.5. This includes
352 // the nul terminator character as well as the string length for pascal
353 // strings.
354 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000355 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000356 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000357
Chris Lattner5b183d82006-11-10 05:03:26 +0000358 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump11289f42009-09-09 15:08:12 +0000359 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000360 Literal.GetStringLength(),
361 Literal.AnyWide, StrTy,
362 &StringTokLocs[0],
363 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000364}
365
Chris Lattner2a9d9892008-10-20 05:16:36 +0000366/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
367/// CurBlock to VD should cause it to be snapshotted (as we do for auto
368/// variables defined outside the block) or false if this is not needed (e.g.
369/// for values inside the block or for globals).
370///
Chris Lattner497d7b02009-04-21 22:26:47 +0000371/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
372/// up-to-date.
373///
Chris Lattner2a9d9892008-10-20 05:16:36 +0000374static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
375 ValueDecl *VD) {
376 // If the value is defined inside the block, we couldn't snapshot it even if
377 // we wanted to.
378 if (CurBlock->TheDecl == VD->getDeclContext())
379 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000380
Chris Lattner2a9d9892008-10-20 05:16:36 +0000381 // If this is an enum constant or function, it is constant, don't snapshot.
382 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
383 return false;
384
385 // If this is a reference to an extern, static, or global variable, no need to
386 // snapshot it.
387 // FIXME: What about 'const' variables in C++?
388 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000389 if (!Var->hasLocalStorage())
390 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000391
Chris Lattner497d7b02009-04-21 22:26:47 +0000392 // Blocks that have these can't be constant.
393 CurBlock->hasBlockDeclRefExprs = true;
394
395 // If we have nested blocks, the decl may be declared in an outer block (in
396 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
397 // be defined outside all of the current blocks (in which case the blocks do
398 // all get the bit). Walk the nesting chain.
399 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
400 NextBlock = NextBlock->PrevBlockInfo) {
401 // If we found the defining block for the variable, don't mark the block as
402 // having a reference outside it.
403 if (NextBlock->TheDecl == VD->getDeclContext())
404 break;
Mike Stump11289f42009-09-09 15:08:12 +0000405
Chris Lattner497d7b02009-04-21 22:26:47 +0000406 // Otherwise, the DeclRef from the inner block causes the outer one to need
407 // a snapshot as well.
408 NextBlock->hasBlockDeclRefExprs = true;
409 }
Mike Stump11289f42009-09-09 15:08:12 +0000410
Chris Lattner2a9d9892008-10-20 05:16:36 +0000411 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000412}
413
Chris Lattner2a9d9892008-10-20 05:16:36 +0000414
415
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000416/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlsson946b86d2009-06-24 00:10:43 +0000417Sema::OwningExprResult
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000418Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000419 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000420 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
421 Diag(Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000422 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000423 << D->getDeclName();
424 return ExprError();
425 }
Mike Stump11289f42009-09-09 15:08:12 +0000426
Anders Carlsson946b86d2009-06-24 00:10:43 +0000427 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
428 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
429 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
430 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump11289f42009-09-09 15:08:12 +0000431 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000432 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000433 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000434 << D->getIdentifier();
435 return ExprError();
436 }
437 }
438 }
439 }
Mike Stump11289f42009-09-09 15:08:12 +0000440
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000441 MarkDeclarationReferenced(Loc, D);
Mike Stump11289f42009-09-09 15:08:12 +0000442
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000443 return Owned(DeclRefExpr::Create(Context,
444 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
445 SS? SS->getRange() : SourceRange(),
Douglas Gregored6c7442009-11-23 11:41:28 +0000446 D, Loc, Ty));
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000447}
448
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000449/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
450/// variable corresponding to the anonymous union or struct whose type
451/// is Record.
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000452static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
453 RecordDecl *Record) {
Mike Stump11289f42009-09-09 15:08:12 +0000454 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000455 "Record must be an anonymous struct or union!");
Mike Stump11289f42009-09-09 15:08:12 +0000456
Mike Stump87c57ac2009-05-16 07:39:55 +0000457 // FIXME: Once Decls are directly linked together, this will be an O(1)
458 // operation rather than a slow walk through DeclContext's vector (which
459 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000460 DeclContext *Ctx = Record->getDeclContext();
Mike Stump11289f42009-09-09 15:08:12 +0000461 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000462 DEnd = Ctx->decls_end();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000463 D != DEnd; ++D) {
464 if (*D == Record) {
465 // The object for the anonymous struct/union directly
466 // follows its type in the list of declarations.
467 ++D;
468 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000469 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000470 return *D;
471 }
472 }
473
474 assert(false && "Missing object for anonymous record");
475 return 0;
476}
477
Douglas Gregord5846a12009-04-15 06:41:24 +0000478/// \brief Given a field that represents a member of an anonymous
479/// struct/union, build the path from that field's context to the
480/// actual member.
481///
482/// Construct the sequence of field member references we'll have to
483/// perform to get to the field in the anonymous union/struct. The
484/// list of members is built from the field outward, so traverse it
485/// backwards to go from an object in the current context to the field
486/// we found.
487///
488/// \returns The variable from which the field access should begin,
489/// for an anonymous struct/union that is not a member of another
490/// class. Otherwise, returns NULL.
491VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
492 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000493 assert(Field->getDeclContext()->isRecord() &&
494 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
495 && "Field must be stored inside an anonymous struct or union");
496
Douglas Gregord5846a12009-04-15 06:41:24 +0000497 Path.push_back(Field);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000498 VarDecl *BaseObject = 0;
499 DeclContext *Ctx = Field->getDeclContext();
500 do {
501 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000502 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000503 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregord5846a12009-04-15 06:41:24 +0000504 Path.push_back(AnonField);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000505 else {
506 BaseObject = cast<VarDecl>(AnonObject);
507 break;
508 }
509 Ctx = Ctx->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000510 } while (Ctx->isRecord() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000511 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregord5846a12009-04-15 06:41:24 +0000512
513 return BaseObject;
514}
515
516Sema::OwningExprResult
517Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
518 FieldDecl *Field,
519 Expr *BaseObjectExpr,
520 SourceLocation OpLoc) {
521 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump11289f42009-09-09 15:08:12 +0000522 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregord5846a12009-04-15 06:41:24 +0000523 AnonFields);
524
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000525 // Build the expression that refers to the base object, from
526 // which we will build a sequence of member references to each
527 // of the anonymous union objects and, eventually, the field we
528 // found via name lookup.
529 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000530 Qualifiers BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000531 if (BaseObject) {
532 // BaseObject is an anonymous struct/union variable (and is,
533 // therefore, not part of another non-anonymous record).
Ted Kremenek5a201952009-02-07 01:47:29 +0000534 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000535 MarkDeclarationReferenced(Loc, BaseObject);
Steve Narofff6009ed2009-01-21 00:14:39 +0000536 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000537 SourceLocation());
John McCall8ccfcb52009-09-24 19:53:00 +0000538 BaseQuals
539 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000540 } else if (BaseObjectExpr) {
541 // The caller provided the base object expression. Determine
542 // whether its a pointer and whether it adds any qualifiers to the
543 // anonymous struct/union fields we're looking into.
544 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000545 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000546 BaseObjectIsPointer = true;
547 ObjectType = ObjectPtr->getPointeeType();
548 }
John McCall8ccfcb52009-09-24 19:53:00 +0000549 BaseQuals
550 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000551 } else {
552 // We've found a member of an anonymous struct/union that is
553 // inside a non-anonymous struct/union, so in a well-formed
554 // program our base object expression is "this".
555 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
556 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000557 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000558 = Context.getTagDeclType(
559 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
560 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000561 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000562 == Context.getCanonicalType(ThisType)) ||
563 IsDerivedFrom(ThisType, AnonFieldType)) {
564 // Our base object expression is "this".
Steve Narofff6009ed2009-01-21 00:14:39 +0000565 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000566 MD->getThisType(Context));
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000567 BaseObjectIsPointer = true;
568 }
569 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000570 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
571 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000572 }
John McCall8ccfcb52009-09-24 19:53:00 +0000573 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000574 }
575
Mike Stump11289f42009-09-09 15:08:12 +0000576 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000577 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
578 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000579 }
580
581 // Build the implicit member references to the field of the
582 // anonymous struct/union.
583 Expr *Result = BaseObjectExpr;
John McCall8ccfcb52009-09-24 19:53:00 +0000584 Qualifiers ResultQuals = BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000585 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
586 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
587 FI != FIEnd; ++FI) {
588 QualType MemberType = (*FI)->getType();
John McCall8ccfcb52009-09-24 19:53:00 +0000589 Qualifiers MemberTypeQuals =
590 Context.getCanonicalType(MemberType).getQualifiers();
591
592 // CVR attributes from the base are picked up by members,
593 // except that 'mutable' members don't pick up 'const'.
594 if ((*FI)->isMutable())
595 ResultQuals.removeConst();
596
597 // GC attributes are never picked up by members.
598 ResultQuals.removeObjCGCAttr();
599
600 // TR 18037 does not allow fields to be declared with address spaces.
601 assert(!MemberTypeQuals.hasAddressSpace());
602
603 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
604 if (NewQuals != MemberTypeQuals)
605 MemberType = Context.getQualifiedType(MemberType, NewQuals);
606
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000607 MarkDeclarationReferenced(Loc, *FI);
Eli Friedman78cde142009-12-04 07:18:51 +0000608 PerformObjectMemberConversion(Result, *FI);
Douglas Gregorc1905232009-08-26 22:36:53 +0000609 // FIXME: Might this end up being a qualified name?
Steve Narofff6009ed2009-01-21 00:14:39 +0000610 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
611 OpLoc, MemberType);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000612 BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000613 ResultQuals = NewQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000614 }
615
Sebastian Redlffbcf962009-01-18 18:53:16 +0000616 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000617}
618
John McCall10eae182009-11-30 22:42:35 +0000619/// Decomposes the given name into a DeclarationName, its location, and
620/// possibly a list of template arguments.
621///
622/// If this produces template arguments, it is permitted to call
623/// DecomposeTemplateName.
624///
625/// This actually loses a lot of source location information for
626/// non-standard name kinds; we should consider preserving that in
627/// some way.
628static void DecomposeUnqualifiedId(Sema &SemaRef,
629 const UnqualifiedId &Id,
630 TemplateArgumentListInfo &Buffer,
631 DeclarationName &Name,
632 SourceLocation &NameLoc,
633 const TemplateArgumentListInfo *&TemplateArgs) {
634 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
635 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
636 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
637
638 ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
639 Id.TemplateId->getTemplateArgs(),
640 Id.TemplateId->NumArgs);
641 SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
642 TemplateArgsPtr.release();
643
644 TemplateName TName =
645 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
646
647 Name = SemaRef.Context.getNameForTemplate(TName);
648 NameLoc = Id.TemplateId->TemplateNameLoc;
649 TemplateArgs = &Buffer;
650 } else {
651 Name = SemaRef.GetNameFromUnqualifiedId(Id);
652 NameLoc = Id.StartLocation;
653 TemplateArgs = 0;
654 }
655}
656
657/// Decompose the given template name into a list of lookup results.
658///
659/// The unqualified ID must name a non-dependent template, which can
660/// be more easily tested by checking whether DecomposeUnqualifiedId
661/// found template arguments.
662static void DecomposeTemplateName(LookupResult &R, const UnqualifiedId &Id) {
663 assert(Id.getKind() == UnqualifiedId::IK_TemplateId);
664 TemplateName TName =
665 Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
666
John McCalle66edc12009-11-24 19:00:30 +0000667 if (TemplateDecl *TD = TName.getAsTemplateDecl())
668 R.addDecl(TD);
John McCalld28ae272009-12-02 08:04:21 +0000669 else if (OverloadedTemplateStorage *OT = TName.getAsOverloadedTemplate())
670 for (OverloadedTemplateStorage::iterator I = OT->begin(), E = OT->end();
671 I != E; ++I)
John McCalle66edc12009-11-24 19:00:30 +0000672 R.addDecl(*I);
John McCalla9ee3252009-11-22 02:49:43 +0000673
John McCalle66edc12009-11-24 19:00:30 +0000674 R.resolveKind();
Douglas Gregora121b752009-11-03 16:56:39 +0000675}
676
John McCall10eae182009-11-30 22:42:35 +0000677static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
678 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
679 E = Record->bases_end(); I != E; ++I) {
680 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
681 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
682 if (!BaseRT) return false;
683
684 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
685 if (!BaseRecord->isDefinition() ||
686 !IsFullyFormedScope(SemaRef, BaseRecord))
687 return false;
688 }
689
690 return true;
691}
692
John McCallf786fb12009-11-30 23:50:49 +0000693/// Determines whether we can lookup this id-expression now or whether
694/// we have to wait until template instantiation is complete.
695static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
John McCall10eae182009-11-30 22:42:35 +0000696 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
John McCall10eae182009-11-30 22:42:35 +0000697
John McCallf786fb12009-11-30 23:50:49 +0000698 // If the qualifier scope isn't computable, it's definitely dependent.
699 if (!DC) return true;
700
701 // If the qualifier scope doesn't name a record, we can always look into it.
702 if (!isa<CXXRecordDecl>(DC)) return false;
703
704 // We can't look into record types unless they're fully-formed.
705 if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
706
John McCall2d74de92009-12-01 22:10:20 +0000707 return false;
708}
John McCallf786fb12009-11-30 23:50:49 +0000709
John McCall2d74de92009-12-01 22:10:20 +0000710/// Determines if the given class is provably not derived from all of
711/// the prospective base classes.
712static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
713 CXXRecordDecl *Record,
714 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
John McCalla6d407c2009-12-01 22:28:41 +0000715 if (Bases.count(Record->getCanonicalDecl()))
John McCall2d74de92009-12-01 22:10:20 +0000716 return false;
717
John McCalla6d407c2009-12-01 22:28:41 +0000718 RecordDecl *RD = Record->getDefinition(SemaRef.Context);
719 if (!RD) return false;
720 Record = cast<CXXRecordDecl>(RD);
721
John McCall2d74de92009-12-01 22:10:20 +0000722 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
723 E = Record->bases_end(); I != E; ++I) {
724 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
725 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
726 if (!BaseRT) return false;
727
728 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall2d74de92009-12-01 22:10:20 +0000729 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
730 return false;
731 }
732
733 return true;
734}
735
John McCall5af04502009-12-02 20:26:00 +0000736/// Determines if this a C++ class member.
737static bool IsClassMember(NamedDecl *D) {
738 DeclContext *DC = D->getDeclContext();
John McCall1a49e9d2009-12-02 19:59:55 +0000739
John McCall5af04502009-12-02 20:26:00 +0000740 // C++0x [class.mem]p1:
741 // The enumerators of an unscoped enumeration defined in
742 // the class are members of the class.
743 // FIXME: support C++0x scoped enumerations.
744 if (isa<EnumDecl>(DC))
745 DC = DC->getParent();
746
747 return DC->isRecord();
748}
749
750/// Determines if this is an instance member of a class.
751static bool IsInstanceMember(NamedDecl *D) {
752 assert(IsClassMember(D) &&
John McCall2d74de92009-12-01 22:10:20 +0000753 "checking whether non-member is instance member");
754
755 if (isa<FieldDecl>(D)) return true;
756
757 if (isa<CXXMethodDecl>(D))
758 return !cast<CXXMethodDecl>(D)->isStatic();
759
760 if (isa<FunctionTemplateDecl>(D)) {
761 D = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
762 return !cast<CXXMethodDecl>(D)->isStatic();
763 }
764
765 return false;
766}
767
768enum IMAKind {
769 /// The reference is definitely not an instance member access.
770 IMA_Static,
771
772 /// The reference may be an implicit instance member access.
773 IMA_Mixed,
774
775 /// The reference may be to an instance member, but it is invalid if
776 /// so, because the context is not an instance method.
777 IMA_Mixed_StaticContext,
778
779 /// The reference may be to an instance member, but it is invalid if
780 /// so, because the context is from an unrelated class.
781 IMA_Mixed_Unrelated,
782
783 /// The reference is definitely an implicit instance member access.
784 IMA_Instance,
785
786 /// The reference may be to an unresolved using declaration.
787 IMA_Unresolved,
788
789 /// The reference may be to an unresolved using declaration and the
790 /// context is not an instance method.
791 IMA_Unresolved_StaticContext,
792
793 /// The reference is to a member of an anonymous structure in a
794 /// non-class context.
795 IMA_AnonymousMember,
796
797 /// All possible referrents are instance members and the current
798 /// context is not an instance method.
799 IMA_Error_StaticContext,
800
801 /// All possible referrents are instance members of an unrelated
802 /// class.
803 IMA_Error_Unrelated
804};
805
806/// The given lookup names class member(s) and is not being used for
807/// an address-of-member expression. Classify the type of access
808/// according to whether it's possible that this reference names an
809/// instance member. This is best-effort; it is okay to
810/// conservatively answer "yes", in which case some errors will simply
811/// not be caught until template-instantiation.
812static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
813 const LookupResult &R) {
John McCall5af04502009-12-02 20:26:00 +0000814 assert(!R.empty() && IsClassMember(*R.begin()));
John McCall2d74de92009-12-01 22:10:20 +0000815
816 bool isStaticContext =
817 (!isa<CXXMethodDecl>(SemaRef.CurContext) ||
818 cast<CXXMethodDecl>(SemaRef.CurContext)->isStatic());
819
820 if (R.isUnresolvableResult())
821 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
822
823 // Collect all the declaring classes of instance members we find.
824 bool hasNonInstance = false;
825 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
826 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
827 NamedDecl *D = (*I)->getUnderlyingDecl();
828 if (IsInstanceMember(D)) {
829 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
830
831 // If this is a member of an anonymous record, move out to the
832 // innermost non-anonymous struct or union. If there isn't one,
833 // that's a special case.
834 while (R->isAnonymousStructOrUnion()) {
835 R = dyn_cast<CXXRecordDecl>(R->getParent());
836 if (!R) return IMA_AnonymousMember;
837 }
838 Classes.insert(R->getCanonicalDecl());
839 }
840 else
841 hasNonInstance = true;
842 }
843
844 // If we didn't find any instance members, it can't be an implicit
845 // member reference.
846 if (Classes.empty())
847 return IMA_Static;
848
849 // If the current context is not an instance method, it can't be
850 // an implicit member reference.
851 if (isStaticContext)
852 return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
853
854 // If we can prove that the current context is unrelated to all the
855 // declaring classes, it can't be an implicit member reference (in
856 // which case it's an error if any of those members are selected).
857 if (IsProvablyNotDerivedFrom(SemaRef,
858 cast<CXXMethodDecl>(SemaRef.CurContext)->getParent(),
859 Classes))
860 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
861
862 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
863}
864
865/// Diagnose a reference to a field with no object available.
866static void DiagnoseInstanceReference(Sema &SemaRef,
867 const CXXScopeSpec &SS,
868 const LookupResult &R) {
869 SourceLocation Loc = R.getNameLoc();
870 SourceRange Range(Loc);
871 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
872
873 if (R.getAsSingle<FieldDecl>()) {
874 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
875 if (MD->isStatic()) {
876 // "invalid use of member 'x' in static member function"
877 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
878 << Range << R.getLookupName();
879 return;
880 }
881 }
882
883 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
884 << R.getLookupName() << Range;
885 return;
886 }
887
888 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
John McCall10eae182009-11-30 22:42:35 +0000889}
890
John McCalle66edc12009-11-24 19:00:30 +0000891Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
892 const CXXScopeSpec &SS,
893 UnqualifiedId &Id,
894 bool HasTrailingLParen,
895 bool isAddressOfOperand) {
896 assert(!(isAddressOfOperand && HasTrailingLParen) &&
897 "cannot be direct & operand and have a trailing lparen");
898
899 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +0000900 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +0000901
John McCall10eae182009-11-30 22:42:35 +0000902 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +0000903
904 // Decompose the UnqualifiedId into the following data.
905 DeclarationName Name;
906 SourceLocation NameLoc;
907 const TemplateArgumentListInfo *TemplateArgs;
John McCall10eae182009-11-30 22:42:35 +0000908 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
909 Name, NameLoc, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +0000910
Douglas Gregor4ea80432008-11-18 15:03:34 +0000911 IdentifierInfo *II = Name.getAsIdentifierInfo();
John McCalld14a8642009-11-21 08:51:07 +0000912
John McCalle66edc12009-11-24 19:00:30 +0000913 // C++ [temp.dep.expr]p3:
914 // An id-expression is type-dependent if it contains:
915 // -- a nested-name-specifier that contains a class-name that
916 // names a dependent type.
917 // Determine whether this is a member of an unknown specialization;
918 // we need to handle these differently.
John McCallf786fb12009-11-30 23:50:49 +0000919 if (SS.isSet() && IsDependentIdExpression(*this, SS)) {
John McCalle66edc12009-11-24 19:00:30 +0000920 return ActOnDependentIdExpression(SS, Name, NameLoc,
John McCallcd4b4772009-12-02 03:53:29 +0000921 isAddressOfOperand,
John McCalle66edc12009-11-24 19:00:30 +0000922 TemplateArgs);
923 }
John McCalld14a8642009-11-21 08:51:07 +0000924
John McCalle66edc12009-11-24 19:00:30 +0000925 // Perform the required lookup.
926 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
927 if (TemplateArgs) {
John McCalle66edc12009-11-24 19:00:30 +0000928 // Just re-use the lookup done by isTemplateName.
John McCall10eae182009-11-30 22:42:35 +0000929 DecomposeTemplateName(R, Id);
John McCalle66edc12009-11-24 19:00:30 +0000930 } else {
931 LookupParsedName(R, S, &SS, true);
Mike Stump11289f42009-09-09 15:08:12 +0000932
John McCalle66edc12009-11-24 19:00:30 +0000933 // If this reference is in an Objective-C method, then we need to do
934 // some special Objective-C lookup, too.
935 if (!SS.isSet() && II && getCurMethodDecl()) {
936 OwningExprResult E(LookupInObjCMethod(R, S, II));
937 if (E.isInvalid())
938 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000939
John McCalle66edc12009-11-24 19:00:30 +0000940 Expr *Ex = E.takeAs<Expr>();
941 if (Ex) return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +0000942 }
Chris Lattner59a25942008-03-31 00:36:02 +0000943 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +0000944
John McCalle66edc12009-11-24 19:00:30 +0000945 if (R.isAmbiguous())
946 return ExprError();
947
Douglas Gregor171c45a2009-02-18 21:56:37 +0000948 // Determine whether this name might be a candidate for
949 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +0000950 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000951
John McCalle66edc12009-11-24 19:00:30 +0000952 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +0000953 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +0000954 // in C90, extension in C99, forbidden in C++).
955 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
956 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
957 if (D) R.addDecl(D);
958 }
959
960 // If this name wasn't predeclared and if this is not a function
961 // call, diagnose the problem.
962 if (R.empty()) {
963 if (!SS.isEmpty())
964 return ExprError(Diag(NameLoc, diag::err_no_member)
965 << Name << computeDeclContext(SS, false)
966 << SS.getRange());
Douglas Gregore40876a2009-10-13 21:16:44 +0000967 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Alexis Hunt3d221f22009-11-29 07:34:05 +0000968 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor4ea80432008-11-18 15:03:34 +0000969 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
John McCalle66edc12009-11-24 19:00:30 +0000970 return ExprError(Diag(NameLoc, diag::err_undeclared_use)
971 << Name);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000972 else
John McCalle66edc12009-11-24 19:00:30 +0000973 return ExprError(Diag(NameLoc, diag::err_undeclared_var_use) << Name);
Steve Naroff92e30f82007-04-02 22:35:25 +0000974 }
Chris Lattner17ed4872006-11-20 04:58:19 +0000975 }
Mike Stump11289f42009-09-09 15:08:12 +0000976
John McCalle66edc12009-11-24 19:00:30 +0000977 // This is guaranteed from this point on.
978 assert(!R.empty() || ADL);
979
980 if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +0000981 // Warn about constructs like:
982 // if (void *X = foo()) { ... } else { X }.
983 // In the else block, the pointer is always false.
Mike Stump11289f42009-09-09 15:08:12 +0000984
Douglas Gregor3256d042009-06-30 15:47:41 +0000985 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
986 Scope *CheckS = S;
Douglas Gregor13a2c032009-11-05 17:49:26 +0000987 while (CheckS && CheckS->getControlParent()) {
Mike Stump11289f42009-09-09 15:08:12 +0000988 if (CheckS->isWithinElse() &&
Douglas Gregor3256d042009-06-30 15:47:41 +0000989 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
John McCalle66edc12009-11-24 19:00:30 +0000990 ExprError(Diag(NameLoc, diag::warn_value_always_zero)
Douglas Gregor13a2c032009-11-05 17:49:26 +0000991 << Var->getDeclName()
992 << (Var->getType()->isPointerType()? 2 :
993 Var->getType()->isBooleanType()? 1 : 0));
Douglas Gregor3256d042009-06-30 15:47:41 +0000994 break;
995 }
Mike Stump11289f42009-09-09 15:08:12 +0000996
Douglas Gregor13a2c032009-11-05 17:49:26 +0000997 // Move to the parent of this scope.
998 CheckS = CheckS->getParent();
Douglas Gregor3256d042009-06-30 15:47:41 +0000999 }
1000 }
John McCalle66edc12009-11-24 19:00:30 +00001001 } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
Douglas Gregor3256d042009-06-30 15:47:41 +00001002 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1003 // C99 DR 316 says that, if a function type comes from a
1004 // function definition (without a prototype), that type is only
1005 // used for checking compatibility. Therefore, when referencing
1006 // the function, we pretend that we don't have the full function
1007 // type.
John McCalle66edc12009-11-24 19:00:30 +00001008 if (DiagnoseUseOfDecl(Func, NameLoc))
Douglas Gregor3256d042009-06-30 15:47:41 +00001009 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001010
Douglas Gregor3256d042009-06-30 15:47:41 +00001011 QualType T = Func->getType();
1012 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +00001013 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor3256d042009-06-30 15:47:41 +00001014 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
John McCalle66edc12009-11-24 19:00:30 +00001015 return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
Douglas Gregor3256d042009-06-30 15:47:41 +00001016 }
1017 }
Mike Stump11289f42009-09-09 15:08:12 +00001018
John McCall2d74de92009-12-01 22:10:20 +00001019 // Check whether this might be a C++ implicit instance member access.
1020 // C++ [expr.prim.general]p6:
1021 // Within the definition of a non-static member function, an
1022 // identifier that names a non-static member is transformed to a
1023 // class member access expression.
1024 // But note that &SomeClass::foo is grammatically distinct, even
1025 // though we don't parse it that way.
John McCall5af04502009-12-02 20:26:00 +00001026 if (!R.empty() && IsClassMember(*R.begin())) {
John McCalle66edc12009-11-24 19:00:30 +00001027 bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
John McCallb53bbd42009-11-22 01:44:31 +00001028
John McCall2d74de92009-12-01 22:10:20 +00001029 if (!isAbstractMemberPointer) {
1030 switch (ClassifyImplicitMemberAccess(*this, R)) {
1031 case IMA_Instance:
1032 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1033
1034 case IMA_AnonymousMember:
1035 assert(R.isSingleResult());
1036 return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1037 R.getAsSingle<FieldDecl>());
1038
1039 case IMA_Mixed:
1040 case IMA_Mixed_Unrelated:
1041 case IMA_Unresolved:
1042 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1043
1044 case IMA_Static:
1045 case IMA_Mixed_StaticContext:
1046 case IMA_Unresolved_StaticContext:
1047 break;
1048
1049 case IMA_Error_StaticContext:
1050 case IMA_Error_Unrelated:
1051 DiagnoseInstanceReference(*this, SS, R);
1052 return ExprError();
1053 }
John McCallb53bbd42009-11-22 01:44:31 +00001054 }
1055 }
1056
John McCalle66edc12009-11-24 19:00:30 +00001057 if (TemplateArgs)
1058 return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001059
John McCalle66edc12009-11-24 19:00:30 +00001060 return BuildDeclarationNameExpr(SS, R, ADL);
1061}
1062
John McCall10eae182009-11-30 22:42:35 +00001063/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1064/// declaration name, generally during template instantiation.
1065/// There's a large number of things which don't need to be done along
1066/// this path.
John McCalle66edc12009-11-24 19:00:30 +00001067Sema::OwningExprResult
1068Sema::BuildQualifiedDeclarationNameExpr(const CXXScopeSpec &SS,
1069 DeclarationName Name,
1070 SourceLocation NameLoc) {
1071 DeclContext *DC;
1072 if (!(DC = computeDeclContext(SS, false)) ||
1073 DC->isDependentContext() ||
1074 RequireCompleteDeclContext(SS))
1075 return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1076
1077 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1078 LookupQualifiedName(R, DC);
1079
1080 if (R.isAmbiguous())
1081 return ExprError();
1082
1083 if (R.empty()) {
1084 Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1085 return ExprError();
1086 }
1087
1088 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1089}
1090
1091/// LookupInObjCMethod - The parser has read a name in, and Sema has
1092/// detected that we're currently inside an ObjC method. Perform some
1093/// additional lookup.
1094///
1095/// Ideally, most of this would be done by lookup, but there's
1096/// actually quite a lot of extra work involved.
1097///
1098/// Returns a null sentinel to indicate trivial success.
1099Sema::OwningExprResult
1100Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1101 IdentifierInfo *II) {
1102 SourceLocation Loc = Lookup.getNameLoc();
1103
1104 // There are two cases to handle here. 1) scoped lookup could have failed,
1105 // in which case we should look for an ivar. 2) scoped lookup could have
1106 // found a decl, but that decl is outside the current instance method (i.e.
1107 // a global variable). In these two cases, we do a lookup for an ivar with
1108 // this name, if the lookup sucedes, we replace it our current decl.
1109
1110 // If we're in a class method, we don't normally want to look for
1111 // ivars. But if we don't find anything else, and there's an
1112 // ivar, that's an error.
1113 bool IsClassMethod = getCurMethodDecl()->isClassMethod();
1114
1115 bool LookForIvars;
1116 if (Lookup.empty())
1117 LookForIvars = true;
1118 else if (IsClassMethod)
1119 LookForIvars = false;
1120 else
1121 LookForIvars = (Lookup.isSingleResult() &&
1122 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1123
1124 if (LookForIvars) {
1125 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1126 ObjCInterfaceDecl *ClassDeclared;
1127 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1128 // Diagnose using an ivar in a class method.
1129 if (IsClassMethod)
1130 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1131 << IV->getDeclName());
1132
1133 // If we're referencing an invalid decl, just return this as a silent
1134 // error node. The error diagnostic was already emitted on the decl.
1135 if (IV->isInvalidDecl())
1136 return ExprError();
1137
1138 // Check if referencing a field with __attribute__((deprecated)).
1139 if (DiagnoseUseOfDecl(IV, Loc))
1140 return ExprError();
1141
1142 // Diagnose the use of an ivar outside of the declaring class.
1143 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1144 ClassDeclared != IFace)
1145 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1146
1147 // FIXME: This should use a new expr for a direct reference, don't
1148 // turn this into Self->ivar, just return a BareIVarExpr or something.
1149 IdentifierInfo &II = Context.Idents.get("self");
1150 UnqualifiedId SelfName;
1151 SelfName.setIdentifier(&II, SourceLocation());
1152 CXXScopeSpec SelfScopeSpec;
1153 OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1154 SelfName, false, false);
1155 MarkDeclarationReferenced(Loc, IV);
1156 return Owned(new (Context)
1157 ObjCIvarRefExpr(IV, IV->getType(), Loc,
1158 SelfExpr.takeAs<Expr>(), true, true));
1159 }
1160 } else if (getCurMethodDecl()->isInstanceMethod()) {
1161 // We should warn if a local variable hides an ivar.
1162 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
1163 ObjCInterfaceDecl *ClassDeclared;
1164 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1165 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1166 IFace == ClassDeclared)
1167 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1168 }
1169 }
1170
1171 // Needed to implement property "super.method" notation.
1172 if (Lookup.empty() && II->isStr("super")) {
1173 QualType T;
1174
1175 if (getCurMethodDecl()->isInstanceMethod())
1176 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
1177 getCurMethodDecl()->getClassInterface()));
1178 else
1179 T = Context.getObjCClassType();
1180 return Owned(new (Context) ObjCSuperExpr(Loc, T));
1181 }
1182
1183 // Sentinel value saying that we didn't do anything special.
1184 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001185}
John McCalld14a8642009-11-21 08:51:07 +00001186
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001187/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001188bool
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001189Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1190 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump11289f42009-09-09 15:08:12 +00001191 if (CXXRecordDecl *RD =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001192 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump11289f42009-09-09 15:08:12 +00001193 QualType DestType =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001194 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001195 if (DestType->isDependentType() || From->getType()->isDependentType())
1196 return false;
1197 QualType FromRecordType = From->getType();
1198 QualType DestRecordType = DestType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001199 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001200 DestType = Context.getPointerType(DestType);
1201 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001202 }
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +00001203 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1204 CheckDerivedToBaseConversion(FromRecordType,
1205 DestRecordType,
1206 From->getSourceRange().getBegin(),
1207 From->getSourceRange()))
1208 return true;
Anders Carlssona076d142009-07-31 01:23:52 +00001209 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1210 /*isLvalue=*/true);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001211 }
Fariborz Jahanian3f150832009-07-29 19:40:11 +00001212 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001213}
Douglas Gregor3256d042009-06-30 15:47:41 +00001214
Douglas Gregorf405d7e2009-08-31 23:41:50 +00001215/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +00001216static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
Eli Friedman2cfcef62009-12-04 06:40:45 +00001217 const CXXScopeSpec &SS, ValueDecl *Member,
John McCalle66edc12009-11-24 19:00:30 +00001218 SourceLocation Loc, QualType Ty,
1219 const TemplateArgumentListInfo *TemplateArgs = 0) {
1220 NestedNameSpecifier *Qualifier = 0;
1221 SourceRange QualifierRange;
John McCall10eae182009-11-30 22:42:35 +00001222 if (SS.isSet()) {
1223 Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1224 QualifierRange = SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001225 }
Mike Stump11289f42009-09-09 15:08:12 +00001226
John McCalle66edc12009-11-24 19:00:30 +00001227 return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1228 Member, Loc, TemplateArgs, Ty);
Douglas Gregorc1905232009-08-26 22:36:53 +00001229}
1230
John McCall2d74de92009-12-01 22:10:20 +00001231/// Builds an implicit member access expression. The current context
1232/// is known to be an instance method, and the given unqualified lookup
1233/// set is known to contain only instance members, at least one of which
1234/// is from an appropriate type.
John McCallb53bbd42009-11-22 01:44:31 +00001235Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00001236Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1237 LookupResult &R,
1238 const TemplateArgumentListInfo *TemplateArgs,
1239 bool IsKnownInstance) {
John McCalle66edc12009-11-24 19:00:30 +00001240 assert(!R.empty() && !R.isAmbiguous());
1241
John McCalld14a8642009-11-21 08:51:07 +00001242 SourceLocation Loc = R.getNameLoc();
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00001243
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001244 // We may have found a field within an anonymous union or struct
1245 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +00001246 // FIXME: This needs to happen post-isImplicitMemberReference?
John McCalle66edc12009-11-24 19:00:30 +00001247 // FIXME: template-ids inside anonymous structs?
John McCall10eae182009-11-30 22:42:35 +00001248 if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001249 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
John McCallb53bbd42009-11-22 01:44:31 +00001250 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001251
John McCall2d74de92009-12-01 22:10:20 +00001252 // If this is known to be an instance access, go ahead and build a
1253 // 'this' expression now.
1254 QualType ThisType = cast<CXXMethodDecl>(CurContext)->getThisType(Context);
1255 Expr *This = 0; // null signifies implicit access
1256 if (IsKnownInstance) {
1257 This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00001258 }
1259
John McCall2d74de92009-12-01 22:10:20 +00001260 return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1261 /*OpLoc*/ SourceLocation(),
1262 /*IsArrow*/ true,
1263 SS, R, TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00001264}
1265
John McCalle66edc12009-11-24 19:00:30 +00001266bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001267 const LookupResult &R,
1268 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00001269 // Only when used directly as the postfix-expression of a call.
1270 if (!HasTrailingLParen)
1271 return false;
1272
1273 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00001274 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00001275 return false;
1276
1277 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00001278 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00001279 return false;
1280
1281 // Turn off ADL when we find certain kinds of declarations during
1282 // normal lookup:
1283 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1284 NamedDecl *D = *I;
1285
1286 // C++0x [basic.lookup.argdep]p3:
1287 // -- a declaration of a class member
1288 // Since using decls preserve this property, we check this on the
1289 // original decl.
John McCall5af04502009-12-02 20:26:00 +00001290 if (IsClassMember(D))
John McCalld14a8642009-11-21 08:51:07 +00001291 return false;
1292
1293 // C++0x [basic.lookup.argdep]p3:
1294 // -- a block-scope function declaration that is not a
1295 // using-declaration
1296 // NOTE: we also trigger this for function templates (in fact, we
1297 // don't check the decl type at all, since all other decl types
1298 // turn off ADL anyway).
1299 if (isa<UsingShadowDecl>(D))
1300 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1301 else if (D->getDeclContext()->isFunctionOrMethod())
1302 return false;
1303
1304 // C++0x [basic.lookup.argdep]p3:
1305 // -- a declaration that is neither a function or a function
1306 // template
1307 // And also for builtin functions.
1308 if (isa<FunctionDecl>(D)) {
1309 FunctionDecl *FDecl = cast<FunctionDecl>(D);
1310
1311 // But also builtin functions.
1312 if (FDecl->getBuiltinID() && FDecl->isImplicit())
1313 return false;
1314 } else if (!isa<FunctionTemplateDecl>(D))
1315 return false;
1316 }
1317
1318 return true;
1319}
1320
1321
John McCalld14a8642009-11-21 08:51:07 +00001322/// Diagnoses obvious problems with the use of the given declaration
1323/// as an expression. This is only actually called for lookups that
1324/// were not overloaded, and it doesn't promise that the declaration
1325/// will in fact be used.
1326static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1327 if (isa<TypedefDecl>(D)) {
1328 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1329 return true;
1330 }
1331
1332 if (isa<ObjCInterfaceDecl>(D)) {
1333 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1334 return true;
1335 }
1336
1337 if (isa<NamespaceDecl>(D)) {
1338 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1339 return true;
1340 }
1341
1342 return false;
1343}
1344
1345Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001346Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00001347 LookupResult &R,
1348 bool NeedsADL) {
John McCalle66edc12009-11-24 19:00:30 +00001349 // If this isn't an overloaded result and we don't need ADL, just
1350 // build an ordinary singleton decl ref.
John McCallb53bbd42009-11-22 01:44:31 +00001351 if (!NeedsADL && !R.isOverloadedResult())
1352 return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00001353
1354 // We only need to check the declaration if there's exactly one
1355 // result, because in the overloaded case the results can only be
1356 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00001357 if (R.isSingleResult() &&
1358 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00001359 return ExprError();
1360
John McCalle66edc12009-11-24 19:00:30 +00001361 bool Dependent
1362 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
John McCalld14a8642009-11-21 08:51:07 +00001363 UnresolvedLookupExpr *ULE
John McCalle66edc12009-11-24 19:00:30 +00001364 = UnresolvedLookupExpr::Create(Context, Dependent,
1365 (NestedNameSpecifier*) SS.getScopeRep(),
1366 SS.getRange(),
John McCallb53bbd42009-11-22 01:44:31 +00001367 R.getLookupName(), R.getNameLoc(),
1368 NeedsADL, R.isOverloadedResult());
1369 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1370 ULE->addDecl(*I);
John McCalld14a8642009-11-21 08:51:07 +00001371
1372 return Owned(ULE);
1373}
1374
1375
1376/// \brief Complete semantic analysis for a reference to the given declaration.
1377Sema::OwningExprResult
John McCalle66edc12009-11-24 19:00:30 +00001378Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCalld14a8642009-11-21 08:51:07 +00001379 SourceLocation Loc, NamedDecl *D) {
1380 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00001381 assert(!isa<FunctionTemplateDecl>(D) &&
1382 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00001383 DeclarationName Name = D->getDeclName();
1384
1385 if (CheckDeclInExpr(*this, Loc, D))
1386 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00001387
Douglas Gregore7488b92009-12-01 16:58:18 +00001388 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1389 // Specifically diagnose references to class templates that are missing
1390 // a template argument list.
1391 Diag(Loc, diag::err_template_decl_ref)
1392 << Template << SS.getRange();
1393 Diag(Template->getLocation(), diag::note_template_decl_here);
1394 return ExprError();
1395 }
1396
1397 // Make sure that we're referring to a value.
1398 ValueDecl *VD = dyn_cast<ValueDecl>(D);
1399 if (!VD) {
1400 Diag(Loc, diag::err_ref_non_value)
1401 << D << SS.getRange();
1402 Diag(D->getLocation(), diag::note_previous_decl);
1403 return ExprError();
1404 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001405
Douglas Gregor171c45a2009-02-18 21:56:37 +00001406 // Check whether this declaration can be used. Note that we suppress
1407 // this check when we're going to perform argument-dependent lookup
1408 // on this function name, because this might not be the function
1409 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00001410 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00001411 return ExprError();
1412
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001413 // Only create DeclRefExpr's for valid Decl's.
1414 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001415 return ExprError();
1416
Chris Lattner2a9d9892008-10-20 05:16:36 +00001417 // If the identifier reference is inside a block, and it refers to a value
1418 // that is outside the block, create a BlockDeclRefExpr instead of a
1419 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1420 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001421 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001422 // We do not do this for things like enum constants, global variables, etc,
1423 // as they do not get snapshotted.
1424 //
1425 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001426 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001427 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001428 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001429 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001430 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001431 // This is to record that a 'const' was actually synthesize and added.
1432 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001433 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001434
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001435 ExprTy.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00001436 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001437 constAdded));
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001438 }
1439 // If this reference is not in a block or if the referenced variable is
1440 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001441
John McCalle66edc12009-11-24 19:00:30 +00001442 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001443}
Chris Lattnere168f762006-11-10 05:29:30 +00001444
Sebastian Redlffbcf962009-01-18 18:53:16 +00001445Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1446 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001447 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001448
Chris Lattnere168f762006-11-10 05:29:30 +00001449 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001450 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001451 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1452 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1453 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001454 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001455
Chris Lattnera81a0272008-01-12 08:14:25 +00001456 // Pre-defined identifiers are of type char[x], where x is the length of the
1457 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001458
Anders Carlsson2fb08242009-09-08 18:24:21 +00001459 Decl *currentDecl = getCurFunctionOrMethodDecl();
1460 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001461 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001462 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001463 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001464
Anders Carlsson0b209a82009-09-11 01:22:35 +00001465 QualType ResTy;
1466 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1467 ResTy = Context.DependentTy;
1468 } else {
1469 unsigned Length =
1470 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001471
Anders Carlsson0b209a82009-09-11 01:22:35 +00001472 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001473 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001474 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1475 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001476 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001477}
1478
Sebastian Redlffbcf962009-01-18 18:53:16 +00001479Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001480 llvm::SmallString<16> CharBuffer;
Steve Naroffae4143e2007-04-26 20:39:23 +00001481 CharBuffer.resize(Tok.getLength());
1482 const char *ThisTokBegin = &CharBuffer[0];
1483 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001484
Steve Naroffae4143e2007-04-26 20:39:23 +00001485 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1486 Tok.getLocation(), PP);
1487 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001488 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001489
1490 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1491
Sebastian Redl20614a72009-01-20 22:23:13 +00001492 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1493 Literal.isWide(),
1494 type, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001495}
1496
Sebastian Redlffbcf962009-01-18 18:53:16 +00001497Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1498 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001499 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1500 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001501 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001502 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001503 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001504 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001505 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001506
Chris Lattner23b7eb62007-06-15 23:05:46 +00001507 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001508 // Add padding so that NumericLiteralParser can overread by one character.
1509 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001510 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001511
Chris Lattner67ca9252007-05-21 01:08:44 +00001512 // Get the spelling of the token, which eliminates trigraphs, etc.
Steve Naroff8160ea22007-03-06 01:09:46 +00001513 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001514
Mike Stump11289f42009-09-09 15:08:12 +00001515 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001516 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001517 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001518 return ExprError();
1519
Chris Lattner1c20a172007-08-26 03:42:43 +00001520 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001521
Chris Lattner1c20a172007-08-26 03:42:43 +00001522 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001523 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001524 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001525 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001526 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001527 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001528 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001529 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001530
1531 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1532
Ted Kremenek3a2c9502007-11-29 00:56:49 +00001533 // isExact will be set by GetFloatValue().
1534 bool isExact = false;
Chris Lattnere4edb8e2009-06-29 17:34:55 +00001535 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1536 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001537
Chris Lattner1c20a172007-08-26 03:42:43 +00001538 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001539 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001540 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001541 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001542
Neil Boothac582c52007-08-29 22:00:19 +00001543 // long long is a C99 feature.
1544 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001545 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001546 Diag(Tok.getLocation(), diag::ext_longlong);
1547
Chris Lattner67ca9252007-05-21 01:08:44 +00001548 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001549 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001550
Chris Lattner67ca9252007-05-21 01:08:44 +00001551 if (Literal.GetIntegerValue(ResultVal)) {
1552 // If this value didn't fit into uintmax_t, warn and force to ull.
1553 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001554 Ty = Context.UnsignedLongLongTy;
1555 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001556 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00001557 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00001558 // If this value fits into a ULL, try to figure out what else it fits into
1559 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001560
Chris Lattner67ca9252007-05-21 01:08:44 +00001561 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1562 // be an unsigned int.
1563 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1564
1565 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00001566 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00001567 if (!Literal.isLong && !Literal.isLongLong) {
1568 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00001569 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001570
Chris Lattner67ca9252007-05-21 01:08:44 +00001571 // Does it fit in a unsigned int?
1572 if (ResultVal.isIntN(IntSize)) {
1573 // Does it fit in a signed int?
1574 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001575 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001576 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001577 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001578 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001579 }
Chris Lattner67ca9252007-05-21 01:08:44 +00001580 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001581
Chris Lattner67ca9252007-05-21 01:08:44 +00001582 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001583 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001584 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001585
Chris Lattner67ca9252007-05-21 01:08:44 +00001586 // Does it fit in a unsigned long?
1587 if (ResultVal.isIntN(LongSize)) {
1588 // Does it fit in a signed long?
1589 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001590 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001591 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001592 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001593 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001594 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001595 }
1596
Chris Lattner67ca9252007-05-21 01:08:44 +00001597 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001598 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001599 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001600
Chris Lattner67ca9252007-05-21 01:08:44 +00001601 // Does it fit in a unsigned long long?
1602 if (ResultVal.isIntN(LongLongSize)) {
1603 // Does it fit in a signed long long?
1604 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001605 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001606 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001607 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001608 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001609 }
1610 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001611
Chris Lattner67ca9252007-05-21 01:08:44 +00001612 // If we still couldn't decide a type, we probably have something that
1613 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001614 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00001615 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001616 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001617 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00001618 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001619
Chris Lattner55258cf2008-05-09 05:59:00 +00001620 if (ResultVal.getBitWidth() != Width)
1621 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00001622 }
Sebastian Redl20614a72009-01-20 22:23:13 +00001623 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00001624 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001625
Chris Lattner1c20a172007-08-26 03:42:43 +00001626 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1627 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00001628 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00001629 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00001630
1631 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00001632}
1633
Sebastian Redlffbcf962009-01-18 18:53:16 +00001634Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1635 SourceLocation R, ExprArg Val) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001636 Expr *E = Val.takeAs<Expr>();
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001637 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00001638 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00001639}
1640
Steve Naroff71b59a92007-06-04 22:22:31 +00001641/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00001642/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001643bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00001644 SourceLocation OpLoc,
1645 const SourceRange &ExprRange,
1646 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001647 if (exprType->isDependentType())
1648 return false;
1649
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001650 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1651 // the result is the size of the referenced type."
1652 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1653 // result shall be the alignment of the referenced type."
1654 if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
1655 exprType = Ref->getPointeeType();
1656
Steve Naroff043d45d2007-05-15 02:32:35 +00001657 // C99 6.5.3.4p1:
John McCall4c98fd82009-11-04 07:28:41 +00001658 if (exprType->isFunctionType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001659 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001660 if (isSizeof)
1661 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1662 return false;
1663 }
Mike Stump11289f42009-09-09 15:08:12 +00001664
Chris Lattner62975a72009-04-24 00:30:45 +00001665 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001666 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001667 Diag(OpLoc, diag::ext_sizeof_void_type)
1668 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00001669 return false;
1670 }
Mike Stump11289f42009-09-09 15:08:12 +00001671
Chris Lattner62975a72009-04-24 00:30:45 +00001672 if (RequireCompleteType(OpLoc, exprType,
Mike Stump11289f42009-09-09 15:08:12 +00001673 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssond624e162009-08-26 23:45:07 +00001674 PDiag(diag::err_alignof_incomplete_type)
1675 << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00001676 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001677
Chris Lattner62975a72009-04-24 00:30:45 +00001678 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanian1dcb3222009-04-24 17:34:33 +00001679 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001680 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00001681 << exprType << isSizeof << ExprRange;
1682 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00001683 }
Mike Stump11289f42009-09-09 15:08:12 +00001684
Chris Lattner62975a72009-04-24 00:30:45 +00001685 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00001686}
1687
Chris Lattner8dff0172009-01-24 20:17:12 +00001688bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1689 const SourceRange &ExprRange) {
1690 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001691
Mike Stump11289f42009-09-09 15:08:12 +00001692 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00001693 if (isa<DeclRefExpr>(E))
1694 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001695
1696 // Cannot know anything else if the expression is dependent.
1697 if (E->isTypeDependent())
1698 return false;
1699
Douglas Gregor71235ec2009-05-02 02:18:30 +00001700 if (E->getBitField()) {
1701 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1702 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00001703 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00001704
1705 // Alignment of a field access is always okay, so long as it isn't a
1706 // bit-field.
1707 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00001708 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00001709 return false;
1710
Chris Lattner8dff0172009-01-24 20:17:12 +00001711 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1712}
1713
Douglas Gregor0950e412009-03-13 21:01:28 +00001714/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump11289f42009-09-09 15:08:12 +00001715Action::OwningExprResult
John McCallbcd03502009-12-07 02:54:59 +00001716Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
John McCall4c98fd82009-11-04 07:28:41 +00001717 SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001718 bool isSizeOf, SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00001719 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00001720 return ExprError();
1721
John McCallbcd03502009-12-07 02:54:59 +00001722 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00001723
Douglas Gregor0950e412009-03-13 21:01:28 +00001724 if (!T->isDependentType() &&
1725 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1726 return ExprError();
1727
1728 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
John McCallbcd03502009-12-07 02:54:59 +00001729 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
Douglas Gregor0950e412009-03-13 21:01:28 +00001730 Context.getSizeType(), OpLoc,
1731 R.getEnd()));
1732}
1733
1734/// \brief Build a sizeof or alignof expression given an expression
1735/// operand.
Mike Stump11289f42009-09-09 15:08:12 +00001736Action::OwningExprResult
1737Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001738 bool isSizeOf, SourceRange R) {
1739 // Verify that the operand is valid.
1740 bool isInvalid = false;
1741 if (E->isTypeDependent()) {
1742 // Delay type-checking for type-dependent expressions.
1743 } else if (!isSizeOf) {
1744 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00001745 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00001746 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1747 isInvalid = true;
1748 } else {
1749 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1750 }
1751
1752 if (isInvalid)
1753 return ExprError();
1754
1755 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1756 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1757 Context.getSizeType(), OpLoc,
1758 R.getEnd()));
1759}
1760
Sebastian Redl6f282892008-11-11 17:56:53 +00001761/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1762/// the same for @c alignof and @c __alignof
1763/// Note that the ArgRange is invalid if isType is false.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001764Action::OwningExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00001765Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1766 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001767 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001768 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00001769
Sebastian Redl6f282892008-11-11 17:56:53 +00001770 if (isType) {
John McCallbcd03502009-12-07 02:54:59 +00001771 TypeSourceInfo *TInfo;
1772 (void) GetTypeFromParser(TyOrEx, &TInfo);
1773 return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00001774 }
Sebastian Redl6f282892008-11-11 17:56:53 +00001775
Douglas Gregor0950e412009-03-13 21:01:28 +00001776 Expr *ArgEx = (Expr *)TyOrEx;
1777 Action::OwningExprResult Result
1778 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1779
1780 if (Result.isInvalid())
1781 DeleteExpr(ArgEx);
1782
1783 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00001784}
1785
Chris Lattner709322b2009-02-17 08:12:06 +00001786QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001787 if (V->isTypeDependent())
1788 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00001789
Chris Lattnere267f5d2007-08-26 05:39:26 +00001790 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00001791 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00001792 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001793
Chris Lattnere267f5d2007-08-26 05:39:26 +00001794 // Otherwise they pass through real integer and floating point types here.
1795 if (V->getType()->isArithmeticType())
1796 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001797
Chris Lattnere267f5d2007-08-26 05:39:26 +00001798 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00001799 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1800 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00001801 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00001802}
1803
1804
Chris Lattnere168f762006-11-10 05:29:30 +00001805
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001806Action::OwningExprResult
1807Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1808 tok::TokenKind Kind, ExprArg Input) {
Chris Lattnere168f762006-11-10 05:29:30 +00001809 UnaryOperator::Opcode Opc;
1810 switch (Kind) {
1811 default: assert(0 && "Unknown unary op!");
1812 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1813 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1814 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001815
Eli Friedmancfdd40c2009-11-18 03:38:04 +00001816 return BuildUnaryOp(S, OpLoc, Opc, move(Input));
Chris Lattnere168f762006-11-10 05:29:30 +00001817}
1818
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001819Action::OwningExprResult
1820Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1821 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00001822 // Since this might be a postfix expression, get rid of ParenListExprs.
1823 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1824
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001825 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1826 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump11289f42009-09-09 15:08:12 +00001827
Douglas Gregor40412ac2008-11-19 17:17:41 +00001828 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00001829 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1830 Base.release();
1831 Idx.release();
1832 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1833 Context.DependentTy, RLoc));
1834 }
1835
Mike Stump11289f42009-09-09 15:08:12 +00001836 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001837 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00001838 LHSExp->getType()->isEnumeralType() ||
1839 RHSExp->getType()->isRecordType() ||
1840 RHSExp->getType()->isEnumeralType())) {
Sebastian Redladba46e2009-10-29 20:17:01 +00001841 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
Douglas Gregor40412ac2008-11-19 17:17:41 +00001842 }
1843
Sebastian Redladba46e2009-10-29 20:17:01 +00001844 return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
1845}
1846
1847
1848Action::OwningExprResult
1849Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
1850 ExprArg Idx, SourceLocation RLoc) {
1851 Expr *LHSExp = static_cast<Expr*>(Base.get());
1852 Expr *RHSExp = static_cast<Expr*>(Idx.get());
1853
Chris Lattner36d572b2007-07-16 00:14:47 +00001854 // Perform default conversions.
1855 DefaultFunctionArrayConversion(LHSExp);
1856 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001857
Chris Lattner36d572b2007-07-16 00:14:47 +00001858 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00001859
Steve Naroffc1aadb12007-03-28 21:49:40 +00001860 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00001861 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00001862 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00001863 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00001864 Expr *BaseExpr, *IndexExpr;
1865 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001866 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1867 BaseExpr = LHSExp;
1868 IndexExpr = RHSExp;
1869 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001870 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00001871 BaseExpr = LHSExp;
1872 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001873 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001874 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00001875 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00001876 BaseExpr = RHSExp;
1877 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001878 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001879 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00001880 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001881 BaseExpr = LHSExp;
1882 IndexExpr = RHSExp;
1883 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001884 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00001885 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001886 // Handle the uncommon case of "123[Ptr]".
1887 BaseExpr = RHSExp;
1888 IndexExpr = LHSExp;
1889 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001890 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00001891 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00001892 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00001893
Chris Lattner36d572b2007-07-16 00:14:47 +00001894 // FIXME: need to deal with const...
1895 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00001896 } else if (LHSTy->isArrayType()) {
1897 // If we see an array that wasn't promoted by
1898 // DefaultFunctionArrayConversion, it must be an array that
1899 // wasn't promoted because of the C90 rule that doesn't
1900 // allow promoting non-lvalue arrays. Warn, then
1901 // force the promotion here.
1902 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1903 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00001904 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1905 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00001906 LHSTy = LHSExp->getType();
1907
1908 BaseExpr = LHSExp;
1909 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001910 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00001911 } else if (RHSTy->isArrayType()) {
1912 // Same as previous, except for 123[f().a] case
1913 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1914 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00001915 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1916 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00001917 RHSTy = RHSExp->getType();
1918
1919 BaseExpr = RHSExp;
1920 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001921 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00001922 } else {
Chris Lattner003af242009-04-25 22:50:55 +00001923 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1924 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001925 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00001926 // C99 6.5.2.1p1
Nate Begeman5ec4b312009-08-10 23:49:36 +00001927 if (!(IndexExpr->getType()->isIntegerType() &&
1928 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00001929 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1930 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00001931
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00001932 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00001933 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1934 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00001935 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1936
Douglas Gregorac1fb652009-03-24 19:52:54 +00001937 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00001938 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1939 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00001940 // incomplete types are not object types.
1941 if (ResultType->isFunctionType()) {
1942 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1943 << ResultType << BaseExpr->getSourceRange();
1944 return ExprError();
1945 }
Mike Stump11289f42009-09-09 15:08:12 +00001946
Douglas Gregorac1fb652009-03-24 19:52:54 +00001947 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001948 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00001949 PDiag(diag::err_subscript_incomplete_type)
1950 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00001951 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001952
Chris Lattner62975a72009-04-24 00:30:45 +00001953 // Diagnose bad cases where we step over interface counts.
1954 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1955 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1956 << ResultType << BaseExpr->getSourceRange();
1957 return ExprError();
1958 }
Mike Stump11289f42009-09-09 15:08:12 +00001959
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001960 Base.release();
1961 Idx.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00001962 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00001963 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00001964}
1965
Steve Narofff8fd09e2007-07-27 22:15:19 +00001966QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00001967CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001968 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00001969 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00001970 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1971 // see FIXME there.
1972 //
1973 // FIXME: This logic can be greatly simplified by splitting it along
1974 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00001975 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00001976
Steve Narofff8fd09e2007-07-27 22:15:19 +00001977 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001978 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00001979
Mike Stump4e1f26a2009-02-19 03:04:26 +00001980 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00001981 // special names that indicate a subset of exactly half the elements are
1982 // to be selected.
1983 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00001984
Nate Begemanbb70bf62009-01-18 01:47:54 +00001985 // This flag determines whether or not CompName has an 's' char prefix,
1986 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00001987 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00001988
1989 // Check that we've found one of the special components, or that the component
1990 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00001991 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00001992 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1993 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00001994 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00001995 do
1996 compStr++;
1997 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00001998 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00001999 do
2000 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002001 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00002002 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00002003
Mike Stump4e1f26a2009-02-19 03:04:26 +00002004 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00002005 // We didn't get to the end of the string. This means the component names
2006 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00002007 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2008 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00002009 return QualType();
2010 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002011
Nate Begemanbb70bf62009-01-18 01:47:54 +00002012 // Ensure no component accessor exceeds the width of the vector type it
2013 // operates on.
2014 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002015 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002016
2017 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00002018 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00002019
2020 while (*compStr) {
2021 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2022 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2023 << baseType << SourceRange(CompLoc);
2024 return QualType();
2025 }
2026 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00002027 }
Nate Begemanf322eab2008-05-09 06:41:27 +00002028
Nate Begemanbb70bf62009-01-18 01:47:54 +00002029 // If this is a halving swizzle, verify that the base type has an even
2030 // number of elements.
2031 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner3b054132008-11-19 05:08:23 +00002032 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner1e5665e2008-11-24 06:25:27 +00002033 << baseType << SourceRange(CompLoc);
Nate Begemanf322eab2008-05-09 06:41:27 +00002034 return QualType();
2035 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002036
Steve Narofff8fd09e2007-07-27 22:15:19 +00002037 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002038 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00002039 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002040 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00002041 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanbb70bf62009-01-18 01:47:54 +00002042 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00002043 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00002044 if (HexSwizzle)
2045 CompSize--;
2046
Steve Narofff8fd09e2007-07-27 22:15:19 +00002047 if (CompSize == 1)
2048 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002049
Nate Begemance4d7fc2008-04-18 23:10:10 +00002050 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002051 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00002052 // diagostics look bad. We want extended vector types to appear built-in.
2053 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2054 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2055 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00002056 }
2057 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00002058}
2059
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002060static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00002061 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002062 const Selector &Sel,
2063 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00002064
Anders Carlssonf571c112009-08-26 18:25:21 +00002065 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002066 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002067 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002068 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00002069
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002070 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2071 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00002072 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002073 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002074 return D;
2075 }
2076 return 0;
2077}
2078
Steve Narofffb4330f2009-06-17 22:40:22 +00002079static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00002080 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002081 const Selector &Sel,
2082 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002083 // Check protocols on qualified interfaces.
2084 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00002085 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002086 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002087 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002088 GDecl = PD;
2089 break;
2090 }
2091 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002092 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002093 GDecl = OMD;
2094 break;
2095 }
2096 }
2097 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00002098 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002099 E = QIdTy->qual_end(); I != E; ++I) {
2100 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00002101 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00002102 if (GDecl)
2103 return GDecl;
2104 }
2105 }
2106 return GDecl;
2107}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00002108
John McCall10eae182009-11-30 22:42:35 +00002109Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002110Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2111 bool IsArrow, SourceLocation OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002112 const CXXScopeSpec &SS,
2113 NamedDecl *FirstQualifierInScope,
2114 DeclarationName Name, SourceLocation NameLoc,
2115 const TemplateArgumentListInfo *TemplateArgs) {
2116 Expr *BaseExpr = Base.takeAs<Expr>();
2117
2118 // Even in dependent contexts, try to diagnose base expressions with
2119 // obviously wrong types, e.g.:
2120 //
2121 // T* t;
2122 // t.f;
2123 //
2124 // In Obj-C++, however, the above expression is valid, since it could be
2125 // accessing the 'f' property if T is an Obj-C interface. The extra check
2126 // allows this, while still reporting an error if T is a struct pointer.
2127 if (!IsArrow) {
John McCall2d74de92009-12-01 22:10:20 +00002128 const PointerType *PT = BaseType->getAs<PointerType>();
John McCall10eae182009-11-30 22:42:35 +00002129 if (PT && (!getLangOptions().ObjC1 ||
2130 PT->getPointeeType()->isRecordType())) {
John McCall2d74de92009-12-01 22:10:20 +00002131 assert(BaseExpr && "cannot happen with implicit member accesses");
John McCall10eae182009-11-30 22:42:35 +00002132 Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
John McCall2d74de92009-12-01 22:10:20 +00002133 << BaseType << BaseExpr->getSourceRange();
John McCall10eae182009-11-30 22:42:35 +00002134 return ExprError();
2135 }
2136 }
2137
John McCall2d74de92009-12-01 22:10:20 +00002138 assert(BaseType->isDependentType());
John McCall10eae182009-11-30 22:42:35 +00002139
2140 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2141 // must have pointer type, and the accessed type is the pointee.
John McCall2d74de92009-12-01 22:10:20 +00002142 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
John McCall10eae182009-11-30 22:42:35 +00002143 IsArrow, OpLoc,
2144 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2145 SS.getRange(),
2146 FirstQualifierInScope,
2147 Name, NameLoc,
2148 TemplateArgs));
2149}
2150
2151/// We know that the given qualified member reference points only to
2152/// declarations which do not belong to the static type of the base
2153/// expression. Diagnose the problem.
2154static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2155 Expr *BaseExpr,
2156 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002157 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002158 const LookupResult &R) {
John McCallcd4b4772009-12-02 03:53:29 +00002159 // If this is an implicit member access, use a different set of
2160 // diagnostics.
2161 if (!BaseExpr)
2162 return DiagnoseInstanceReference(SemaRef, SS, R);
John McCall10eae182009-11-30 22:42:35 +00002163
2164 // FIXME: this is an exceedingly lame diagnostic for some of the more
2165 // complicated cases here.
John McCallcd4b4772009-12-02 03:53:29 +00002166 DeclContext *DC = R.getRepresentativeDecl()->getDeclContext();
John McCall10eae182009-11-30 22:42:35 +00002167 SemaRef.Diag(R.getNameLoc(), diag::err_not_direct_base_or_virtual)
John McCallcd4b4772009-12-02 03:53:29 +00002168 << SS.getRange() << DC << BaseType;
John McCall10eae182009-11-30 22:42:35 +00002169}
2170
2171// Check whether the declarations we found through a nested-name
2172// specifier in a member expression are actually members of the base
2173// type. The restriction here is:
2174//
2175// C++ [expr.ref]p2:
2176// ... In these cases, the id-expression shall name a
2177// member of the class or of one of its base classes.
2178//
2179// So it's perfectly legitimate for the nested-name specifier to name
2180// an unrelated class, and for us to find an overload set including
2181// decls from classes which are not superclasses, as long as the decl
2182// we actually pick through overload resolution is from a superclass.
2183bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2184 QualType BaseType,
John McCallcd4b4772009-12-02 03:53:29 +00002185 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002186 const LookupResult &R) {
John McCall2d74de92009-12-01 22:10:20 +00002187 const RecordType *BaseRT = BaseType->getAs<RecordType>();
2188 if (!BaseRT) {
2189 // We can't check this yet because the base type is still
2190 // dependent.
2191 assert(BaseType->isDependentType());
2192 return false;
2193 }
2194 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
John McCall10eae182009-11-30 22:42:35 +00002195
2196 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
John McCall2d74de92009-12-01 22:10:20 +00002197 // If this is an implicit member reference and we find a
2198 // non-instance member, it's not an error.
2199 if (!BaseExpr && !IsInstanceMember((*I)->getUnderlyingDecl()))
2200 return false;
John McCall10eae182009-11-30 22:42:35 +00002201
John McCall2d74de92009-12-01 22:10:20 +00002202 // Note that we use the DC of the decl, not the underlying decl.
2203 CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2204 while (RecordD->isAnonymousStructOrUnion())
2205 RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2206
2207 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2208 MemberRecord.insert(RecordD->getCanonicalDecl());
2209
2210 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2211 return false;
2212 }
2213
John McCallcd4b4772009-12-02 03:53:29 +00002214 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
John McCall2d74de92009-12-01 22:10:20 +00002215 return true;
2216}
2217
2218static bool
2219LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2220 SourceRange BaseRange, const RecordType *RTy,
2221 SourceLocation OpLoc, const CXXScopeSpec &SS) {
2222 RecordDecl *RDecl = RTy->getDecl();
2223 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2224 PDiag(diag::err_typecheck_incomplete_tag)
2225 << BaseRange))
2226 return true;
2227
2228 DeclContext *DC = RDecl;
2229 if (SS.isSet()) {
2230 // If the member name was a qualified-id, look into the
2231 // nested-name-specifier.
2232 DC = SemaRef.computeDeclContext(SS, false);
2233
John McCallcd4b4772009-12-02 03:53:29 +00002234 if (SemaRef.RequireCompleteDeclContext(SS)) {
2235 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2236 << SS.getRange() << DC;
2237 return true;
2238 }
2239
John McCall2d74de92009-12-01 22:10:20 +00002240 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2241
2242 if (!isa<TypeDecl>(DC)) {
2243 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2244 << DC << SS.getRange();
2245 return true;
John McCall10eae182009-11-30 22:42:35 +00002246 }
2247 }
2248
John McCall2d74de92009-12-01 22:10:20 +00002249 // The record definition is complete, now look up the member.
2250 SemaRef.LookupQualifiedName(R, DC);
John McCall10eae182009-11-30 22:42:35 +00002251
2252 return false;
2253}
2254
2255Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002256Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
John McCall10eae182009-11-30 22:42:35 +00002257 SourceLocation OpLoc, bool IsArrow,
2258 const CXXScopeSpec &SS,
2259 NamedDecl *FirstQualifierInScope,
2260 DeclarationName Name, SourceLocation NameLoc,
2261 const TemplateArgumentListInfo *TemplateArgs) {
2262 Expr *Base = BaseArg.takeAs<Expr>();
2263
John McCallcd4b4772009-12-02 03:53:29 +00002264 if (BaseType->isDependentType() ||
2265 (SS.isSet() && isDependentScopeSpecifier(SS)))
John McCall2d74de92009-12-01 22:10:20 +00002266 return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
John McCall10eae182009-11-30 22:42:35 +00002267 IsArrow, OpLoc,
2268 SS, FirstQualifierInScope,
2269 Name, NameLoc,
2270 TemplateArgs);
2271
2272 LookupResult R(*this, Name, NameLoc, LookupMemberName);
John McCall10eae182009-11-30 22:42:35 +00002273
John McCall2d74de92009-12-01 22:10:20 +00002274 // Implicit member accesses.
2275 if (!Base) {
2276 QualType RecordTy = BaseType;
2277 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2278 if (LookupMemberExprInRecord(*this, R, SourceRange(),
2279 RecordTy->getAs<RecordType>(),
2280 OpLoc, SS))
2281 return ExprError();
2282
2283 // Explicit member accesses.
2284 } else {
2285 OwningExprResult Result =
2286 LookupMemberExpr(R, Base, IsArrow, OpLoc,
2287 SS, FirstQualifierInScope,
2288 /*ObjCImpDecl*/ DeclPtrTy());
2289
2290 if (Result.isInvalid()) {
2291 Owned(Base);
2292 return ExprError();
2293 }
2294
2295 if (Result.get())
2296 return move(Result);
John McCall10eae182009-11-30 22:42:35 +00002297 }
2298
John McCall2d74de92009-12-01 22:10:20 +00002299 return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2300 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002301}
2302
2303Sema::OwningExprResult
John McCall2d74de92009-12-01 22:10:20 +00002304Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2305 SourceLocation OpLoc, bool IsArrow,
2306 const CXXScopeSpec &SS,
John McCall10eae182009-11-30 22:42:35 +00002307 LookupResult &R,
2308 const TemplateArgumentListInfo *TemplateArgs) {
2309 Expr *BaseExpr = Base.takeAs<Expr>();
John McCall2d74de92009-12-01 22:10:20 +00002310 QualType BaseType = BaseExprType;
John McCall10eae182009-11-30 22:42:35 +00002311 if (IsArrow) {
2312 assert(BaseType->isPointerType());
2313 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2314 }
2315
2316 NestedNameSpecifier *Qualifier =
2317 static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2318 DeclarationName MemberName = R.getLookupName();
2319 SourceLocation MemberLoc = R.getNameLoc();
2320
2321 if (R.isAmbiguous())
Douglas Gregord8061562009-08-06 03:17:00 +00002322 return ExprError();
2323
John McCall10eae182009-11-30 22:42:35 +00002324 if (R.empty()) {
2325 // Rederive where we looked up.
2326 DeclContext *DC = (SS.isSet()
2327 ? computeDeclContext(SS, false)
2328 : BaseType->getAs<RecordType>()->getDecl());
Nate Begeman5ec4b312009-08-10 23:49:36 +00002329
John McCall10eae182009-11-30 22:42:35 +00002330 Diag(R.getNameLoc(), diag::err_no_member)
John McCall2d74de92009-12-01 22:10:20 +00002331 << MemberName << DC
2332 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
John McCall10eae182009-11-30 22:42:35 +00002333 return ExprError();
2334 }
2335
John McCallcd4b4772009-12-02 03:53:29 +00002336 // Diagnose qualified lookups that find only declarations from a
2337 // non-base type. Note that it's okay for lookup to find
2338 // declarations from a non-base type as long as those aren't the
2339 // ones picked by overload resolution.
2340 if (SS.isSet() && CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
John McCall10eae182009-11-30 22:42:35 +00002341 return ExprError();
2342
2343 // Construct an unresolved result if we in fact got an unresolved
2344 // result.
2345 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
John McCall2d74de92009-12-01 22:10:20 +00002346 bool Dependent =
2347 R.isUnresolvableResult() ||
2348 UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002349
2350 UnresolvedMemberExpr *MemExpr
2351 = UnresolvedMemberExpr::Create(Context, Dependent,
2352 R.isUnresolvableResult(),
John McCall2d74de92009-12-01 22:10:20 +00002353 BaseExpr, BaseExprType,
2354 IsArrow, OpLoc,
John McCall10eae182009-11-30 22:42:35 +00002355 Qualifier, SS.getRange(),
2356 MemberName, MemberLoc,
2357 TemplateArgs);
2358 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
2359 MemExpr->addDecl(*I);
2360
2361 return Owned(MemExpr);
2362 }
2363
2364 assert(R.isSingleResult());
2365 NamedDecl *MemberDecl = R.getFoundDecl();
2366
2367 // FIXME: diagnose the presence of template arguments now.
2368
2369 // If the decl being referenced had an error, return an error for this
2370 // sub-expr without emitting another error, in order to avoid cascading
2371 // error cases.
2372 if (MemberDecl->isInvalidDecl())
2373 return ExprError();
2374
John McCall2d74de92009-12-01 22:10:20 +00002375 // Handle the implicit-member-access case.
2376 if (!BaseExpr) {
2377 // If this is not an instance member, convert to a non-member access.
2378 if (!IsInstanceMember(MemberDecl))
2379 return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2380
2381 BaseExpr = new (Context) CXXThisExpr(SourceLocation(), BaseExprType);
2382 }
2383
John McCall10eae182009-11-30 22:42:35 +00002384 bool ShouldCheckUse = true;
2385 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2386 // Don't diagnose the use of a virtual member function unless it's
2387 // explicitly qualified.
2388 if (MD->isVirtual() && !SS.isSet())
2389 ShouldCheckUse = false;
2390 }
2391
2392 // Check the use of this member.
2393 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2394 Owned(BaseExpr);
2395 return ExprError();
2396 }
2397
2398 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2399 // We may have found a field within an anonymous union or struct
2400 // (C++ [class.union]).
Eli Friedman78cde142009-12-04 07:18:51 +00002401 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2402 !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
John McCall10eae182009-11-30 22:42:35 +00002403 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2404 BaseExpr, OpLoc);
2405
2406 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2407 QualType MemberType = FD->getType();
2408 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2409 MemberType = Ref->getPointeeType();
2410 else {
2411 Qualifiers BaseQuals = BaseType.getQualifiers();
2412 BaseQuals.removeObjCGCAttr();
2413 if (FD->isMutable()) BaseQuals.removeConst();
2414
2415 Qualifiers MemberQuals
2416 = Context.getCanonicalType(MemberType).getQualifiers();
2417
2418 Qualifiers Combined = BaseQuals + MemberQuals;
2419 if (Combined != MemberQuals)
2420 MemberType = Context.getQualifiedType(MemberType, Combined);
2421 }
2422
2423 MarkDeclarationReferenced(MemberLoc, FD);
2424 if (PerformObjectMemberConversion(BaseExpr, FD))
2425 return ExprError();
2426 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2427 FD, MemberLoc, MemberType));
2428 }
2429
2430 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2431 MarkDeclarationReferenced(MemberLoc, Var);
2432 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2433 Var, MemberLoc,
2434 Var->getType().getNonReferenceType()));
2435 }
2436
2437 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2438 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2439 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2440 MemberFn, MemberLoc,
2441 MemberFn->getType()));
2442 }
2443
2444 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2445 MarkDeclarationReferenced(MemberLoc, MemberDecl);
2446 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2447 Enum, MemberLoc, Enum->getType()));
2448 }
2449
2450 Owned(BaseExpr);
2451
2452 if (isa<TypeDecl>(MemberDecl))
2453 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2454 << MemberName << int(IsArrow));
2455
2456 // We found a declaration kind that we didn't expect. This is a
2457 // generic error message that tells the user that she can't refer
2458 // to this member with '.' or '->'.
2459 return ExprError(Diag(MemberLoc,
2460 diag::err_typecheck_member_reference_unknown)
2461 << MemberName << int(IsArrow));
2462}
2463
2464/// Look up the given member of the given non-type-dependent
2465/// expression. This can return in one of two ways:
2466/// * If it returns a sentinel null-but-valid result, the caller will
2467/// assume that lookup was performed and the results written into
2468/// the provided structure. It will take over from there.
2469/// * Otherwise, the returned expression will be produced in place of
2470/// an ordinary member expression.
2471///
2472/// The ObjCImpDecl bit is a gross hack that will need to be properly
2473/// fixed for ObjC++.
2474Sema::OwningExprResult
2475Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
2476 bool IsArrow, SourceLocation OpLoc,
2477 const CXXScopeSpec &SS,
2478 NamedDecl *FirstQualifierInScope,
2479 DeclPtrTy ObjCImpDecl) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002480 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00002481
Steve Naroffeaaae462007-12-16 21:42:28 +00002482 // Perform default conversions.
2483 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002484
Steve Naroff185616f2007-07-26 03:11:44 +00002485 QualType BaseType = BaseExpr->getType();
John McCall10eae182009-11-30 22:42:35 +00002486 assert(!BaseType->isDependentType());
2487
2488 DeclarationName MemberName = R.getLookupName();
2489 SourceLocation MemberLoc = R.getNameLoc();
Douglas Gregord82ae382009-11-06 06:30:47 +00002490
2491 // If the user is trying to apply -> or . to a function pointer
John McCall10eae182009-11-30 22:42:35 +00002492 // type, it's probably because they forgot parentheses to call that
Douglas Gregord82ae382009-11-06 06:30:47 +00002493 // function. Suggest the addition of those parentheses, build the
2494 // call, and continue on.
2495 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2496 if (const FunctionProtoType *Fun
2497 = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2498 QualType ResultTy = Fun->getResultType();
2499 if (Fun->getNumArgs() == 0 &&
John McCall10eae182009-11-30 22:42:35 +00002500 ((!IsArrow && ResultTy->isRecordType()) ||
2501 (IsArrow && ResultTy->isPointerType() &&
Douglas Gregord82ae382009-11-06 06:30:47 +00002502 ResultTy->getAs<PointerType>()->getPointeeType()
2503 ->isRecordType()))) {
2504 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2505 Diag(Loc, diag::err_member_reference_needs_call)
2506 << QualType(Fun, 0)
2507 << CodeModificationHint::CreateInsertion(Loc, "()");
2508
2509 OwningExprResult NewBase
John McCall10eae182009-11-30 22:42:35 +00002510 = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
Douglas Gregord82ae382009-11-06 06:30:47 +00002511 MultiExprArg(*this, 0, 0), 0, Loc);
2512 if (NewBase.isInvalid())
John McCall10eae182009-11-30 22:42:35 +00002513 return ExprError();
Douglas Gregord82ae382009-11-06 06:30:47 +00002514
2515 BaseExpr = NewBase.takeAs<Expr>();
2516 DefaultFunctionArrayConversion(BaseExpr);
2517 BaseType = BaseExpr->getType();
2518 }
2519 }
2520 }
2521
David Chisnall9f57c292009-08-17 16:35:33 +00002522 // If this is an Objective-C pseudo-builtin and a definition is provided then
2523 // use that.
2524 if (BaseType->isObjCIdType()) {
Fariborz Jahanianc2949f92009-12-07 20:09:25 +00002525 if (IsArrow) {
2526 // Handle the following exceptional case PObj->isa.
2527 if (const ObjCObjectPointerType *OPT =
2528 BaseType->getAs<ObjCObjectPointerType>()) {
2529 if (OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2530 MemberName.getAsIdentifierInfo()->isStr("isa"))
2531 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2532 Context.getObjCIdType()));
2533 }
2534 }
David Chisnall9f57c292009-08-17 16:35:33 +00002535 // We have an 'id' type. Rather than fall through, we check if this
2536 // is a reference to 'isa'.
2537 if (BaseType != Context.ObjCIdRedefinitionType) {
2538 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002539 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00002540 }
David Chisnall9f57c292009-08-17 16:35:33 +00002541 }
John McCall10eae182009-11-30 22:42:35 +00002542
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00002543 // If this is an Objective-C pseudo-builtin and a definition is provided then
2544 // use that.
2545 if (Context.isObjCSelType(BaseType)) {
2546 // We have an 'SEL' type. Rather than fall through, we check if this
2547 // is a reference to 'sel_id'.
2548 if (BaseType != Context.ObjCSelRedefinitionType) {
2549 BaseType = Context.ObjCSelRedefinitionType;
2550 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2551 }
2552 }
John McCall10eae182009-11-30 22:42:35 +00002553
Steve Naroff185616f2007-07-26 03:11:44 +00002554 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002555
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002556 // Handle properties on ObjC 'Class' types.
John McCall10eae182009-11-30 22:42:35 +00002557 if (!IsArrow && BaseType->isObjCClassType()) {
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002558 // Also must look for a getter name which uses property syntax.
2559 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2560 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2561 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2562 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2563 ObjCMethodDecl *Getter;
2564 // FIXME: need to also look locally in the implementation.
2565 if ((Getter = IFace->lookupClassMethod(Sel))) {
2566 // Check the use of this method.
2567 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2568 return ExprError();
2569 }
2570 // If we found a getter then this may be a valid dot-reference, we
2571 // will look for the matching setter, in case it is needed.
2572 Selector SetterSel =
2573 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2574 PP.getSelectorTable(), Member);
2575 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2576 if (!Setter) {
2577 // If this reference is in an @implementation, also check for 'private'
2578 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002579 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002580 }
2581 // Look through local category implementations associated with the class.
2582 if (!Setter)
2583 Setter = IFace->getCategoryClassMethod(SetterSel);
2584
2585 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2586 return ExprError();
2587
2588 if (Getter || Setter) {
2589 QualType PType;
2590
2591 if (Getter)
2592 PType = Getter->getResultType();
2593 else
2594 // Get the expression type from Setter's incoming parameter.
2595 PType = (*(Setter->param_end() -1))->getType();
2596 // FIXME: we must check that the setter has property type.
2597 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2598 PType,
2599 Setter, MemberLoc, BaseExpr));
2600 }
2601 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2602 << MemberName << BaseType);
2603 }
2604 }
2605
2606 if (BaseType->isObjCClassType() &&
2607 BaseType != Context.ObjCClassRedefinitionType) {
2608 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002609 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002610 }
Mike Stump11289f42009-09-09 15:08:12 +00002611
John McCall10eae182009-11-30 22:42:35 +00002612 if (IsArrow) {
2613 if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00002614 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002615 else if (BaseType->isObjCObjectPointerType())
2616 ;
John McCall10eae182009-11-30 22:42:35 +00002617 else {
2618 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
2619 << BaseType << BaseExpr->getSourceRange();
2620 return ExprError();
Anders Carlsson524d5a42009-05-16 20:31:20 +00002621 }
John McCall10eae182009-11-30 22:42:35 +00002622 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002623
John McCall10eae182009-11-30 22:42:35 +00002624 // Handle field access to simple records. This also handles access
2625 // to fields of the ObjC 'id' struct.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002626 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
John McCall2d74de92009-12-01 22:10:20 +00002627 if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
2628 RTy, OpLoc, SS))
Douglas Gregordd430f72009-01-19 19:26:10 +00002629 return ExprError();
John McCall10eae182009-11-30 22:42:35 +00002630 return Owned((Expr*) 0);
Chris Lattnerb63a7452008-07-21 04:28:12 +00002631 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002632
Douglas Gregorad8a3362009-09-04 17:36:40 +00002633 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2634 // into a record type was handled above, any destructor we see here is a
2635 // pseudo-destructor.
2636 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2637 // C++ [expr.pseudo]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002638 // The left hand side of the dot operator shall be of scalar type. The
2639 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregorad8a3362009-09-04 17:36:40 +00002640 // type.
2641 if (!BaseType->isScalarType())
2642 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2643 << BaseType << BaseExpr->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +00002644
Douglas Gregorad8a3362009-09-04 17:36:40 +00002645 // [...] The type designated by the pseudo-destructor-name shall be the
2646 // same as the object type.
2647 if (!MemberName.getCXXNameType()->isDependentType() &&
2648 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2649 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2650 << BaseType << MemberName.getCXXNameType()
2651 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump11289f42009-09-09 15:08:12 +00002652
2653 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregorad8a3362009-09-04 17:36:40 +00002654 // the form
2655 //
Mike Stump11289f42009-09-09 15:08:12 +00002656 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2657 //
Douglas Gregorad8a3362009-09-04 17:36:40 +00002658 // shall designate the same scalar type.
2659 //
2660 // FIXME: DPG can't see any way to trigger this particular clause, so it
2661 // isn't checked here.
Mike Stump11289f42009-09-09 15:08:12 +00002662
Douglas Gregorad8a3362009-09-04 17:36:40 +00002663 // FIXME: We've lost the precise spelling of the type by going through
2664 // DeclarationName. Can we do better?
2665 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002666 IsArrow, OpLoc,
2667 (NestedNameSpecifier *) SS.getScopeRep(),
2668 SS.getRange(),
Douglas Gregorad8a3362009-09-04 17:36:40 +00002669 MemberName.getCXXNameType(),
2670 MemberLoc));
2671 }
Mike Stump11289f42009-09-09 15:08:12 +00002672
Chris Lattnerdc420f42008-07-21 04:59:05 +00002673 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2674 // (*Obj).ivar.
John McCall10eae182009-11-30 22:42:35 +00002675 if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
2676 (!IsArrow && BaseType->isObjCInterfaceType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002677 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002678 const ObjCInterfaceType *IFaceT =
John McCall9dd450b2009-09-21 23:43:11 +00002679 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffa057ba92009-07-16 00:25:06 +00002680 if (IFaceT) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002681 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2682
Steve Naroffa057ba92009-07-16 00:25:06 +00002683 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2684 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00002685 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00002686
Steve Naroffa057ba92009-07-16 00:25:06 +00002687 if (IV) {
2688 // If the decl being referenced had an error, return an error for this
2689 // sub-expr without emitting another error, in order to avoid cascading
2690 // error cases.
2691 if (IV->isInvalidDecl())
2692 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002693
Steve Naroffa057ba92009-07-16 00:25:06 +00002694 // Check whether we can reference this field.
2695 if (DiagnoseUseOfDecl(IV, MemberLoc))
2696 return ExprError();
2697 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2698 IV->getAccessControl() != ObjCIvarDecl::Package) {
2699 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2700 if (ObjCMethodDecl *MD = getCurMethodDecl())
2701 ClassOfMethodDecl = MD->getClassInterface();
2702 else if (ObjCImpDecl && getCurFunctionDecl()) {
2703 // Case of a c-function declared inside an objc implementation.
2704 // FIXME: For a c-style function nested inside an objc implementation
2705 // class, there is no implementation context available, so we pass
2706 // down the context as argument to this routine. Ideally, this context
2707 // need be passed down in the AST node and somehow calculated from the
2708 // AST for a function decl.
2709 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump11289f42009-09-09 15:08:12 +00002710 if (ObjCImplementationDecl *IMPD =
Steve Naroffa057ba92009-07-16 00:25:06 +00002711 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2712 ClassOfMethodDecl = IMPD->getClassInterface();
2713 else if (ObjCCategoryImplDecl* CatImplClass =
2714 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2715 ClassOfMethodDecl = CatImplClass->getClassInterface();
2716 }
Mike Stump11289f42009-09-09 15:08:12 +00002717
2718 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2719 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00002720 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00002721 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002722 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00002723 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2724 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00002725 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002726 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00002727 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002728
2729 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2730 MemberLoc, BaseExpr,
John McCall10eae182009-11-30 22:42:35 +00002731 IsArrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00002732 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002733 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00002734 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00002735 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00002736 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00002737 }
Steve Naroff1329fa02009-07-15 18:40:39 +00002738 // Handle properties on 'id' and qualified "id".
John McCall10eae182009-11-30 22:42:35 +00002739 if (!IsArrow && (BaseType->isObjCIdType() ||
2740 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002741 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00002742 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002743
Steve Naroff7cae42b2009-07-10 23:34:53 +00002744 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00002745 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002746 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2747 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2748 // Check the use of this declaration
2749 if (DiagnoseUseOfDecl(PD, MemberLoc))
2750 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002751
Steve Naroff7cae42b2009-07-10 23:34:53 +00002752 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2753 MemberLoc, BaseExpr));
2754 }
2755 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2756 // Check the use of this method.
2757 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2758 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002759
Steve Naroff7cae42b2009-07-10 23:34:53 +00002760 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump11289f42009-09-09 15:08:12 +00002761 OMD->getResultType(),
2762 OMD, OpLoc, MemberLoc,
Steve Naroff7cae42b2009-07-10 23:34:53 +00002763 NULL, 0));
2764 }
2765 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002766
Steve Naroff7cae42b2009-07-10 23:34:53 +00002767 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002768 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002769 }
Chris Lattnerdc420f42008-07-21 04:59:05 +00002770 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2771 // pointer to a (potentially qualified) interface type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002772 const ObjCObjectPointerType *OPT;
John McCall10eae182009-11-30 22:42:35 +00002773 if (!IsArrow && (OPT = BaseType->getAsObjCInterfacePointerType())) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002774 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2775 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlssonf571c112009-08-26 18:25:21 +00002776 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002777
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002778 // Search for a declared property first.
Anders Carlssonf571c112009-08-26 18:25:21 +00002779 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002780 // Check whether we can reference this property.
2781 if (DiagnoseUseOfDecl(PD, MemberLoc))
2782 return ExprError();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002783 QualType ResTy = PD->getType();
Anders Carlssonf571c112009-08-26 18:25:21 +00002784 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002785 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianfe9e3942009-05-08 20:20:55 +00002786 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2787 ResTy = Getter->getResultType();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002788 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner43df5562009-02-16 18:35:08 +00002789 MemberLoc, BaseExpr));
2790 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002791 // Check protocols on qualified interfaces.
Steve Naroffaccc4882009-07-20 17:56:53 +00002792 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2793 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00002794 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002795 // Check whether we can reference this property.
2796 if (DiagnoseUseOfDecl(PD, MemberLoc))
2797 return ExprError();
Chris Lattner43df5562009-02-16 18:35:08 +00002798
Steve Narofff6009ed2009-01-21 00:14:39 +00002799 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner43df5562009-02-16 18:35:08 +00002800 MemberLoc, BaseExpr));
2801 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002802 // If that failed, look for an "implicit" property by seeing if the nullary
2803 // selector is implemented.
2804
2805 // FIXME: The logic for looking up nullary and unary selectors should be
2806 // shared with the code in ActOnInstanceMessage.
2807
Anders Carlssonf571c112009-08-26 18:25:21 +00002808 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002809 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002810
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002811 // If this reference is in an @implementation, check for 'private' methods.
2812 if (!Getter)
Steve Naroffbb69c942009-10-01 23:46:04 +00002813 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002814
Steve Naroff1df62692008-10-22 19:16:27 +00002815 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002816 if (!Getter)
2817 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002818 if (Getter) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002819 // Check if we can reference this property.
2820 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2821 return ExprError();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002822 }
2823 // If we found a getter then this may be a valid dot-reference, we
2824 // will look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00002825 Selector SetterSel =
2826 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00002827 PP.getSelectorTable(), Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002828 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002829 if (!Setter) {
2830 // If this reference is in an @implementation, also check for 'private'
2831 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002832 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002833 }
2834 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002835 if (!Setter)
2836 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002837
Steve Naroff1d984fe2009-03-11 13:48:17 +00002838 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2839 return ExprError();
2840
2841 if (Getter || Setter) {
2842 QualType PType;
2843
2844 if (Getter)
2845 PType = Getter->getResultType();
Fariborz Jahanian88cc2342009-08-18 20:50:23 +00002846 else
2847 // Get the expression type from Setter's incoming parameter.
2848 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002849 // FIXME: we must check that the setter has property type.
Fariborz Jahanian9a846652009-08-20 17:02:02 +00002850 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1d984fe2009-03-11 13:48:17 +00002851 Setter, MemberLoc, BaseExpr));
2852 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002853 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002854 << MemberName << BaseType);
Fariborz Jahanian21f54ee2007-11-12 22:29:28 +00002855 }
Mike Stump11289f42009-09-09 15:08:12 +00002856
Steve Naroffe87026a2009-07-24 17:54:45 +00002857 // Handle the following exceptional case (*Obj).isa.
John McCall10eae182009-11-30 22:42:35 +00002858 if (!IsArrow &&
Steve Naroffe87026a2009-07-24 17:54:45 +00002859 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlssonf571c112009-08-26 18:25:21 +00002860 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00002861 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2862 Context.getObjCIdType()));
2863
Chris Lattnerb63a7452008-07-21 04:28:12 +00002864 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002865 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002866 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00002867 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2868 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002869 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00002870 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00002871 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00002872 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002873
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002874 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2875 << BaseType << BaseExpr->getSourceRange();
2876
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002877 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00002878}
2879
John McCall10eae182009-11-30 22:42:35 +00002880static Sema::OwningExprResult DiagnoseDtorReference(Sema &SemaRef,
2881 SourceLocation NameLoc,
2882 Sema::ExprArg MemExpr) {
2883 Expr *E = (Expr *) MemExpr.get();
2884 SourceLocation ExpectedLParenLoc = SemaRef.PP.getLocForEndOfToken(NameLoc);
2885 SemaRef.Diag(E->getLocStart(), diag::err_dtor_expr_without_call)
Douglas Gregor30d60cb2009-11-03 19:44:04 +00002886 << isa<CXXPseudoDestructorExpr>(E)
2887 << CodeModificationHint::CreateInsertion(ExpectedLParenLoc, "()");
2888
John McCall10eae182009-11-30 22:42:35 +00002889 return SemaRef.ActOnCallExpr(/*Scope*/ 0,
2890 move(MemExpr),
2891 /*LPLoc*/ ExpectedLParenLoc,
2892 Sema::MultiExprArg(SemaRef, 0, 0),
2893 /*CommaLocs*/ 0,
2894 /*RPLoc*/ ExpectedLParenLoc);
2895}
2896
2897/// The main callback when the parser finds something like
2898/// expression . [nested-name-specifier] identifier
2899/// expression -> [nested-name-specifier] identifier
2900/// where 'identifier' encompasses a fairly broad spectrum of
2901/// possibilities, including destructor and operator references.
2902///
2903/// \param OpKind either tok::arrow or tok::period
2904/// \param HasTrailingLParen whether the next token is '(', which
2905/// is used to diagnose mis-uses of special members that can
2906/// only be called
2907/// \param ObjCImpDecl the current ObjC @implementation decl;
2908/// this is an ugly hack around the fact that ObjC @implementations
2909/// aren't properly put in the context chain
2910Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
2911 SourceLocation OpLoc,
2912 tok::TokenKind OpKind,
2913 const CXXScopeSpec &SS,
2914 UnqualifiedId &Id,
2915 DeclPtrTy ObjCImpDecl,
2916 bool HasTrailingLParen) {
2917 if (SS.isSet() && SS.isInvalid())
2918 return ExprError();
2919
2920 TemplateArgumentListInfo TemplateArgsBuffer;
2921
2922 // Decompose the name into its component parts.
2923 DeclarationName Name;
2924 SourceLocation NameLoc;
2925 const TemplateArgumentListInfo *TemplateArgs;
2926 DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
2927 Name, NameLoc, TemplateArgs);
2928
2929 bool IsArrow = (OpKind == tok::arrow);
2930
2931 NamedDecl *FirstQualifierInScope
2932 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
2933 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
2934
2935 // This is a postfix expression, so get rid of ParenListExprs.
2936 BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
2937
2938 Expr *Base = BaseArg.takeAs<Expr>();
2939 OwningExprResult Result(*this);
2940 if (Base->getType()->isDependentType()) {
John McCall2d74de92009-12-01 22:10:20 +00002941 Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
John McCall10eae182009-11-30 22:42:35 +00002942 IsArrow, OpLoc,
2943 SS, FirstQualifierInScope,
2944 Name, NameLoc,
2945 TemplateArgs);
2946 } else {
2947 LookupResult R(*this, Name, NameLoc, LookupMemberName);
2948 if (TemplateArgs) {
2949 // Re-use the lookup done for the template name.
2950 DecomposeTemplateName(R, Id);
2951 } else {
2952 Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
2953 SS, FirstQualifierInScope,
2954 ObjCImpDecl);
2955
2956 if (Result.isInvalid()) {
2957 Owned(Base);
2958 return ExprError();
2959 }
2960
2961 if (Result.get()) {
2962 // The only way a reference to a destructor can be used is to
2963 // immediately call it, which falls into this case. If the
2964 // next token is not a '(', produce a diagnostic and build the
2965 // call now.
2966 if (!HasTrailingLParen &&
2967 Id.getKind() == UnqualifiedId::IK_DestructorName)
2968 return DiagnoseDtorReference(*this, NameLoc, move(Result));
2969
2970 return move(Result);
2971 }
2972 }
2973
John McCall2d74de92009-12-01 22:10:20 +00002974 Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
2975 OpLoc, IsArrow, SS, R, TemplateArgs);
John McCall10eae182009-11-30 22:42:35 +00002976 }
2977
2978 return move(Result);
Anders Carlssonf571c112009-08-26 18:25:21 +00002979}
2980
Anders Carlsson355933d2009-08-25 03:49:14 +00002981Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2982 FunctionDecl *FD,
2983 ParmVarDecl *Param) {
2984 if (Param->hasUnparsedDefaultArg()) {
2985 Diag (CallLoc,
2986 diag::err_use_of_default_argument_to_function_declared_later) <<
2987 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00002988 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00002989 diag::note_default_argument_declared_here);
2990 } else {
2991 if (Param->hasUninstantiatedDefaultArg()) {
2992 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2993
2994 // Instantiate the expression.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002995 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson657bad42009-09-05 05:14:19 +00002996
Mike Stump11289f42009-09-09 15:08:12 +00002997 InstantiatingTemplate Inst(*this, CallLoc, Param,
2998 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00002999 ArgList.getInnermost().flat_size());
Anders Carlsson355933d2009-08-25 03:49:14 +00003000
John McCall76d824f2009-08-25 22:02:44 +00003001 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00003002 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00003003 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003004
3005 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson355933d2009-08-25 03:49:14 +00003006 /*FIXME:EqualLoc*/
3007 UninstExpr->getSourceRange().getBegin()))
3008 return ExprError();
3009 }
Mike Stump11289f42009-09-09 15:08:12 +00003010
Anders Carlsson355933d2009-08-25 03:49:14 +00003011 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +00003012
Anders Carlsson355933d2009-08-25 03:49:14 +00003013 // If the default expression creates temporaries, we need to
3014 // push them to the current stack of expression temporaries so they'll
3015 // be properly destroyed.
Mike Stump11289f42009-09-09 15:08:12 +00003016 if (CXXExprWithTemporaries *E
Anders Carlsson355933d2009-08-25 03:49:14 +00003017 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00003018 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson355933d2009-08-25 03:49:14 +00003019 "Can't destroy temporaries in a default argument expr!");
3020 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
3021 ExprTemporaries.push_back(E->getTemporary(I));
3022 }
3023 }
3024
3025 // We already type-checked the argument, so we know it works.
3026 return Owned(CXXDefaultArgExpr::Create(Context, Param));
3027}
3028
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003029/// ConvertArgumentsForCall - Converts the arguments specified in
3030/// Args/NumArgs to the parameter types of the function FDecl with
3031/// function prototype Proto. Call is the call expression itself, and
3032/// Fn is the function expression. For a C++ member function, this
3033/// routine does not attempt to convert the object argument. Returns
3034/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003035bool
3036Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003037 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003038 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003039 Expr **Args, unsigned NumArgs,
3040 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003041 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003042 // assignment, to the types of the corresponding parameter, ...
3043 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003044 bool Invalid = false;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003045
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003046 // If too few arguments are available (and we don't have default
3047 // arguments for the remaining parameters), don't make the call.
3048 if (NumArgs < NumArgsInProto) {
3049 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3050 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3051 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
Ted Kremenek5a201952009-02-07 01:47:29 +00003052 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003053 }
3054
3055 // If too many are passed and not variadic, error on the extras and drop
3056 // them.
3057 if (NumArgs > NumArgsInProto) {
3058 if (!Proto->isVariadic()) {
3059 Diag(Args[NumArgsInProto]->getLocStart(),
3060 diag::err_typecheck_call_too_many_args)
3061 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
3062 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3063 Args[NumArgs-1]->getLocEnd());
3064 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003065 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003066 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003067 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003068 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003069 llvm::SmallVector<Expr *, 8> AllArgs;
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003070 VariadicCallType CallType =
3071 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3072 if (Fn->getType()->isBlockPointerType())
3073 CallType = VariadicBlock; // Block
3074 else if (isa<MemberExpr>(Fn))
3075 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003076 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003077 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003078 if (Invalid)
3079 return true;
3080 unsigned TotalNumArgs = AllArgs.size();
3081 for (unsigned i = 0; i < TotalNumArgs; ++i)
3082 Call->setArg(i, AllArgs[i]);
3083
3084 return false;
3085}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003086
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003087bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3088 FunctionDecl *FDecl,
3089 const FunctionProtoType *Proto,
3090 unsigned FirstProtoArg,
3091 Expr **Args, unsigned NumArgs,
3092 llvm::SmallVector<Expr *, 8> &AllArgs,
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003093 VariadicCallType CallType) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003094 unsigned NumArgsInProto = Proto->getNumArgs();
3095 unsigned NumArgsToCheck = NumArgs;
3096 bool Invalid = false;
3097 if (NumArgs != NumArgsInProto)
3098 // Use default arguments for missing arguments
3099 NumArgsToCheck = NumArgsInProto;
3100 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003101 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003102 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003103 QualType ProtoArgType = Proto->getArgType(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003104
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003105 Expr *Arg;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003106 if (ArgIx < NumArgs) {
3107 Arg = Args[ArgIx++];
3108
Eli Friedman3164fb12009-03-22 22:00:50 +00003109 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3110 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003111 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003112 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003113 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003114
Douglas Gregor58354032008-12-24 00:01:03 +00003115 // Pass the argument.
3116 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3117 return true;
Anders Carlsson78cfaa92009-11-13 04:34:45 +00003118
Anders Carlsson97df0b42009-11-13 17:04:35 +00003119 if (!ProtoArgType->isReferenceType())
3120 Arg = MaybeBindToTemporary(Arg).takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003121 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00003122 ParmVarDecl *Param = FDecl->getParamDecl(i);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003123
Mike Stump11289f42009-09-09 15:08:12 +00003124 OwningExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003125 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003126 if (ArgExpr.isInvalid())
3127 return true;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003128
Anders Carlsson355933d2009-08-25 03:49:14 +00003129 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003130 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003131 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003132 }
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003133
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003134 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003135 if (CallType != VariadicDoesNotApply) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003136 // Promote the arguments (C99 6.5.2.2p7).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003137 for (unsigned i = ArgIx; i < NumArgs; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003138 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00003139 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003140 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003141 }
3142 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003143 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003144}
3145
Douglas Gregorcabea402009-09-22 15:41:20 +00003146/// \brief "Deconstruct" the function argument of a call expression to find
3147/// the underlying declaration (if any), the name of the called function,
3148/// whether argument-dependent lookup is available, whether it has explicit
3149/// template arguments, etc.
3150void Sema::DeconstructCallFunction(Expr *FnExpr,
John McCalld14a8642009-11-21 08:51:07 +00003151 llvm::SmallVectorImpl<NamedDecl*> &Fns,
Douglas Gregorcabea402009-09-22 15:41:20 +00003152 DeclarationName &Name,
3153 NestedNameSpecifier *&Qualifier,
3154 SourceRange &QualifierRange,
3155 bool &ArgumentDependentLookup,
John McCall283b9012009-11-22 00:44:51 +00003156 bool &Overloaded,
Douglas Gregorcabea402009-09-22 15:41:20 +00003157 bool &HasExplicitTemplateArguments,
John McCall6b51f282009-11-23 01:53:49 +00003158 TemplateArgumentListInfo &ExplicitTemplateArgs) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003159 // Set defaults for all of the output parameters.
Douglas Gregorcabea402009-09-22 15:41:20 +00003160 Name = DeclarationName();
3161 Qualifier = 0;
3162 QualifierRange = SourceRange();
John McCalle66edc12009-11-24 19:00:30 +00003163 ArgumentDependentLookup = false;
John McCall283b9012009-11-22 00:44:51 +00003164 Overloaded = false;
Douglas Gregorcabea402009-09-22 15:41:20 +00003165 HasExplicitTemplateArguments = false;
John McCall283b9012009-11-22 00:44:51 +00003166
Douglas Gregorcabea402009-09-22 15:41:20 +00003167 // If we're directly calling a function, get the appropriate declaration.
3168 // Also, in C++, keep track of whether we should perform argument-dependent
3169 // lookup and whether there were any explicitly-specified template arguments.
3170 while (true) {
3171 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
3172 FnExpr = IcExpr->getSubExpr();
3173 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003174 FnExpr = PExpr->getSubExpr();
3175 } else if (isa<UnaryOperator>(FnExpr) &&
3176 cast<UnaryOperator>(FnExpr)->getOpcode()
3177 == UnaryOperator::AddrOf) {
3178 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregorcabea402009-09-22 15:41:20 +00003179 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
John McCalld14a8642009-11-21 08:51:07 +00003180 Fns.push_back(cast<NamedDecl>(DRExpr->getDecl()));
3181 ArgumentDependentLookup = false;
3182 if ((Qualifier = DRExpr->getQualifier()))
Douglas Gregor4bd90e52009-10-23 18:54:35 +00003183 QualifierRange = DRExpr->getQualifierRange();
Douglas Gregorcabea402009-09-22 15:41:20 +00003184 break;
John McCalld14a8642009-11-21 08:51:07 +00003185 } else if (UnresolvedLookupExpr *UnresLookup
3186 = dyn_cast<UnresolvedLookupExpr>(FnExpr)) {
3187 Name = UnresLookup->getName();
3188 Fns.append(UnresLookup->decls_begin(), UnresLookup->decls_end());
3189 ArgumentDependentLookup = UnresLookup->requiresADL();
John McCall283b9012009-11-22 00:44:51 +00003190 Overloaded = UnresLookup->isOverloaded();
John McCalld14a8642009-11-21 08:51:07 +00003191 if ((Qualifier = UnresLookup->getQualifier()))
3192 QualifierRange = UnresLookup->getQualifierRange();
John McCalle66edc12009-11-24 19:00:30 +00003193 if (UnresLookup->hasExplicitTemplateArgs()) {
3194 HasExplicitTemplateArguments = true;
3195 UnresLookup->copyTemplateArgumentsInto(ExplicitTemplateArgs);
Douglas Gregorcabea402009-09-22 15:41:20 +00003196 }
3197 break;
3198 } else {
Douglas Gregorcabea402009-09-22 15:41:20 +00003199 break;
3200 }
3201 }
3202}
3203
Steve Naroff83895f72007-09-16 03:34:24 +00003204/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003205/// This provides the location of the left/right parens and a list of comma
3206/// locations.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003207Action::OwningExprResult
3208Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3209 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003210 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003211 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003212
3213 // Since this might be a postfix expression, get rid of ParenListExprs.
3214 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump11289f42009-09-09 15:08:12 +00003215
Anders Carlsson3cbc8592009-05-01 19:30:39 +00003216 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003217 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner38dbdb22007-07-21 03:03:59 +00003218 assert(Fn && "no function call expression");
Mike Stump11289f42009-09-09 15:08:12 +00003219
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003220 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003221 // If this is a pseudo-destructor expression, build the call immediately.
3222 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3223 if (NumArgs > 0) {
3224 // Pseudo-destructor calls should not have any arguments.
3225 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3226 << CodeModificationHint::CreateRemoval(
3227 SourceRange(Args[0]->getLocStart(),
3228 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003229
Douglas Gregorad8a3362009-09-04 17:36:40 +00003230 for (unsigned I = 0; I != NumArgs; ++I)
3231 Args[I]->Destroy(Context);
Mike Stump11289f42009-09-09 15:08:12 +00003232
Douglas Gregorad8a3362009-09-04 17:36:40 +00003233 NumArgs = 0;
3234 }
Mike Stump11289f42009-09-09 15:08:12 +00003235
Douglas Gregorad8a3362009-09-04 17:36:40 +00003236 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3237 RParenLoc));
3238 }
Mike Stump11289f42009-09-09 15:08:12 +00003239
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003240 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003241 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003242 // FIXME: Will need to cache the results of name lookup (including ADL) in
3243 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003244 bool Dependent = false;
3245 if (Fn->isTypeDependent())
3246 Dependent = true;
3247 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3248 Dependent = true;
3249
3250 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003251 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003252 Context.DependentTy, RParenLoc));
3253
3254 // Determine whether this is a call to an object (C++ [over.call.object]).
3255 if (Fn->getType()->isRecordType())
3256 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3257 CommaLocs, RParenLoc));
3258
John McCall10eae182009-11-30 22:42:35 +00003259 Expr *NakedFn = Fn->IgnoreParens();
3260
3261 // Determine whether this is a call to an unresolved member function.
3262 if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3263 // If lookup was unresolved but not dependent (i.e. didn't find
3264 // an unresolved using declaration), it has to be an overloaded
3265 // function set, which means it must contain either multiple
3266 // declarations (all methods or method templates) or a single
3267 // method template.
3268 assert((MemE->getNumDecls() > 1) ||
3269 isa<FunctionTemplateDecl>(*MemE->decls_begin()));
Douglas Gregor8f184a32009-12-01 03:34:29 +00003270 (void)MemE;
John McCall10eae182009-11-30 22:42:35 +00003271
John McCall2d74de92009-12-01 22:10:20 +00003272 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3273 CommaLocs, RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003274 }
3275
Douglas Gregore254f902009-02-04 00:32:51 +00003276 // Determine whether this is a call to a member function.
John McCall10eae182009-11-30 22:42:35 +00003277 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003278 NamedDecl *MemDecl = MemExpr->getMemberDecl();
John McCall10eae182009-11-30 22:42:35 +00003279 if (isa<CXXMethodDecl>(MemDecl))
John McCall2d74de92009-12-01 22:10:20 +00003280 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3281 CommaLocs, RParenLoc);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003282 }
Anders Carlsson61914b52009-10-03 17:40:22 +00003283
3284 // Determine whether this is a call to a pointer-to-member function.
John McCall10eae182009-11-30 22:42:35 +00003285 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
Anders Carlsson61914b52009-10-03 17:40:22 +00003286 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3287 BO->getOpcode() == BinaryOperator::PtrMemI) {
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003288 if (const FunctionProtoType *FPT =
3289 dyn_cast<FunctionProtoType>(BO->getType())) {
3290 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson61914b52009-10-03 17:40:22 +00003291
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003292 ExprOwningPtr<CXXMemberCallExpr>
3293 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3294 NumArgs, ResultTy,
3295 RParenLoc));
Anders Carlsson61914b52009-10-03 17:40:22 +00003296
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003297 if (CheckCallReturnType(FPT->getResultType(),
3298 BO->getRHS()->getSourceRange().getBegin(),
3299 TheCall.get(), 0))
3300 return ExprError();
Anders Carlsson63dce022009-10-15 00:41:48 +00003301
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003302 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3303 RParenLoc))
3304 return ExprError();
Anders Carlsson61914b52009-10-03 17:40:22 +00003305
Fariborz Jahanian42f66632009-10-28 16:49:46 +00003306 return Owned(MaybeBindToTemporary(TheCall.release()).release());
3307 }
3308 return ExprError(Diag(Fn->getLocStart(),
3309 diag::err_typecheck_call_not_function)
3310 << Fn->getType() << Fn->getSourceRange());
Anders Carlsson61914b52009-10-03 17:40:22 +00003311 }
3312 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003313 }
3314
Douglas Gregore254f902009-02-04 00:32:51 +00003315 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00003316 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00003317 // lookup and whether there were any explicitly-specified template arguments.
John McCalld14a8642009-11-21 08:51:07 +00003318 llvm::SmallVector<NamedDecl*,8> Fns;
3319 DeclarationName UnqualifiedName;
John McCall283b9012009-11-22 00:44:51 +00003320 bool Overloaded;
3321 bool ADL;
Douglas Gregor89026b52009-06-30 23:57:56 +00003322 bool HasExplicitTemplateArgs = 0;
John McCall6b51f282009-11-23 01:53:49 +00003323 TemplateArgumentListInfo ExplicitTemplateArgs;
Douglas Gregorcabea402009-09-22 15:41:20 +00003324 NestedNameSpecifier *Qualifier = 0;
3325 SourceRange QualifierRange;
John McCalld14a8642009-11-21 08:51:07 +00003326 DeconstructCallFunction(Fn, Fns, UnqualifiedName, Qualifier, QualifierRange,
John McCall283b9012009-11-22 00:44:51 +00003327 ADL, Overloaded, HasExplicitTemplateArgs,
John McCall6b51f282009-11-23 01:53:49 +00003328 ExplicitTemplateArgs);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003329
John McCall283b9012009-11-22 00:44:51 +00003330 NamedDecl *NDecl; // the specific declaration we're calling, if applicable
3331 FunctionDecl *FDecl; // same, if it's known to be a function
John McCalld14a8642009-11-21 08:51:07 +00003332
John McCall283b9012009-11-22 00:44:51 +00003333 if (Overloaded || ADL) {
3334#ifndef NDEBUG
3335 if (ADL) {
3336 // To do ADL, we must have found an unqualified name.
3337 assert(UnqualifiedName && "found no unqualified name for ADL");
3338
3339 // We don't perform ADL for implicit declarations of builtins.
3340 // Verify that this was correctly set up.
3341 if (Fns.size() == 1 && (FDecl = dyn_cast<FunctionDecl>(Fns[0])) &&
3342 FDecl->getBuiltinID() && FDecl->isImplicit())
3343 assert(0 && "performing ADL for builtin");
3344
3345 // We don't perform ADL in C.
3346 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
3347 }
3348
3349 if (Overloaded) {
3350 // To be overloaded, we must either have multiple functions or
3351 // at least one function template (which is effectively an
3352 // infinite set of functions).
3353 assert((Fns.size() > 1 ||
3354 (Fns.size() == 1 &&
3355 isa<FunctionTemplateDecl>(Fns[0]->getUnderlyingDecl())))
3356 && "unrecognized overload situation");
3357 }
3358#endif
3359
3360 FDecl = ResolveOverloadedCallFn(Fn, Fns, UnqualifiedName,
John McCall6b51f282009-11-23 01:53:49 +00003361 (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
John McCall283b9012009-11-22 00:44:51 +00003362 LParenLoc, Args, NumArgs, CommaLocs,
3363 RParenLoc, ADL);
3364 if (!FDecl)
3365 return ExprError();
3366
3367 Fn = FixOverloadedFunctionReference(Fn, FDecl);
3368
3369 NDecl = FDecl;
3370 } else {
3371 assert(Fns.size() <= 1 && "overloaded without Overloaded flag");
3372 if (Fns.empty())
John McCall2d74de92009-12-01 22:10:20 +00003373 NDecl = 0;
John McCall283b9012009-11-22 00:44:51 +00003374 else {
3375 NDecl = Fns[0];
Douglas Gregore254f902009-02-04 00:32:51 +00003376 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003377 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003378
John McCall2d74de92009-12-01 22:10:20 +00003379 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3380}
3381
3382/// BuildCallExpr - Build a call to a resolved expression, i.e. an
3383/// expression not of \p OverloadTy. The expression should
3384/// unary-convert to an expression of function-pointer or
3385/// block-pointer type.
3386///
3387/// \param NDecl the declaration being called, if available
3388Sema::OwningExprResult
3389Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3390 SourceLocation LParenLoc,
3391 Expr **Args, unsigned NumArgs,
3392 SourceLocation RParenLoc) {
3393 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3394
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003395 // Promote the function operand.
3396 UsualUnaryConversions(Fn);
3397
Chris Lattner08464942007-12-28 05:29:59 +00003398 // Make the call expr early, before semantic checks. This guarantees cleanup
3399 // of arguments and function on error.
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003400 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3401 Args, NumArgs,
3402 Context.BoolTy,
3403 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003404
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003405 const FunctionType *FuncT;
3406 if (!Fn->getType()->isBlockPointerType()) {
3407 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3408 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003409 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003410 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003411 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3412 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00003413 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003414 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003415 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00003416 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003417 }
Chris Lattner08464942007-12-28 05:29:59 +00003418 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003419 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3420 << Fn->getType() << Fn->getSourceRange());
3421
Eli Friedman3164fb12009-03-22 22:00:50 +00003422 // Check for a valid return type
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003423 if (CheckCallReturnType(FuncT->getResultType(),
3424 Fn->getSourceRange().getBegin(), TheCall.get(),
3425 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003426 return ExprError();
3427
Chris Lattner08464942007-12-28 05:29:59 +00003428 // We know the result type of the call, set it.
Douglas Gregor786ab212008-10-29 02:00:59 +00003429 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003430
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003431 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00003432 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003433 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003434 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003435 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003436 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003437
Douglas Gregord8e97de2009-04-02 15:37:10 +00003438 if (FDecl) {
3439 // Check if we have too few/too many template arguments, based
3440 // on our knowledge of the function definition.
3441 const FunctionDecl *Def = 0;
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00003442 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003443 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00003444 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003445 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3446 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3447 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3448 }
3449 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00003450 }
3451
Steve Naroff0b661582007-08-28 23:30:39 +00003452 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003453 for (unsigned i = 0; i != NumArgs; i++) {
3454 Expr *Arg = Args[i];
3455 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00003456 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3457 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00003458 PDiag(diag::err_call_incomplete_argument)
3459 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003460 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003461 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003462 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003463 }
Chris Lattner08464942007-12-28 05:29:59 +00003464
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003465 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3466 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003467 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3468 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003469
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003470 // Check for sentinels
3471 if (NDecl)
3472 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003473
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003474 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003475 if (FDecl) {
3476 if (CheckFunctionCall(FDecl, TheCall.get()))
3477 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003478
Douglas Gregor15fc9562009-09-12 00:22:50 +00003479 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003480 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3481 } else if (NDecl) {
3482 if (CheckBlockCall(NDecl, TheCall.get()))
3483 return ExprError();
3484 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003485
Anders Carlssonf8984012009-08-16 03:06:32 +00003486 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00003487}
3488
Sebastian Redlb5d49352009-01-19 22:31:54 +00003489Action::OwningExprResult
3490Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3491 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003492 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003493 //FIXME: Preserve type source info.
3494 QualType literalType = GetTypeFromParser(Ty);
Steve Naroff57eb2c52007-07-19 21:32:11 +00003495 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003496 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb5d49352009-01-19 22:31:54 +00003497 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003498
Eli Friedman37a186d2008-05-20 05:22:08 +00003499 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003500 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003501 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3502 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003503 } else if (!literalType->isDependentType() &&
3504 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003505 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003506 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003507 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003508 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003509
Sebastian Redlb5d49352009-01-19 22:31:54 +00003510 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003511 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003512 return ExprError();
Steve Naroffd32419d2008-01-14 18:19:28 +00003513
Chris Lattner79413952008-12-04 23:50:19 +00003514 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003515 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003516 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003517 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003518 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00003519 InitExpr.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003520 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003521 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003522}
3523
Sebastian Redlb5d49352009-01-19 22:31:54 +00003524Action::OwningExprResult
3525Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003526 SourceLocation RBraceLoc) {
3527 unsigned NumInit = initlist.size();
3528 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003529
Steve Naroff30d242c2007-09-15 18:49:24 +00003530 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003531 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003532
Mike Stump4e1f26a2009-02-19 03:04:26 +00003533 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00003534 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003535 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003536 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003537}
3538
Anders Carlsson094c4592009-10-18 18:12:03 +00003539static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3540 QualType SrcTy, QualType DestTy) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003541 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
Anders Carlsson094c4592009-10-18 18:12:03 +00003542 return CastExpr::CK_NoOp;
3543
3544 if (SrcTy->hasPointerRepresentation()) {
3545 if (DestTy->hasPointerRepresentation())
3546 return CastExpr::CK_BitCast;
3547 if (DestTy->isIntegerType())
3548 return CastExpr::CK_PointerToIntegral;
3549 }
3550
3551 if (SrcTy->isIntegerType()) {
3552 if (DestTy->isIntegerType())
3553 return CastExpr::CK_IntegralCast;
3554 if (DestTy->hasPointerRepresentation())
3555 return CastExpr::CK_IntegralToPointer;
3556 if (DestTy->isRealFloatingType())
3557 return CastExpr::CK_IntegralToFloating;
3558 }
3559
3560 if (SrcTy->isRealFloatingType()) {
3561 if (DestTy->isRealFloatingType())
3562 return CastExpr::CK_FloatingCast;
3563 if (DestTy->isIntegerType())
3564 return CastExpr::CK_FloatingToIntegral;
3565 }
3566
3567 // FIXME: Assert here.
3568 // assert(false && "Unhandled cast combination!");
3569 return CastExpr::CK_Unknown;
3570}
3571
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003572/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003573bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003574 CastExpr::CastKind& Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003575 CXXMethodDecl *& ConversionDecl,
3576 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003577 if (getLangOptions().CPlusPlus)
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003578 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3579 ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003580
Eli Friedmanda8d4de2009-08-15 19:02:19 +00003581 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003582
3583 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3584 // type needs to be scalar.
3585 if (castType->isVoidType()) {
3586 // Cast to void allows any expr type.
Anders Carlssonef918ac2009-10-16 02:35:04 +00003587 Kind = CastExpr::CK_ToVoid;
3588 return false;
3589 }
3590
3591 if (!castType->isScalarType() && !castType->isVectorType()) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003592 if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003593 (castType->isStructureType() || castType->isUnionType())) {
3594 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003595 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003596 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3597 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003598 Kind = CastExpr::CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003599 return false;
3600 }
3601
3602 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003603 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003604 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003605 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003606 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003607 Field != FieldEnd; ++Field) {
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003608 if (Context.hasSameUnqualifiedType(Field->getType(),
3609 castExpr->getType())) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003610 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3611 << castExpr->getSourceRange();
3612 break;
3613 }
3614 }
3615 if (Field == FieldEnd)
3616 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3617 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003618 Kind = CastExpr::CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003619 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003620 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00003621
3622 // Reject any other conversions to non-scalar types.
3623 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3624 << castType << castExpr->getSourceRange();
3625 }
3626
3627 if (!castExpr->getType()->isScalarType() &&
3628 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003629 return Diag(castExpr->getLocStart(),
3630 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003631 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003632 }
3633
Anders Carlsson43d70f82009-10-16 05:23:41 +00003634 if (castType->isExtVectorType())
3635 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3636
Anders Carlsson525b76b2009-10-16 02:48:28 +00003637 if (castType->isVectorType())
3638 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3639 if (castExpr->getType()->isVectorType())
3640 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3641
3642 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffb47acdb2009-04-08 23:52:26 +00003643 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003644
Anders Carlsson43d70f82009-10-16 05:23:41 +00003645 if (isa<ObjCSelectorExpr>(castExpr))
3646 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3647
Anders Carlsson525b76b2009-10-16 02:48:28 +00003648 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003649 QualType castExprType = castExpr->getType();
3650 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3651 return Diag(castExpr->getLocStart(),
3652 diag::err_cast_pointer_from_non_pointer_int)
3653 << castExprType << castExpr->getSourceRange();
3654 } else if (!castExpr->getType()->isArithmeticType()) {
3655 if (!castType->isIntegralType() && castType->isArithmeticType())
3656 return Diag(castExpr->getLocStart(),
3657 diag::err_cast_pointer_to_non_pointer_int)
3658 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003659 }
Anders Carlsson094c4592009-10-18 18:12:03 +00003660
3661 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003662 return false;
3663}
3664
Anders Carlsson525b76b2009-10-16 02:48:28 +00003665bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3666 CastExpr::CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003667 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003668
Anders Carlssonde71adf2007-11-27 05:51:55 +00003669 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003670 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003671 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003672 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003673 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003674 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003675 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003676 } else
3677 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003678 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003679 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003680
Anders Carlsson525b76b2009-10-16 02:48:28 +00003681 Kind = CastExpr::CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003682 return false;
3683}
3684
Anders Carlsson43d70f82009-10-16 05:23:41 +00003685bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3686 CastExpr::CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00003687 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson43d70f82009-10-16 05:23:41 +00003688
3689 QualType SrcTy = CastExpr->getType();
3690
Nate Begemanc8961a42009-06-27 22:05:55 +00003691 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3692 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003693 if (SrcTy->isVectorType()) {
3694 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3695 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3696 << DestTy << SrcTy << R;
Anders Carlsson43d70f82009-10-16 05:23:41 +00003697 Kind = CastExpr::CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00003698 return false;
3699 }
3700
Nate Begemanbd956c42009-06-28 02:36:38 +00003701 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00003702 // conversion will take place first from scalar to elt type, and then
3703 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00003704 if (SrcTy->isPointerType())
3705 return Diag(R.getBegin(),
3706 diag::err_invalid_conversion_between_vector_and_scalar)
3707 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003708
3709 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3710 ImpCastExprToType(CastExpr, DestElemTy,
3711 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson43d70f82009-10-16 05:23:41 +00003712
3713 Kind = CastExpr::CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00003714 return false;
3715}
3716
Sebastian Redlb5d49352009-01-19 22:31:54 +00003717Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00003718Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003719 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssonf10e4142009-08-07 22:21:05 +00003720 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump11289f42009-09-09 15:08:12 +00003721
Sebastian Redlb5d49352009-01-19 22:31:54 +00003722 assert((Ty != 0) && (Op.get() != 0) &&
3723 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00003724
Nate Begeman5ec4b312009-08-10 23:49:36 +00003725 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003726 //FIXME: Preserve type source info.
3727 QualType castType = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003728
Nate Begeman5ec4b312009-08-10 23:49:36 +00003729 // If the Expr being casted is a ParenListExpr, handle it specially.
3730 if (isa<ParenListExpr>(castExpr))
3731 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlssone9766d52009-09-09 21:33:21 +00003732 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003733 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlssone9766d52009-09-09 21:33:21 +00003734 Kind, Method))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003735 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00003736
3737 if (Method) {
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003738 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlssone9766d52009-09-09 21:33:21 +00003739 Method, move(Op));
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003740
Anders Carlssone9766d52009-09-09 21:33:21 +00003741 if (CastArg.isInvalid())
3742 return ExprError();
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003743
Anders Carlssone9766d52009-09-09 21:33:21 +00003744 castExpr = CastArg.takeAs<Expr>();
3745 } else {
3746 Op.release();
Fariborz Jahanian3df87672009-08-29 19:15:16 +00003747 }
Mike Stump11289f42009-09-09 15:08:12 +00003748
Sebastian Redl9f831db2009-07-25 15:41:38 +00003749 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump11289f42009-09-09 15:08:12 +00003750 Kind, castExpr, castType,
Anders Carlssonf10e4142009-08-07 22:21:05 +00003751 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003752}
3753
Nate Begeman5ec4b312009-08-10 23:49:36 +00003754/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3755/// of comma binary operators.
3756Action::OwningExprResult
3757Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3758 Expr *expr = EA.takeAs<Expr>();
3759 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3760 if (!E)
3761 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00003762
Nate Begeman5ec4b312009-08-10 23:49:36 +00003763 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00003764
Nate Begeman5ec4b312009-08-10 23:49:36 +00003765 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3766 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3767 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00003768
Nate Begeman5ec4b312009-08-10 23:49:36 +00003769 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3770}
3771
3772Action::OwningExprResult
3773Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3774 SourceLocation RParenLoc, ExprArg Op,
3775 QualType Ty) {
3776 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump11289f42009-09-09 15:08:12 +00003777
3778 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman5ec4b312009-08-10 23:49:36 +00003779 // then handle it as such.
3780 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3781 if (PE->getNumExprs() == 0) {
3782 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3783 return ExprError();
3784 }
3785
3786 llvm::SmallVector<Expr *, 8> initExprs;
3787 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3788 initExprs.push_back(PE->getExpr(i));
3789
3790 // FIXME: This means that pretty-printing the final AST will produce curly
3791 // braces instead of the original commas.
3792 Op.release();
Mike Stump11289f42009-09-09 15:08:12 +00003793 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00003794 initExprs.size(), RParenLoc);
3795 E->setType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003796 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003797 Owned(E));
3798 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003799 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00003800 // sequence of BinOp comma operators.
3801 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3802 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3803 }
3804}
3805
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003806Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003807 SourceLocation R,
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003808 MultiExprArg Val,
3809 TypeTy *TypeOfCast) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003810 unsigned nexprs = Val.size();
3811 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00003812 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
3813 Expr *expr;
3814 if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
3815 expr = new (Context) ParenExpr(L, R, exprs[0]);
3816 else
3817 expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00003818 return Owned(expr);
3819}
3820
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003821/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3822/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00003823/// C99 6.5.15
3824QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3825 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003826 // C++ is sufficiently different to merit its own checker.
3827 if (getLangOptions().CPlusPlus)
3828 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3829
John McCall1fa36b72009-11-05 09:23:39 +00003830 CheckSignCompare(LHS, RHS, QuestionLoc, diag::warn_mixed_sign_conditional);
3831
Chris Lattner432cff52009-02-18 04:28:32 +00003832 UsualUnaryConversions(Cond);
3833 UsualUnaryConversions(LHS);
3834 UsualUnaryConversions(RHS);
3835 QualType CondTy = Cond->getType();
3836 QualType LHSTy = LHS->getType();
3837 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00003838
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003839 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003840 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3841 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3842 << CondTy;
3843 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003844 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003845
Chris Lattnere2949f42008-01-06 22:42:25 +00003846 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00003847 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3848 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00003849
Chris Lattnere2949f42008-01-06 22:42:25 +00003850 // If both operands have arithmetic type, do the usual arithmetic conversions
3851 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00003852 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3853 UsualArithmeticConversions(LHS, RHS);
3854 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00003855 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003856
Chris Lattnere2949f42008-01-06 22:42:25 +00003857 // If both operands are the same structure or union type, the result is that
3858 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003859 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3860 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00003861 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00003862 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00003863 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00003864 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00003865 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003866 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003867
Chris Lattnere2949f42008-01-06 22:42:25 +00003868 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00003869 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00003870 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3871 if (!LHSTy->isVoidType())
3872 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3873 << RHS->getSourceRange();
3874 if (!RHSTy->isVoidType())
3875 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3876 << LHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003877 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3878 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00003879 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00003880 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00003881 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3882 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00003883 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00003884 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003885 // promote the null to a pointer.
3886 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00003887 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003888 }
Steve Naroff6b712a72009-07-14 18:25:06 +00003889 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00003890 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003891 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00003892 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003893 }
David Chisnall9f57c292009-08-17 16:35:33 +00003894 // Handle things like Class and struct objc_class*. Here we case the result
3895 // to the pseudo-builtin, because that will be implicitly cast back to the
3896 // redefinition type if an attempt is made to access its fields.
3897 if (LHSTy->isObjCClassType() &&
3898 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003899 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003900 return LHSTy;
3901 }
3902 if (RHSTy->isObjCClassType() &&
3903 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003904 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003905 return RHSTy;
3906 }
3907 // And the same for struct objc_object* / id
3908 if (LHSTy->isObjCIdType() &&
3909 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003910 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003911 return LHSTy;
3912 }
3913 if (RHSTy->isObjCIdType() &&
3914 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003915 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003916 return RHSTy;
3917 }
Fariborz Jahanian04b258c2009-11-25 23:07:42 +00003918 // And the same for struct objc_selector* / SEL
3919 if (Context.isObjCSelType(LHSTy) &&
3920 (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
3921 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
3922 return LHSTy;
3923 }
3924 if (Context.isObjCSelType(RHSTy) &&
3925 (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
3926 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
3927 return RHSTy;
3928 }
Steve Naroff05efa972009-07-01 14:36:47 +00003929 // Handle block pointer types.
3930 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3931 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3932 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3933 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003934 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3935 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003936 return destType;
3937 }
3938 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3939 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3940 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00003941 }
Steve Naroff05efa972009-07-01 14:36:47 +00003942 // We have 2 block pointer types.
3943 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3944 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00003945 return LHSTy;
3946 }
Steve Naroff05efa972009-07-01 14:36:47 +00003947 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003948 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3949 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003950
Steve Naroff05efa972009-07-01 14:36:47 +00003951 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3952 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00003953 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3954 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3955 // In this situation, we assume void* type. No especially good
3956 // reason, but this is what gcc does, and we do have to pick
3957 // to get a consistent AST.
3958 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003959 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3960 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00003961 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003962 }
Steve Naroff05efa972009-07-01 14:36:47 +00003963 // The block pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00003964 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3965 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00003966 return LHSTy;
3967 }
Steve Naroff05efa972009-07-01 14:36:47 +00003968 // Check constraints for Objective-C object pointers types.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003969 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003970
Steve Naroff05efa972009-07-01 14:36:47 +00003971 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3972 // Two identical object pointer types are always compatible.
3973 return LHSTy;
3974 }
John McCall9dd450b2009-09-21 23:43:11 +00003975 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3976 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
Steve Naroff05efa972009-07-01 14:36:47 +00003977 QualType compositeType = LHSTy;
Mike Stump11289f42009-09-09 15:08:12 +00003978
Steve Naroff05efa972009-07-01 14:36:47 +00003979 // If both operands are interfaces and either operand can be
3980 // assigned to the other, use that type as the composite
3981 // type. This allows
3982 // xxx ? (A*) a : (B*) b
3983 // where B is a subclass of A.
3984 //
3985 // Additionally, as for assignment, if either type is 'id'
3986 // allow silent coercion. Finally, if the types are
3987 // incompatible then make sure to use 'id' as the composite
3988 // type so the result is acceptable for sending messages to.
3989
3990 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3991 // It could return the composite type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003992 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahaniana83c0162009-08-22 22:27:17 +00003993 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003994 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahaniana83c0162009-08-22 22:27:17 +00003995 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump11289f42009-09-09 15:08:12 +00003996 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00003997 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff8e6aee52009-07-23 01:01:38 +00003998 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump11289f42009-09-09 15:08:12 +00003999 // Need to handle "id<xx>" explicitly.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004000 // GCC allows qualified id and any Objective-C type to devolve to
4001 // id. Currently localizing to here until clear this should be
4002 // part of ObjCQualifiedIdTypesAreCompatible.
4003 compositeType = Context.getObjCIdType();
4004 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff05efa972009-07-01 14:36:47 +00004005 compositeType = Context.getObjCIdType();
Fariborz Jahanianef8b8ce2009-10-27 23:02:38 +00004006 } else if (!(compositeType =
4007 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4008 ;
4009 else {
Steve Naroff05efa972009-07-01 14:36:47 +00004010 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4011 << LHSTy << RHSTy
4012 << LHS->getSourceRange() << RHS->getSourceRange();
4013 QualType incompatTy = Context.getObjCIdType();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004014 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4015 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004016 return incompatTy;
4017 }
4018 // The object pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00004019 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4020 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004021 return compositeType;
4022 }
Steve Naroff85d97152009-07-29 15:09:39 +00004023 // Check Objective-C object pointer types and 'void *'
4024 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004025 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00004026 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004027 QualType destPointee
4028 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff85d97152009-07-29 15:09:39 +00004029 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004030 // Add qualifiers if necessary.
4031 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4032 // Promote to void*.
4033 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff85d97152009-07-29 15:09:39 +00004034 return destType;
4035 }
4036 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
John McCall9dd450b2009-09-21 23:43:11 +00004037 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004038 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004039 QualType destPointee
4040 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff85d97152009-07-29 15:09:39 +00004041 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004042 // Add qualifiers if necessary.
4043 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4044 // Promote to void*.
4045 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff85d97152009-07-29 15:09:39 +00004046 return destType;
4047 }
Steve Naroff05efa972009-07-01 14:36:47 +00004048 // Check constraints for C object pointers types (C99 6.5.15p3,6).
4049 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4050 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004051 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4052 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00004053
4054 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4055 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4056 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00004057 QualType destPointee
4058 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004059 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004060 // Add qualifiers if necessary.
4061 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4062 // Promote to void*.
4063 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004064 return destType;
4065 }
4066 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00004067 QualType destPointee
4068 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00004069 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004070 // Add qualifiers if necessary.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004071 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004072 // Promote to void*.
Eli Friedmanb0bc5592009-11-17 01:22:05 +00004073 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004074 return destType;
4075 }
4076
4077 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4078 // Two identical pointer types are always compatible.
4079 return LHSTy;
4080 }
4081 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4082 rhptee.getUnqualifiedType())) {
4083 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4084 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4085 // In this situation, we assume void* type. No especially good
4086 // reason, but this is what gcc does, and we do have to pick
4087 // to get a consistent AST.
4088 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00004089 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4090 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004091 return incompatTy;
4092 }
4093 // The pointer types are compatible.
4094 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4095 // differently qualified versions of compatible types, the result type is
4096 // a pointer to an appropriately qualified version of the *composite*
4097 // type.
4098 // FIXME: Need to calculate the composite type.
4099 // FIXME: Need to add qualifiers
Eli Friedman06ed2a52009-10-20 08:27:19 +00004100 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4101 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00004102 return LHSTy;
4103 }
Mike Stump11289f42009-09-09 15:08:12 +00004104
Steve Naroff05efa972009-07-01 14:36:47 +00004105 // GCC compatibility: soften pointer/integer mismatch.
4106 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4107 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4108 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004109 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004110 return RHSTy;
4111 }
4112 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4113 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4114 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004115 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00004116 return LHSTy;
4117 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00004118
Chris Lattnere2949f42008-01-06 22:42:25 +00004119 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004120 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4121 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004122 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004123}
4124
Steve Naroff83895f72007-09-16 03:34:24 +00004125/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004126/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004127Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4128 SourceLocation ColonLoc,
4129 ExprArg Cond, ExprArg LHS,
4130 ExprArg RHS) {
4131 Expr *CondExpr = (Expr *) Cond.get();
4132 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00004133
4134 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4135 // was the condition.
4136 bool isLHSNull = LHSExpr == 0;
4137 if (isLHSNull)
4138 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00004139
4140 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00004141 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00004142 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004143 return ExprError();
4144
4145 Cond.release();
4146 LHS.release();
4147 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00004148 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00004149 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00004150 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00004151}
4152
Steve Naroff3f597292007-05-11 22:18:03 +00004153// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00004154// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00004155// routine is it effectively iqnores the qualifiers on the top level pointee.
4156// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4157// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004158Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004159Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00004160 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004161
David Chisnall9f57c292009-08-17 16:35:33 +00004162 if ((lhsType->isObjCClassType() &&
4163 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4164 (rhsType->isObjCClassType() &&
4165 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4166 return Compatible;
4167 }
4168
Steve Naroff1f4d7272007-05-11 04:00:31 +00004169 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004170 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4171 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004172
Steve Naroff1f4d7272007-05-11 04:00:31 +00004173 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00004174 lhptee = Context.getCanonicalType(lhptee);
4175 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00004176
Chris Lattner9bad62c2008-01-04 18:04:52 +00004177 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004178
4179 // C99 6.5.16.1p1: This following citation is common to constraints
4180 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4181 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00004182 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00004183 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004184 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00004185
Mike Stump4e1f26a2009-02-19 03:04:26 +00004186 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4187 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00004188 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00004189 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004190 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004191 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004192
Chris Lattner0a788432008-01-03 22:56:36 +00004193 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004194 assert(rhptee->isFunctionType());
4195 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004196 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004197
Chris Lattner0a788432008-01-03 22:56:36 +00004198 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004199 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00004200 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00004201
4202 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00004203 assert(lhptee->isFunctionType());
4204 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00004205 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004206 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00004207 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00004208 lhptee = lhptee.getUnqualifiedType();
4209 rhptee = rhptee.getUnqualifiedType();
4210 if (!Context.typesAreCompatible(lhptee, rhptee)) {
4211 // Check if the pointee types are compatible ignoring the sign.
4212 // We explicitly check for char so that we catch "char" vs
4213 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00004214 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004215 lhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004216 else if (lhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004217 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004218
4219 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004220 rhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00004221 else if (rhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00004222 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00004223
Eli Friedman80160bd2009-03-22 23:59:44 +00004224 if (lhptee == rhptee) {
4225 // Types are compatible ignoring the sign. Qualifier incompatibility
4226 // takes priority over sign incompatibility because the sign
4227 // warning can be disabled.
4228 if (ConvTy != Compatible)
4229 return ConvTy;
4230 return IncompatiblePointerSign;
4231 }
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004232
4233 // If we are a multi-level pointer, it's possible that our issue is simply
4234 // one of qualification - e.g. char ** -> const char ** is not allowed. If
4235 // the eventual target type is the same and the pointers have the same
4236 // level of indirection, this must be the issue.
4237 if (lhptee->isPointerType() && rhptee->isPointerType()) {
4238 do {
4239 lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4240 rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4241
4242 lhptee = Context.getCanonicalType(lhptee);
4243 rhptee = Context.getCanonicalType(rhptee);
4244 } while (lhptee->isPointerType() && rhptee->isPointerType());
4245
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004246 if (Context.hasSameUnqualifiedType(lhptee, rhptee))
Alexis Hunt6f3de502009-11-08 07:46:34 +00004247 return IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00004248 }
4249
Eli Friedman80160bd2009-03-22 23:59:44 +00004250 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00004251 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00004252 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004253 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00004254}
4255
Steve Naroff081c7422008-09-04 15:10:53 +00004256/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4257/// block pointer types are compatible or whether a block and normal pointer
4258/// are compatible. It is more restrict than comparing two function pointer
4259// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004260Sema::AssignConvertType
4261Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00004262 QualType rhsType) {
4263 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004264
Steve Naroff081c7422008-09-04 15:10:53 +00004265 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004266 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4267 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004268
Steve Naroff081c7422008-09-04 15:10:53 +00004269 // make sure we operate on the canonical type
4270 lhptee = Context.getCanonicalType(lhptee);
4271 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004272
Steve Naroff081c7422008-09-04 15:10:53 +00004273 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004274
Steve Naroff081c7422008-09-04 15:10:53 +00004275 // For blocks we enforce that qualifiers are identical.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004276 if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
Steve Naroff081c7422008-09-04 15:10:53 +00004277 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004278
Eli Friedmana6638ca2009-06-08 05:08:54 +00004279 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004280 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00004281 return ConvTy;
4282}
4283
Mike Stump4e1f26a2009-02-19 03:04:26 +00004284/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4285/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00004286/// pointers. Here are some objectionable examples that GCC considers warnings:
4287///
4288/// int a, *pint;
4289/// short *pshort;
4290/// struct foo *pfoo;
4291///
4292/// pint = pshort; // warning: assignment from incompatible pointer type
4293/// a = pint; // warning: assignment makes integer from pointer without a cast
4294/// pint = a; // warning: assignment makes pointer from integer without a cast
4295/// pint = pfoo; // warning: assignment from incompatible pointer type
4296///
4297/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00004298/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00004299///
Chris Lattner9bad62c2008-01-04 18:04:52 +00004300Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00004301Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00004302 // Get canonical types. We're not formatting these types, just comparing
4303 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00004304 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4305 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00004306
4307 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00004308 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00004309
David Chisnall9f57c292009-08-17 16:35:33 +00004310 if ((lhsType->isObjCClassType() &&
4311 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4312 (rhsType->isObjCClassType() &&
4313 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4314 return Compatible;
4315 }
4316
Douglas Gregor6b754842008-10-28 00:22:11 +00004317 // If the left-hand side is a reference type, then we are in a
4318 // (rare!) case where we've allowed the use of references in C,
4319 // e.g., as a parameter type in a built-in function. In this case,
4320 // just make sure that the type referenced is compatible with the
4321 // right-hand side type. The caller is responsible for adjusting
4322 // lhsType so that the resulting expression does not have reference
4323 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004324 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00004325 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00004326 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004327 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00004328 }
Nate Begemanbd956c42009-06-28 02:36:38 +00004329 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4330 // to the same ExtVector type.
4331 if (lhsType->isExtVectorType()) {
4332 if (rhsType->isExtVectorType())
4333 return lhsType == rhsType ? Compatible : Incompatible;
4334 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
4335 return Compatible;
4336 }
Mike Stump11289f42009-09-09 15:08:12 +00004337
Nate Begeman191a6b12008-07-14 18:02:46 +00004338 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004339 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00004340 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00004341 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00004342 if (getLangOptions().LaxVectorConversions &&
4343 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004344 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004345 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00004346 }
4347 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004348 }
Eli Friedman3360d892008-05-30 18:07:22 +00004349
Chris Lattner881a2122008-01-04 23:32:24 +00004350 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Steve Naroff98cf3e92007-06-06 18:38:38 +00004351 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00004352
Chris Lattnerec646832008-04-07 06:49:41 +00004353 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004354 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004355 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00004356
Chris Lattnerec646832008-04-07 06:49:41 +00004357 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004358 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004359
Steve Naroffaccc4882009-07-20 17:56:53 +00004360 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004361 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004362 if (lhsType->isVoidPointerType()) // an exception to the rule.
4363 return Compatible;
4364 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004365 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004366 if (rhsType->getAs<BlockPointerType>()) {
4367 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004368 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00004369
4370 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004371 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004372 return Compatible;
4373 }
Steve Naroff081c7422008-09-04 15:10:53 +00004374 return Incompatible;
4375 }
4376
4377 if (isa<BlockPointerType>(lhsType)) {
4378 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00004379 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004380
Steve Naroff32d072c2008-09-29 18:10:17 +00004381 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004382 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00004383 return Compatible;
4384
Steve Naroff081c7422008-09-04 15:10:53 +00004385 if (rhsType->isBlockPointerType())
4386 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004387
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004388 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00004389 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004390 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00004391 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00004392 return Incompatible;
4393 }
4394
Steve Naroff7cae42b2009-07-10 23:34:53 +00004395 if (isa<ObjCObjectPointerType>(lhsType)) {
4396 if (rhsType->isIntegerType())
4397 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00004398
Steve Naroffaccc4882009-07-20 17:56:53 +00004399 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004400 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004401 if (rhsType->isVoidPointerType()) // an exception to the rule.
4402 return Compatible;
4403 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004404 }
4405 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff1329fa02009-07-15 18:40:39 +00004406 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
4407 return Compatible;
Steve Naroffaccc4882009-07-20 17:56:53 +00004408 if (Context.typesAreCompatible(lhsType, rhsType))
4409 return Compatible;
Steve Naroff8e6aee52009-07-23 01:01:38 +00004410 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4411 return IncompatibleObjCQualifiedId;
Steve Naroffaccc4882009-07-20 17:56:53 +00004412 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004413 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004414 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00004415 if (RHSPT->getPointeeType()->isVoidType())
4416 return Compatible;
4417 }
4418 // Treat block pointers as objects.
4419 if (rhsType->isBlockPointerType())
4420 return Compatible;
4421 return Incompatible;
4422 }
Chris Lattnerec646832008-04-07 06:49:41 +00004423 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00004424 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00004425 if (lhsType == Context.BoolTy)
4426 return Compatible;
4427
4428 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00004429 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00004430
Mike Stump4e1f26a2009-02-19 03:04:26 +00004431 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004432 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004433
4434 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004435 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00004436 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004437 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00004438 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004439 if (isa<ObjCObjectPointerType>(rhsType)) {
4440 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4441 if (lhsType == Context.BoolTy)
4442 return Compatible;
4443
4444 if (lhsType->isIntegerType())
4445 return PointerToInt;
4446
Steve Naroffaccc4882009-07-20 17:56:53 +00004447 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00004448 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00004449 if (lhsType->isVoidPointerType()) // an exception to the rule.
4450 return Compatible;
4451 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00004452 }
4453 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004454 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00004455 return Compatible;
4456 return Incompatible;
4457 }
Eli Friedman3360d892008-05-30 18:07:22 +00004458
Chris Lattnera52c2f22008-01-04 23:18:45 +00004459 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00004460 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00004461 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00004462 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00004463 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00004464}
4465
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004466/// \brief Constructs a transparent union from an expression that is
4467/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00004468static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004469 QualType UnionType, FieldDecl *Field) {
4470 // Build an initializer list that designates the appropriate member
4471 // of the transparent union.
4472 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
4473 &E, 1,
4474 SourceLocation());
4475 Initializer->setType(UnionType);
4476 Initializer->setInitializedFieldInUnion(Field);
4477
4478 // Build a compound literal constructing a value of the transparent
4479 // union type from this initializer list.
4480 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
4481 false);
4482}
4483
4484Sema::AssignConvertType
4485Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4486 QualType FromType = rExpr->getType();
4487
Mike Stump11289f42009-09-09 15:08:12 +00004488 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004489 // transparent_union GCC extension.
4490 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004491 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004492 return Incompatible;
4493
4494 // The field to initialize within the transparent union.
4495 RecordDecl *UD = UT->getDecl();
4496 FieldDecl *InitField = 0;
4497 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004498 for (RecordDecl::field_iterator it = UD->field_begin(),
4499 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004500 it != itend; ++it) {
4501 if (it->getType()->isPointerType()) {
4502 // If the transparent union contains a pointer type, we allow:
4503 // 1) void pointer
4504 // 2) null pointer constant
4505 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004506 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004507 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004508 InitField = *it;
4509 break;
4510 }
Mike Stump11289f42009-09-09 15:08:12 +00004511
Douglas Gregor56751b52009-09-25 04:25:58 +00004512 if (rExpr->isNullPointerConstant(Context,
4513 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004514 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004515 InitField = *it;
4516 break;
4517 }
4518 }
4519
4520 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4521 == Compatible) {
4522 InitField = *it;
4523 break;
4524 }
4525 }
4526
4527 if (!InitField)
4528 return Incompatible;
4529
4530 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4531 return Compatible;
4532}
4533
Chris Lattner9bad62c2008-01-04 18:04:52 +00004534Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004535Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00004536 if (getLangOptions().CPlusPlus) {
4537 if (!lhsType->isRecordType()) {
4538 // C++ 5.17p3: If the left operand is not of class type, the
4539 // expression is implicitly converted (C++ 4) to the
4540 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00004541 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4542 "assigning"))
Douglas Gregor9a657932008-10-21 23:43:52 +00004543 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00004544 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00004545 }
4546
4547 // FIXME: Currently, we fall through and treat C++ classes like C
4548 // structures.
4549 }
4550
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004551 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4552 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00004553 if ((lhsType->isPointerType() ||
4554 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00004555 lhsType->isBlockPointerType())
Douglas Gregor56751b52009-09-25 04:25:58 +00004556 && rExpr->isNullPointerConstant(Context,
4557 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004558 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004559 return Compatible;
4560 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004561
Chris Lattnere6dcd502007-10-16 02:55:40 +00004562 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004563 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00004564 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004565 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00004566 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00004567 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00004568 if (!lhsType->isReferenceType())
4569 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004570
Chris Lattner9bad62c2008-01-04 18:04:52 +00004571 Sema::AssignConvertType result =
4572 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004573
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004574 // C99 6.5.16.1p2: The value of the right operand is converted to the
4575 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00004576 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4577 // so that we can use references in built-in functions even in C.
4578 // The getNonReferenceType() call makes sure that the resulting expression
4579 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004580 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004581 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4582 CastExpr::CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004583 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004584}
4585
Chris Lattner326f7572008-11-18 01:30:42 +00004586QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004587 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004588 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004589 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004590 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004591}
4592
Mike Stump4e1f26a2009-02-19 03:04:26 +00004593inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff7a5af782007-07-13 16:58:59 +00004594 Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004595 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004596 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004597 QualType lhsType =
4598 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4599 QualType rhsType =
4600 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004601
Nate Begeman191a6b12008-07-14 18:02:46 +00004602 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004603 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004604 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004605
Nate Begeman191a6b12008-07-14 18:02:46 +00004606 // Handle the case of a vector & extvector type of the same size and element
4607 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004608 if (getLangOptions().LaxVectorConversions) {
4609 // FIXME: Should we warn here?
John McCall9dd450b2009-09-21 23:43:11 +00004610 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4611 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begeman191a6b12008-07-14 18:02:46 +00004612 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004613 LV->getNumElements() == RV->getNumElements()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004614 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004615 }
4616 }
4617 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004618
Nate Begemanbd956c42009-06-28 02:36:38 +00004619 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4620 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4621 bool swapped = false;
4622 if (rhsType->isExtVectorType()) {
4623 swapped = true;
4624 std::swap(rex, lex);
4625 std::swap(rhsType, lhsType);
4626 }
Mike Stump11289f42009-09-09 15:08:12 +00004627
Nate Begeman886448d2009-06-28 19:12:57 +00004628 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00004629 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00004630 QualType EltTy = LV->getElementType();
4631 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4632 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004633 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004634 if (swapped) std::swap(rex, lex);
4635 return lhsType;
4636 }
4637 }
4638 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4639 rhsType->isRealFloatingType()) {
4640 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004641 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004642 if (swapped) std::swap(rex, lex);
4643 return lhsType;
4644 }
Nate Begeman330aaa72007-12-30 02:59:45 +00004645 }
4646 }
Mike Stump11289f42009-09-09 15:08:12 +00004647
Nate Begeman886448d2009-06-28 19:12:57 +00004648 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00004649 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004650 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004651 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00004652 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00004653}
4654
Steve Naroff218bc2b2007-05-04 21:54:46 +00004655inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004656 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00004657 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004658 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004659
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004660 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004661
Steve Naroffdbd9e892007-07-17 00:58:39 +00004662 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004663 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004664 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004665}
4666
Steve Naroff218bc2b2007-05-04 21:54:46 +00004667inline QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004668 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00004669 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4670 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4671 return CheckVectorOperands(Loc, lex, rex);
4672 return InvalidOperands(Loc, lex, rex);
4673 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004674
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004675 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004676
Steve Naroffdbd9e892007-07-17 00:58:39 +00004677 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004678 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004679 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004680}
4681
4682inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00004683 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004684 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4685 QualType compType = CheckVectorOperands(Loc, lex, rex);
4686 if (CompLHSTy) *CompLHSTy = compType;
4687 return compType;
4688 }
Steve Naroff7a5af782007-07-13 16:58:59 +00004689
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004690 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00004691
Steve Naroffe4718892007-04-27 18:30:00 +00004692 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004693 if (lex->getType()->isArithmeticType() &&
4694 rex->getType()->isArithmeticType()) {
4695 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004696 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004697 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00004698
Eli Friedman8e122982008-05-18 18:08:51 +00004699 // Put any potential pointer into PExp
4700 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00004701 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00004702 std::swap(PExp, IExp);
4703
Steve Naroff6b712a72009-07-14 18:25:06 +00004704 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004705
Eli Friedman8e122982008-05-18 18:08:51 +00004706 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004707 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004708
Chris Lattner12bdebb2009-04-24 23:50:08 +00004709 // Check for arithmetic on pointers to incomplete types.
4710 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004711 if (getLangOptions().CPlusPlus) {
4712 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00004713 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00004714 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00004715 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004716
4717 // GNU extension: arithmetic on pointer to void
4718 Diag(Loc, diag::ext_gnu_void_ptr)
4719 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00004720 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004721 if (getLangOptions().CPlusPlus) {
4722 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4723 << lex->getType() << lex->getSourceRange();
4724 return QualType();
4725 }
4726
4727 // GNU extension: arithmetic on pointer to function
4728 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4729 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00004730 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004731 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00004732 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00004733 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004734 PExp->getType()->isObjCObjectPointerType()) &&
4735 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00004736 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4737 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004738 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004739 return QualType();
4740 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00004741 // Diagnose bad cases where we step over interface counts.
4742 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4743 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4744 << PointeeTy << PExp->getSourceRange();
4745 return QualType();
4746 }
Mike Stump11289f42009-09-09 15:08:12 +00004747
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004748 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00004749 QualType LHSTy = Context.isPromotableBitField(lex);
4750 if (LHSTy.isNull()) {
4751 LHSTy = lex->getType();
4752 if (LHSTy->isPromotableIntegerType())
4753 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004754 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004755 *CompLHSTy = LHSTy;
4756 }
Eli Friedman8e122982008-05-18 18:08:51 +00004757 return PExp->getType();
4758 }
4759 }
4760
Chris Lattner326f7572008-11-18 01:30:42 +00004761 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004762}
4763
Chris Lattner2a3569b2008-04-07 05:30:13 +00004764// C99 6.5.6
4765QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004766 SourceLocation Loc, QualType* CompLHSTy) {
4767 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4768 QualType compType = CheckVectorOperands(Loc, lex, rex);
4769 if (CompLHSTy) *CompLHSTy = compType;
4770 return compType;
4771 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004772
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004773 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004774
Chris Lattner4d62f422007-12-09 21:53:25 +00004775 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004776
Chris Lattner4d62f422007-12-09 21:53:25 +00004777 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00004778 if (lex->getType()->isArithmeticType()
4779 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004780 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004781 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004782 }
Mike Stump11289f42009-09-09 15:08:12 +00004783
Chris Lattner4d62f422007-12-09 21:53:25 +00004784 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00004785 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00004786 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004787
Douglas Gregorac1fb652009-03-24 19:52:54 +00004788 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00004789
Douglas Gregorac1fb652009-03-24 19:52:54 +00004790 bool ComplainAboutVoid = false;
4791 Expr *ComplainAboutFunc = 0;
4792 if (lpointee->isVoidType()) {
4793 if (getLangOptions().CPlusPlus) {
4794 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4795 << lex->getSourceRange() << rex->getSourceRange();
4796 return QualType();
4797 }
4798
4799 // GNU C extension: arithmetic on pointer to void
4800 ComplainAboutVoid = true;
4801 } else if (lpointee->isFunctionType()) {
4802 if (getLangOptions().CPlusPlus) {
4803 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004804 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004805 return QualType();
4806 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004807
4808 // GNU C extension: arithmetic on pointer to function
4809 ComplainAboutFunc = lex;
4810 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00004811 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004812 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00004813 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004814 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004815 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004816
Chris Lattner12bdebb2009-04-24 23:50:08 +00004817 // Diagnose bad cases where we step over interface counts.
4818 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4819 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4820 << lpointee << lex->getSourceRange();
4821 return QualType();
4822 }
Mike Stump11289f42009-09-09 15:08:12 +00004823
Chris Lattner4d62f422007-12-09 21:53:25 +00004824 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00004825 if (rex->getType()->isIntegerType()) {
4826 if (ComplainAboutVoid)
4827 Diag(Loc, diag::ext_gnu_void_ptr)
4828 << lex->getSourceRange() << rex->getSourceRange();
4829 if (ComplainAboutFunc)
4830 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004831 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004832 << ComplainAboutFunc->getSourceRange();
4833
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004834 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004835 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00004836 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004837
Chris Lattner4d62f422007-12-09 21:53:25 +00004838 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004839 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00004840 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004841
Douglas Gregorac1fb652009-03-24 19:52:54 +00004842 // RHS must be a completely-type object type.
4843 // Handle the GNU void* extension.
4844 if (rpointee->isVoidType()) {
4845 if (getLangOptions().CPlusPlus) {
4846 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4847 << lex->getSourceRange() << rex->getSourceRange();
4848 return QualType();
4849 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004850
Douglas Gregorac1fb652009-03-24 19:52:54 +00004851 ComplainAboutVoid = true;
4852 } else if (rpointee->isFunctionType()) {
4853 if (getLangOptions().CPlusPlus) {
4854 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004855 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004856 return QualType();
4857 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004858
4859 // GNU extension: arithmetic on pointer to function
4860 if (!ComplainAboutFunc)
4861 ComplainAboutFunc = rex;
4862 } else if (!rpointee->isDependentType() &&
4863 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004864 PDiag(diag::err_typecheck_sub_ptr_object)
4865 << rex->getSourceRange()
4866 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004867 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004868
Eli Friedman168fe152009-05-16 13:54:38 +00004869 if (getLangOptions().CPlusPlus) {
4870 // Pointee types must be the same: C++ [expr.add]
4871 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4872 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4873 << lex->getType() << rex->getType()
4874 << lex->getSourceRange() << rex->getSourceRange();
4875 return QualType();
4876 }
4877 } else {
4878 // Pointee types must be compatible C99 6.5.6p3
4879 if (!Context.typesAreCompatible(
4880 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4881 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4882 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4883 << lex->getType() << rex->getType()
4884 << lex->getSourceRange() << rex->getSourceRange();
4885 return QualType();
4886 }
Chris Lattner4d62f422007-12-09 21:53:25 +00004887 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004888
Douglas Gregorac1fb652009-03-24 19:52:54 +00004889 if (ComplainAboutVoid)
4890 Diag(Loc, diag::ext_gnu_void_ptr)
4891 << lex->getSourceRange() << rex->getSourceRange();
4892 if (ComplainAboutFunc)
4893 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004894 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004895 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004896
4897 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004898 return Context.getPointerDiffType();
4899 }
4900 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004901
Chris Lattner326f7572008-11-18 01:30:42 +00004902 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004903}
4904
Chris Lattner2a3569b2008-04-07 05:30:13 +00004905// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00004906QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00004907 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00004908 // C99 6.5.7p2: Each of the operands shall have integer type.
4909 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00004910 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004911
Nate Begemane46ee9a2009-10-25 02:26:48 +00004912 // Vector shifts promote their scalar inputs to vector type.
4913 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4914 return CheckVectorOperands(Loc, lex, rex);
4915
Chris Lattner5c11c412007-12-12 05:47:28 +00004916 // Shifts don't perform usual arithmetic conversions, they just do integer
4917 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00004918 QualType LHSTy = Context.isPromotableBitField(lex);
4919 if (LHSTy.isNull()) {
4920 LHSTy = lex->getType();
4921 if (LHSTy->isPromotableIntegerType())
4922 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004923 }
Chris Lattner3c133402007-12-13 07:28:16 +00004924 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004925 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004926
Chris Lattner5c11c412007-12-12 05:47:28 +00004927 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004928
Ryan Flynnf53fab82009-08-07 16:20:20 +00004929 // Sanity-check shift operands
4930 llvm::APSInt Right;
4931 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00004932 if (!rex->isValueDependent() &&
4933 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00004934 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00004935 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4936 else {
4937 llvm::APInt LeftBits(Right.getBitWidth(),
4938 Context.getTypeSize(lex->getType()));
4939 if (Right.uge(LeftBits))
4940 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4941 }
4942 }
4943
Chris Lattner5c11c412007-12-12 05:47:28 +00004944 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004945 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00004946}
4947
John McCall99ce6bf2009-11-06 08:49:08 +00004948/// \brief Implements -Wsign-compare.
4949///
4950/// \param lex the left-hand expression
4951/// \param rex the right-hand expression
4952/// \param OpLoc the location of the joining operator
John McCalle46fd852009-11-06 08:53:51 +00004953/// \param Equality whether this is an "equality-like" join, which
4954/// suppresses the warning in some cases
John McCall1fa36b72009-11-05 09:23:39 +00004955void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCall99ce6bf2009-11-06 08:49:08 +00004956 const PartialDiagnostic &PD, bool Equality) {
John McCalle2c91e62009-11-06 18:16:06 +00004957 // Don't warn if we're in an unevaluated context.
Douglas Gregorff790f12009-11-26 00:44:06 +00004958 if (ExprEvalContexts.back().Context == Unevaluated)
John McCalle2c91e62009-11-06 18:16:06 +00004959 return;
4960
John McCall644a4182009-11-05 00:40:04 +00004961 QualType lt = lex->getType(), rt = rex->getType();
4962
4963 // Only warn if both operands are integral.
4964 if (!lt->isIntegerType() || !rt->isIntegerType())
4965 return;
4966
Sebastian Redl0b7c85f2009-11-05 21:09:23 +00004967 // If either expression is value-dependent, don't warn. We'll get another
4968 // chance at instantiation time.
4969 if (lex->isValueDependent() || rex->isValueDependent())
4970 return;
4971
John McCall644a4182009-11-05 00:40:04 +00004972 // The rule is that the signed operand becomes unsigned, so isolate the
4973 // signed operand.
John McCall99ce6bf2009-11-06 08:49:08 +00004974 Expr *signedOperand, *unsignedOperand;
John McCall644a4182009-11-05 00:40:04 +00004975 if (lt->isSignedIntegerType()) {
4976 if (rt->isSignedIntegerType()) return;
4977 signedOperand = lex;
John McCall99ce6bf2009-11-06 08:49:08 +00004978 unsignedOperand = rex;
John McCall644a4182009-11-05 00:40:04 +00004979 } else {
4980 if (!rt->isSignedIntegerType()) return;
4981 signedOperand = rex;
John McCall99ce6bf2009-11-06 08:49:08 +00004982 unsignedOperand = lex;
John McCall644a4182009-11-05 00:40:04 +00004983 }
4984
John McCall99ce6bf2009-11-06 08:49:08 +00004985 // If the unsigned type is strictly smaller than the signed type,
John McCalle46fd852009-11-06 08:53:51 +00004986 // then (1) the result type will be signed and (2) the unsigned
4987 // value will fit fully within the signed type, and thus the result
John McCall99ce6bf2009-11-06 08:49:08 +00004988 // of the comparison will be exact.
4989 if (Context.getIntWidth(signedOperand->getType()) >
4990 Context.getIntWidth(unsignedOperand->getType()))
4991 return;
4992
John McCall644a4182009-11-05 00:40:04 +00004993 // If the value is a non-negative integer constant, then the
4994 // signed->unsigned conversion won't change it.
4995 llvm::APSInt value;
John McCall1fa36b72009-11-05 09:23:39 +00004996 if (signedOperand->isIntegerConstantExpr(value, Context)) {
John McCall644a4182009-11-05 00:40:04 +00004997 assert(value.isSigned() && "result of signed expression not signed");
4998
4999 if (value.isNonNegative())
5000 return;
5001 }
5002
John McCall99ce6bf2009-11-06 08:49:08 +00005003 if (Equality) {
5004 // For (in)equality comparisons, if the unsigned operand is a
John McCalle46fd852009-11-06 08:53:51 +00005005 // constant which cannot collide with a overflowed signed operand,
5006 // then reinterpreting the signed operand as unsigned will not
5007 // change the result of the comparison.
John McCall99ce6bf2009-11-06 08:49:08 +00005008 if (unsignedOperand->isIntegerConstantExpr(value, Context)) {
5009 assert(!value.isSigned() && "result of unsigned expression is signed");
5010
5011 // 2's complement: test the top bit.
5012 if (value.isNonNegative())
5013 return;
5014 }
5015 }
5016
John McCall1fa36b72009-11-05 09:23:39 +00005017 Diag(OpLoc, PD)
John McCall644a4182009-11-05 00:40:04 +00005018 << lex->getType() << rex->getType()
5019 << lex->getSourceRange() << rex->getSourceRange();
5020}
5021
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005022// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00005023QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005024 unsigned OpaqueOpc, bool isRelational) {
5025 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5026
Chris Lattner9a152e22009-12-05 05:40:13 +00005027 // Handle vector comparisons separately.
Nate Begeman191a6b12008-07-14 18:02:46 +00005028 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005029 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005030
John McCall99ce6bf2009-11-06 08:49:08 +00005031 CheckSignCompare(lex, rex, Loc, diag::warn_mixed_sign_comparison,
5032 (Opc == BinaryOperator::EQ || Opc == BinaryOperator::NE));
John McCall644a4182009-11-05 00:40:04 +00005033
Chris Lattnerb620c342007-08-26 01:18:55 +00005034 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff47fea352007-08-10 18:26:40 +00005035 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5036 UsualArithmeticConversions(lex, rex);
5037 else {
5038 UsualUnaryConversions(lex);
5039 UsualUnaryConversions(rex);
5040 }
Steve Naroff31090012007-07-16 21:54:35 +00005041 QualType lType = lex->getType();
5042 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005043
Mike Stumpf70bcf72009-05-07 18:43:07 +00005044 if (!lType->isFloatingType()
5045 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00005046 // For non-floating point types, check for self-comparisons of the form
5047 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5048 // often indicate logic errors in the program.
Mike Stump11289f42009-09-09 15:08:12 +00005049 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenekde9e9682009-03-20 19:57:37 +00005050 // from macro expansions, and are usually quite deliberate.
Chris Lattner222b8bd2009-03-08 19:39:53 +00005051 Expr *LHSStripped = lex->IgnoreParens();
5052 Expr *RHSStripped = rex->IgnoreParens();
5053 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5054 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek9ffbe412009-03-20 18:35:45 +00005055 if (DRL->getDecl() == DRR->getDecl() &&
5056 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump4e1f26a2009-02-19 03:04:26 +00005057 Diag(Loc, diag::warn_selfcomparison);
Mike Stump11289f42009-09-09 15:08:12 +00005058
Chris Lattner222b8bd2009-03-08 19:39:53 +00005059 if (isa<CastExpr>(LHSStripped))
5060 LHSStripped = LHSStripped->IgnoreParenCasts();
5061 if (isa<CastExpr>(RHSStripped))
5062 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00005063
Chris Lattner222b8bd2009-03-08 19:39:53 +00005064 // Warn about comparisons against a string constant (unless the other
5065 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005066 Expr *literalString = 0;
5067 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00005068 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005069 !RHSStripped->isNullPointerConstant(Context,
5070 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005071 literalString = lex;
5072 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00005073 } else if ((isa<StringLiteral>(RHSStripped) ||
5074 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00005075 !LHSStripped->isNullPointerConstant(Context,
5076 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005077 literalString = rex;
5078 literalStringStripped = RHSStripped;
5079 }
5080
5081 if (literalString) {
5082 std::string resultComparison;
5083 switch (Opc) {
5084 case BinaryOperator::LT: resultComparison = ") < 0"; break;
5085 case BinaryOperator::GT: resultComparison = ") > 0"; break;
5086 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5087 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5088 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5089 case BinaryOperator::NE: resultComparison = ") != 0"; break;
5090 default: assert(false && "Invalid comparison operator");
5091 }
5092 Diag(Loc, diag::warn_stringcompare)
5093 << isa<ObjCEncodeExpr>(literalStringStripped)
5094 << literalString->getSourceRange()
Douglas Gregor170512f2009-04-01 23:51:29 +00005095 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
5096 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
5097 "strcmp(")
5098 << CodeModificationHint::CreateInsertion(
5099 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005100 resultComparison);
5101 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00005102 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005103
Douglas Gregorca63811b2008-11-19 03:25:36 +00005104 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner9a152e22009-12-05 05:40:13 +00005105 QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00005106
Chris Lattnerb620c342007-08-26 01:18:55 +00005107 if (isRelational) {
5108 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005109 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005110 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00005111 // Check for comparisons of floating point operands using != and ==.
Chris Lattner9a152e22009-12-05 05:40:13 +00005112 if (lType->isFloatingType() && rType->isFloatingType())
Chris Lattner326f7572008-11-18 01:30:42 +00005113 CheckFloatComparison(Loc,lex,rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005114
Chris Lattnerb620c342007-08-26 01:18:55 +00005115 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00005116 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00005117 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005118
Douglas Gregor56751b52009-09-25 04:25:58 +00005119 bool LHSIsNull = lex->isNullPointerConstant(Context,
5120 Expr::NPC_ValueDependentIsNull);
5121 bool RHSIsNull = rex->isNullPointerConstant(Context,
5122 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005123
Chris Lattnerb620c342007-08-26 01:18:55 +00005124 // All of the following pointer related warnings are GCC extensions, except
5125 // when handling null pointer constants. One day, we can consider making them
5126 // errors (when -pedantic-errors is enabled).
Steve Naroff808eb8f2007-08-27 04:08:11 +00005127 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00005128 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005129 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00005130 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005131 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005132
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005133 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00005134 if (LCanPointeeTy == RCanPointeeTy)
5135 return ResultTy;
5136
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005137 // C++ [expr.rel]p2:
5138 // [...] Pointer conversions (4.10) and qualification
5139 // conversions (4.4) are performed on pointer operands (or on
5140 // a pointer operand and a null pointer constant) to bring
5141 // them to their composite pointer type. [...]
5142 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005143 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005144 // comparisons of pointers.
Douglas Gregorb8420462009-05-05 04:50:50 +00005145 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005146 if (T.isNull()) {
5147 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5148 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5149 return QualType();
5150 }
5151
Eli Friedman06ed2a52009-10-20 08:27:19 +00005152 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5153 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00005154 return ResultTy;
5155 }
Eli Friedman16c209612009-08-23 00:27:47 +00005156 // C99 6.5.9p2 and C99 6.5.8p2
5157 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5158 RCanPointeeTy.getUnqualifiedType())) {
5159 // Valid unless a relational comparison of function pointers
5160 if (isRelational && LCanPointeeTy->isFunctionType()) {
5161 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5162 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5163 }
5164 } else if (!isRelational &&
5165 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5166 // Valid unless comparison between non-null pointer and function pointer
5167 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5168 && !LHSIsNull && !RHSIsNull) {
5169 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5170 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5171 }
5172 } else {
5173 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00005174 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005175 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00005176 }
Eli Friedman16c209612009-08-23 00:27:47 +00005177 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman06ed2a52009-10-20 08:27:19 +00005178 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005179 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005180 }
Mike Stump11289f42009-09-09 15:08:12 +00005181
Sebastian Redl576fd422009-05-10 18:38:11 +00005182 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00005183 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005184 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00005185 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005186 (lType->isPointerType() ||
5187 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005188 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005189 return ResultTy;
5190 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005191 if (LHSIsNull &&
5192 (rType->isPointerType() ||
5193 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00005194 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00005195 return ResultTy;
5196 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005197
5198 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00005199 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005200 lType->isMemberPointerType() && rType->isMemberPointerType()) {
5201 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005202 // In addition, pointers to members can be compared, or a pointer to
5203 // member and a null pointer constant. Pointer to member conversions
5204 // (4.11) and qualification conversions (4.4) are performed to bring
5205 // them to a common type. If one operand is a null pointer constant,
5206 // the common type is the type of the other operand. Otherwise, the
5207 // common type is a pointer to member type similar (4.4) to the type
5208 // of one of the operands, with a cv-qualification signature (4.4)
5209 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005210 // types.
5211 QualType T = FindCompositePointerType(lex, rex);
5212 if (T.isNull()) {
5213 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5214 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5215 return QualType();
5216 }
Mike Stump11289f42009-09-09 15:08:12 +00005217
Eli Friedman06ed2a52009-10-20 08:27:19 +00005218 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5219 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005220 return ResultTy;
5221 }
Mike Stump11289f42009-09-09 15:08:12 +00005222
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005223 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00005224 if (lType->isNullPtrType() && rType->isNullPtrType())
5225 return ResultTy;
5226 }
Mike Stump11289f42009-09-09 15:08:12 +00005227
Steve Naroff081c7422008-09-04 15:10:53 +00005228 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00005229 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005230 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5231 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005232
Steve Naroff081c7422008-09-04 15:10:53 +00005233 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00005234 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005235 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005236 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00005237 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005238 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005239 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00005240 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00005241 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00005242 if (!isRelational
5243 && ((lType->isBlockPointerType() && rType->isPointerType())
5244 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00005245 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005246 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005247 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005248 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00005249 ->getPointeeType()->isVoidType())))
5250 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5251 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00005252 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005253 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005254 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00005255 }
Steve Naroff081c7422008-09-04 15:10:53 +00005256
Steve Naroff7cae42b2009-07-10 23:34:53 +00005257 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005258 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005259 const PointerType *LPT = lType->getAs<PointerType>();
5260 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005261 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005262 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005263 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00005264 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005265
Steve Naroff753567f2008-11-17 19:49:16 +00005266 if (!LPtrToVoid && !RPtrToVoid &&
5267 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005268 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005269 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00005270 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005271 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005272 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00005273 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005274 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005275 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00005276 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5277 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005278 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005279 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00005280 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00005281 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005282 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005283 unsigned DiagID = 0;
5284 if (RHSIsNull) {
5285 if (isRelational)
5286 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5287 } else if (isRelational)
5288 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5289 else
5290 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005291
Chris Lattnerd99bd522009-08-23 00:03:44 +00005292 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005293 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005294 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005295 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005296 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005297 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00005298 }
Steve Naroff6b712a72009-07-14 18:25:06 +00005299 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00005300 unsigned DiagID = 0;
5301 if (LHSIsNull) {
5302 if (isRelational)
5303 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5304 } else if (isRelational)
5305 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5306 else
5307 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00005308
Chris Lattnerd99bd522009-08-23 00:03:44 +00005309 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00005310 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00005311 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00005312 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00005313 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005314 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00005315 }
Steve Naroff4b191572008-09-04 16:56:14 +00005316 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00005317 if (!isRelational && RHSIsNull
5318 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005319 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005320 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005321 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00005322 if (!isRelational && LHSIsNull
5323 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005324 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00005325 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00005326 }
Chris Lattner326f7572008-11-18 01:30:42 +00005327 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005328}
5329
Nate Begeman191a6b12008-07-14 18:02:46 +00005330/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00005331/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00005332/// like a scalar comparison, a vector comparison produces a vector of integer
5333/// types.
5334QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00005335 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00005336 bool isRelational) {
5337 // Check to make sure we're operating on vectors of the same type and width,
5338 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00005339 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005340 if (vType.isNull())
5341 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005342
Nate Begeman191a6b12008-07-14 18:02:46 +00005343 QualType lType = lex->getType();
5344 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005345
Nate Begeman191a6b12008-07-14 18:02:46 +00005346 // For non-floating point types, check for self-comparisons of the form
5347 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
5348 // often indicate logic errors in the program.
5349 if (!lType->isFloatingType()) {
5350 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5351 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5352 if (DRL->getDecl() == DRR->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00005353 Diag(Loc, diag::warn_selfcomparison);
Nate Begeman191a6b12008-07-14 18:02:46 +00005354 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005355
Nate Begeman191a6b12008-07-14 18:02:46 +00005356 // Check for comparisons of floating point operands using != and ==.
5357 if (!isRelational && lType->isFloatingType()) {
5358 assert (rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00005359 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00005360 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005361
Nate Begeman191a6b12008-07-14 18:02:46 +00005362 // Return the type for the comparison, which is the same as vector type for
5363 // integer vectors, or an integer type of identical size and number of
5364 // elements for floating point vectors.
5365 if (lType->isIntegerType())
5366 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005367
John McCall9dd450b2009-09-21 23:43:11 +00005368 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00005369 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005370 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00005371 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00005372 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005373 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5374
Mike Stump4e1f26a2009-02-19 03:04:26 +00005375 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005376 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00005377 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5378}
5379
Steve Naroff218bc2b2007-05-04 21:54:46 +00005380inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00005381 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00005382 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00005383 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005384
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005385 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005386
Steve Naroffdbd9e892007-07-17 00:58:39 +00005387 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00005388 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00005389 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00005390}
5391
Steve Naroff218bc2b2007-05-04 21:54:46 +00005392inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump11289f42009-09-09 15:08:12 +00005393 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005394 if (!Context.getLangOptions().CPlusPlus) {
5395 UsualUnaryConversions(lex);
5396 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005397
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005398 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5399 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005400
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005401 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00005402 }
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005403
5404 // C++ [expr.log.and]p1
5405 // C++ [expr.log.or]p1
5406 // The operands are both implicitly converted to type bool (clause 4).
5407 StandardConversionSequence LHS;
5408 if (!IsStandardConversion(lex, Context.BoolTy,
5409 /*InOverloadResolution=*/false, LHS))
5410 return InvalidOperands(Loc, lex, rex);
Anders Carlsson35a99d92009-10-16 01:44:21 +00005411
Anders Carlsson2e7bc112009-11-23 21:47:44 +00005412 if (PerformImplicitConversion(lex, Context.BoolTy, LHS,
5413 "passing", /*IgnoreBaseAccess=*/false))
5414 return InvalidOperands(Loc, lex, rex);
5415
5416 StandardConversionSequence RHS;
5417 if (!IsStandardConversion(rex, Context.BoolTy,
5418 /*InOverloadResolution=*/false, RHS))
5419 return InvalidOperands(Loc, lex, rex);
5420
5421 if (PerformImplicitConversion(rex, Context.BoolTy, RHS,
5422 "passing", /*IgnoreBaseAccess=*/false))
5423 return InvalidOperands(Loc, lex, rex);
5424
5425 // C++ [expr.log.and]p2
5426 // C++ [expr.log.or]p2
5427 // The result is a bool.
5428 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00005429}
5430
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005431/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5432/// is a read-only property; return true if so. A readonly property expression
5433/// depends on various declarations and thus must be treated specially.
5434///
Mike Stump11289f42009-09-09 15:08:12 +00005435static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005436 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5437 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5438 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5439 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005440 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00005441 BaseType->getAsObjCInterfacePointerType())
5442 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5443 if (S.isPropertyReadonly(PDecl, IFace))
5444 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005445 }
5446 }
5447 return false;
5448}
5449
Chris Lattner30bd3272008-11-18 01:22:49 +00005450/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
5451/// emit an error and return true. If so, return false.
5452static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005453 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00005454 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005455 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00005456 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5457 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00005458 if (IsLV == Expr::MLV_Valid)
5459 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005460
Chris Lattner30bd3272008-11-18 01:22:49 +00005461 unsigned Diag = 0;
5462 bool NeedType = false;
5463 switch (IsLV) { // C99 6.5.16p2
5464 default: assert(0 && "Unknown result from isModifiableLvalue!");
5465 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005466 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005467 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5468 NeedType = true;
5469 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005470 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00005471 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5472 NeedType = true;
5473 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00005474 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00005475 Diag = diag::err_typecheck_lvalue_casts_not_supported;
5476 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005477 case Expr::MLV_InvalidExpression:
Chris Lattner30bd3272008-11-18 01:22:49 +00005478 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5479 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005480 case Expr::MLV_IncompleteType:
5481 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00005482 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00005483 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5484 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00005485 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00005486 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5487 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00005488 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00005489 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5490 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00005491 case Expr::MLV_ReadonlyProperty:
5492 Diag = diag::error_readonly_property_assignment;
5493 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00005494 case Expr::MLV_NoSetterProperty:
5495 Diag = diag::error_nosetter_property_assignment;
5496 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005497 }
Steve Naroffad373bd2007-07-31 12:34:36 +00005498
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005499 SourceRange Assign;
5500 if (Loc != OrigLoc)
5501 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00005502 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00005503 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005504 else
Mike Stump11289f42009-09-09 15:08:12 +00005505 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00005506 return true;
5507}
5508
5509
5510
5511// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00005512QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5513 SourceLocation Loc,
5514 QualType CompoundType) {
5515 // Verify that LHS is a modifiable lvalue, and emit error if not.
5516 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00005517 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00005518
5519 QualType LHSType = LHS->getType();
5520 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005521
Chris Lattner9bad62c2008-01-04 18:04:52 +00005522 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00005523 if (CompoundType.isNull()) {
Chris Lattnerea714382008-08-21 18:04:13 +00005524 // Simple assignment "x = y".
Chris Lattner326f7572008-11-18 01:30:42 +00005525 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005526 // Special case of NSObject attributes on c-style pointer types.
5527 if (ConvTy == IncompatiblePointer &&
5528 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005529 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005530 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00005531 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00005532 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005533
Chris Lattnerea714382008-08-21 18:04:13 +00005534 // If the RHS is a unary plus or minus, check to see if they = and + are
5535 // right next to each other. If so, the user may have typo'd "x =+ 4"
5536 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00005537 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00005538 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5539 RHSCheck = ICE->getSubExpr();
5540 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5541 if ((UO->getOpcode() == UnaryOperator::Plus ||
5542 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00005543 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00005544 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00005545 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5546 // And there is a space or other character before the subexpr of the
5547 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00005548 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5549 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005550 Diag(Loc, diag::warn_not_compound_assign)
5551 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5552 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00005553 }
Chris Lattnerea714382008-08-21 18:04:13 +00005554 }
5555 } else {
5556 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00005557 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00005558 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00005559
Chris Lattner326f7572008-11-18 01:30:42 +00005560 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5561 RHS, "assigning"))
Chris Lattner9bad62c2008-01-04 18:04:52 +00005562 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005563
Steve Naroff98cf3e92007-06-06 18:38:38 +00005564 // C99 6.5.16p3: The type of an assignment expression is the type of the
5565 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00005566 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00005567 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5568 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00005569 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00005570 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00005571 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00005572}
5573
Chris Lattner326f7572008-11-18 01:30:42 +00005574// C99 6.5.17
5575QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattnerf6e1e302008-07-25 20:54:07 +00005576 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner326f7572008-11-18 01:30:42 +00005577 DefaultFunctionArrayConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00005578
5579 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5580 // incomplete in C++).
5581
Chris Lattner326f7572008-11-18 01:30:42 +00005582 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00005583}
5584
Steve Naroff7a5af782007-07-13 16:58:59 +00005585/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5586/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00005587QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5588 bool isInc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005589 if (Op->isTypeDependent())
5590 return Context.DependentTy;
5591
Chris Lattner6b0cf142008-11-21 07:05:48 +00005592 QualType ResType = Op->getType();
5593 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00005594
Sebastian Redle10c2c32008-12-20 09:35:34 +00005595 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5596 // Decrement of bool is not allowed.
5597 if (!isInc) {
5598 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5599 return QualType();
5600 }
5601 // Increment of bool sets it to true, but is deprecated.
5602 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5603 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005604 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00005605 } else if (ResType->isAnyPointerType()) {
5606 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005607
Chris Lattner6b0cf142008-11-21 07:05:48 +00005608 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00005609 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005610 if (getLangOptions().CPlusPlus) {
5611 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5612 << Op->getSourceRange();
5613 return QualType();
5614 }
5615
5616 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005617 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005618 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005619 if (getLangOptions().CPlusPlus) {
5620 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5621 << Op->getType() << Op->getSourceRange();
5622 return QualType();
5623 }
5624
5625 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005626 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005627 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00005628 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005629 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005630 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00005631 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00005632 // Diagnose bad cases where we step over interface counts.
5633 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5634 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5635 << PointeeTy << Op->getSourceRange();
5636 return QualType();
5637 }
Chris Lattner6b0cf142008-11-21 07:05:48 +00005638 } else if (ResType->isComplexType()) {
5639 // C99 does not support ++/-- on complex types, we allow as an extension.
5640 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005641 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005642 } else {
5643 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005644 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005645 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00005646 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005647 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00005648 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005649 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00005650 return QualType();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005651 return ResType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005652}
5653
Anders Carlsson806700f2008-02-01 07:15:58 +00005654/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00005655/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005656/// where the declaration is needed for type checking. We only need to
5657/// handle cases when the expression references a function designator
5658/// or is an lvalue. Here are some examples:
5659/// - &(x) => x
5660/// - &*****f => f for f a function designator.
5661/// - &s.xx => s
5662/// - &s.zz[1].yy -> s, if zz is an array
5663/// - *(x + 1) -> x, if x is an array
5664/// - &"123"[2] -> 0
5665/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005666static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005667 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00005668 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005669 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00005670 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005671 // If this is an arrow operator, the address is an offset from
5672 // the base's value, so the object the base refers to is
5673 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005674 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00005675 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00005676 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005677 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00005678 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00005679 // FIXME: This code shouldn't be necessary! We should catch the implicit
5680 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00005681 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5682 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5683 if (ICE->getSubExpr()->getType()->isArrayType())
5684 return getPrimaryDecl(ICE->getSubExpr());
5685 }
5686 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00005687 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005688 case Stmt::UnaryOperatorClass: {
5689 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005690
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005691 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005692 case UnaryOperator::Real:
5693 case UnaryOperator::Imag:
5694 case UnaryOperator::Extension:
5695 return getPrimaryDecl(UO->getSubExpr());
5696 default:
5697 return 0;
5698 }
5699 }
Steve Naroff47500512007-04-19 23:00:49 +00005700 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005701 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00005702 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005703 // If the result of an implicit cast is an l-value, we care about
5704 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005705 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00005706 default:
5707 return 0;
5708 }
5709}
5710
5711/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00005712/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00005713/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005714/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005715/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005716/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00005717/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00005718QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005719 // Make sure to ignore parentheses in subsequent checks
5720 op = op->IgnoreParens();
5721
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00005722 if (op->isTypeDependent())
5723 return Context.DependentTy;
5724
Steve Naroff826e91a2008-01-13 17:10:08 +00005725 if (getLangOptions().C99) {
5726 // Implement C99-only parts of addressof rules.
5727 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5728 if (uOp->getOpcode() == UnaryOperator::Deref)
5729 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5730 // (assuming the deref expression is valid).
5731 return uOp->getSubExpr()->getType();
5732 }
5733 // Technically, there should be a check for array subscript
5734 // expressions here, but the result of one is always an lvalue anyway.
5735 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005736 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00005737 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00005738
Eli Friedmance7f9002009-05-16 23:27:50 +00005739 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5740 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005741 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00005742 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00005743 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00005744 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5745 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005746 return QualType();
5747 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00005748 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005749 // The operand cannot be a bit-field
5750 Diag(OpLoc, diag::err_typecheck_address_of)
5751 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00005752 return QualType();
Nate Begemana6b47a42009-02-15 22:45:20 +00005753 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5754 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman3a1e6922009-04-20 08:23:18 +00005755 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00005756 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00005757 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005758 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00005759 } else if (isa<ObjCPropertyRefExpr>(op)) {
5760 // cannot take address of a property expression.
5761 Diag(OpLoc, diag::err_typecheck_address_of)
5762 << "property expression" << op->getSourceRange();
5763 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00005764 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5765 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00005766 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5767 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00005768 } else if (isa<UnresolvedLookupExpr>(op)) {
5769 return Context.OverloadTy;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005770 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00005771 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00005772 // with the register storage-class specifier.
5773 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00005774 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005775 Diag(OpLoc, diag::err_typecheck_address_of)
5776 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005777 return QualType();
5778 }
John McCalld14a8642009-11-21 08:51:07 +00005779 } else if (isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005780 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00005781 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00005782 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005783 // Could be a pointer to member, though, if there is an explicit
5784 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005785 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005786 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00005787 if (Ctx && Ctx->isRecord()) {
5788 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005789 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00005790 diag::err_cannot_form_pointer_to_member_of_reference_type)
5791 << FD->getDeclName() << FD->getType();
5792 return QualType();
5793 }
Mike Stump11289f42009-09-09 15:08:12 +00005794
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005795 return Context.getMemberPointerType(op->getType(),
5796 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00005797 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005798 }
Anders Carlsson5b535762009-05-16 21:43:42 +00005799 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00005800 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005801 // As above.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005802 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5803 MD->isInstance())
Anders Carlsson5b535762009-05-16 21:43:42 +00005804 return Context.getMemberPointerType(op->getType(),
5805 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5806 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00005807 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00005808 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005809
Eli Friedmance7f9002009-05-16 23:27:50 +00005810 if (lval == Expr::LV_IncompleteVoidType) {
5811 // Taking the address of a void variable is technically illegal, but we
5812 // allow it in cases which are otherwise valid.
5813 // Example: "extern void x; void* y = &x;".
5814 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5815 }
5816
Steve Naroff47500512007-04-19 23:00:49 +00005817 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00005818 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00005819}
5820
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005821QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005822 if (Op->isTypeDependent())
5823 return Context.DependentTy;
5824
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005825 UsualUnaryConversions(Op);
5826 QualType Ty = Op->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005827
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005828 // Note that per both C89 and C99, this is always legal, even if ptype is an
5829 // incomplete type or void. It would be possible to warn about dereferencing
5830 // a void pointer, but it's completely well-defined, and such a warning is
5831 // unlikely to catch any mistakes.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005832 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff826e91a2008-01-13 17:10:08 +00005833 return PT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005834
John McCall9dd450b2009-09-21 23:43:11 +00005835 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +00005836 return OPT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005837
Chris Lattner29e812b2008-11-20 06:06:08 +00005838 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005839 << Ty << Op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005840 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +00005841}
Steve Naroff218bc2b2007-05-04 21:54:46 +00005842
5843static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5844 tok::TokenKind Kind) {
5845 BinaryOperator::Opcode Opc;
5846 switch (Kind) {
5847 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00005848 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5849 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005850 case tok::star: Opc = BinaryOperator::Mul; break;
5851 case tok::slash: Opc = BinaryOperator::Div; break;
5852 case tok::percent: Opc = BinaryOperator::Rem; break;
5853 case tok::plus: Opc = BinaryOperator::Add; break;
5854 case tok::minus: Opc = BinaryOperator::Sub; break;
5855 case tok::lessless: Opc = BinaryOperator::Shl; break;
5856 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5857 case tok::lessequal: Opc = BinaryOperator::LE; break;
5858 case tok::less: Opc = BinaryOperator::LT; break;
5859 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5860 case tok::greater: Opc = BinaryOperator::GT; break;
5861 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5862 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5863 case tok::amp: Opc = BinaryOperator::And; break;
5864 case tok::caret: Opc = BinaryOperator::Xor; break;
5865 case tok::pipe: Opc = BinaryOperator::Or; break;
5866 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5867 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5868 case tok::equal: Opc = BinaryOperator::Assign; break;
5869 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5870 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5871 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5872 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5873 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5874 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5875 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5876 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5877 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5878 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5879 case tok::comma: Opc = BinaryOperator::Comma; break;
5880 }
5881 return Opc;
5882}
5883
Steve Naroff35d85152007-05-07 00:24:15 +00005884static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5885 tok::TokenKind Kind) {
5886 UnaryOperator::Opcode Opc;
5887 switch (Kind) {
5888 default: assert(0 && "Unknown unary op!");
5889 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5890 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5891 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5892 case tok::star: Opc = UnaryOperator::Deref; break;
5893 case tok::plus: Opc = UnaryOperator::Plus; break;
5894 case tok::minus: Opc = UnaryOperator::Minus; break;
5895 case tok::tilde: Opc = UnaryOperator::Not; break;
5896 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005897 case tok::kw___real: Opc = UnaryOperator::Real; break;
5898 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00005899 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005900 }
5901 return Opc;
5902}
5903
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005904/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5905/// operator @p Opc at location @c TokLoc. This routine only supports
5906/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005907Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5908 unsigned Op,
5909 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005910 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005911 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005912 // The following two variables are used for compound assignment operators
5913 QualType CompLHSTy; // Type of LHS after promotions for computation
5914 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005915
5916 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005917 case BinaryOperator::Assign:
5918 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5919 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00005920 case BinaryOperator::PtrMemD:
5921 case BinaryOperator::PtrMemI:
5922 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5923 Opc == BinaryOperator::PtrMemI);
5924 break;
5925 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005926 case BinaryOperator::Div:
5927 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5928 break;
5929 case BinaryOperator::Rem:
5930 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5931 break;
5932 case BinaryOperator::Add:
5933 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5934 break;
5935 case BinaryOperator::Sub:
5936 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5937 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00005938 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005939 case BinaryOperator::Shr:
5940 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5941 break;
5942 case BinaryOperator::LE:
5943 case BinaryOperator::LT:
5944 case BinaryOperator::GE:
5945 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005946 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005947 break;
5948 case BinaryOperator::EQ:
5949 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005950 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005951 break;
5952 case BinaryOperator::And:
5953 case BinaryOperator::Xor:
5954 case BinaryOperator::Or:
5955 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5956 break;
5957 case BinaryOperator::LAnd:
5958 case BinaryOperator::LOr:
5959 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5960 break;
5961 case BinaryOperator::MulAssign:
5962 case BinaryOperator::DivAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005963 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5964 CompLHSTy = CompResultTy;
5965 if (!CompResultTy.isNull())
5966 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005967 break;
5968 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005969 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5970 CompLHSTy = CompResultTy;
5971 if (!CompResultTy.isNull())
5972 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005973 break;
5974 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005975 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5976 if (!CompResultTy.isNull())
5977 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005978 break;
5979 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005980 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5981 if (!CompResultTy.isNull())
5982 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005983 break;
5984 case BinaryOperator::ShlAssign:
5985 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005986 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5987 CompLHSTy = CompResultTy;
5988 if (!CompResultTy.isNull())
5989 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005990 break;
5991 case BinaryOperator::AndAssign:
5992 case BinaryOperator::XorAssign:
5993 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005994 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5995 CompLHSTy = CompResultTy;
5996 if (!CompResultTy.isNull())
5997 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005998 break;
5999 case BinaryOperator::Comma:
6000 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6001 break;
6002 }
6003 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00006004 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006005 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00006006 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6007 else
6008 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006009 CompLHSTy, CompResultTy,
6010 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006011}
6012
Sebastian Redl44615072009-10-27 12:10:02 +00006013/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6014/// ParenRange in parentheses.
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006015static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6016 const PartialDiagnostic &PD,
6017 SourceRange ParenRange)
6018{
6019 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
6020 if (!ParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6021 // We can't display the parentheses, so just dig the
6022 // warning/error and return.
6023 Self.Diag(Loc, PD);
6024 return;
6025 }
6026
6027 Self.Diag(Loc, PD)
6028 << CodeModificationHint::CreateInsertion(ParenRange.getBegin(), "(")
6029 << CodeModificationHint::CreateInsertion(EndLoc, ")");
6030}
6031
Sebastian Redl44615072009-10-27 12:10:02 +00006032/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6033/// operators are mixed in a way that suggests that the programmer forgot that
6034/// comparison operators have higher precedence. The most typical example of
6035/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
Sebastian Redl43028242009-10-26 15:24:15 +00006036static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6037 SourceLocation OpLoc,Expr *lhs,Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006038 typedef BinaryOperator BinOp;
6039 BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6040 rhsopc = static_cast<BinOp::Opcode>(-1);
6041 if (BinOp *BO = dyn_cast<BinOp>(lhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006042 lhsopc = BO->getOpcode();
Sebastian Redl44615072009-10-27 12:10:02 +00006043 if (BinOp *BO = dyn_cast<BinOp>(rhs))
Sebastian Redl43028242009-10-26 15:24:15 +00006044 rhsopc = BO->getOpcode();
6045
6046 // Subs are not binary operators.
6047 if (lhsopc == -1 && rhsopc == -1)
6048 return;
6049
6050 // Bitwise operations are sometimes used as eager logical ops.
6051 // Don't diagnose this.
Sebastian Redl44615072009-10-27 12:10:02 +00006052 if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6053 (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00006054 return;
6055
Sebastian Redl44615072009-10-27 12:10:02 +00006056 if (BinOp::isComparisonOp(lhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006057 SuggestParentheses(Self, OpLoc,
6058 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006059 << SourceRange(lhs->getLocStart(), OpLoc)
6060 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
6061 SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()));
6062 else if (BinOp::isComparisonOp(rhsopc))
Sebastian Redl4afb7c582009-10-26 17:01:32 +00006063 SuggestParentheses(Self, OpLoc,
6064 PDiag(diag::warn_precedence_bitwise_rel)
Sebastian Redl44615072009-10-27 12:10:02 +00006065 << SourceRange(OpLoc, rhs->getLocEnd())
6066 << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
6067 SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()));
Sebastian Redl43028242009-10-26 15:24:15 +00006068}
6069
6070/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6071/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6072/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6073static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6074 SourceLocation OpLoc, Expr *lhs, Expr *rhs){
Sebastian Redl44615072009-10-27 12:10:02 +00006075 if (BinaryOperator::isBitwiseOp(Opc))
Sebastian Redl43028242009-10-26 15:24:15 +00006076 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6077}
6078
Steve Naroff218bc2b2007-05-04 21:54:46 +00006079// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00006080Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6081 tok::TokenKind Kind,
6082 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00006083 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006084 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00006085
Steve Naroff83895f72007-09-16 03:34:24 +00006086 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6087 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00006088
Sebastian Redl43028242009-10-26 15:24:15 +00006089 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6090 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6091
Douglas Gregor5287f092009-11-05 00:51:44 +00006092 return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6093}
6094
6095Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6096 BinaryOperator::Opcode Opc,
6097 Expr *lhs, Expr *rhs) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006098 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00006099 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006100 rhs->getType()->isOverloadableType())) {
6101 // Find all of the overloaded operators visible from this
6102 // point. We perform both an operator-name lookup from the local
6103 // scope and an argument-dependent lookup based on the types of
6104 // the arguments.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006105 FunctionSet Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006106 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6107 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006108 if (S)
6109 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6110 Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006111 Expr *Args[2] = { lhs, rhs };
Mike Stump11289f42009-09-09 15:08:12 +00006112 DeclarationName OpName
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006113 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00006114 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregora11693b2008-11-12 17:17:38 +00006115 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006116
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006117 // Build the (potentially-overloaded, potentially-dependent)
6118 // binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006119 return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00006120 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006121
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00006122 // Build a built-in binary operation.
Douglas Gregor5287f092009-11-05 00:51:44 +00006123 return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006124}
6125
Douglas Gregor084d8552009-03-13 23:49:33 +00006126Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006127 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00006128 ExprArg InputArg) {
6129 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00006130
Mike Stump87c57ac2009-05-16 07:39:55 +00006131 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00006132 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00006133 QualType resultType;
6134 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006135 case UnaryOperator::OffsetOf:
6136 assert(false && "Invalid unary operator");
6137 break;
6138
Steve Naroff35d85152007-05-07 00:24:15 +00006139 case UnaryOperator::PreInc:
6140 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00006141 case UnaryOperator::PostInc:
6142 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00006143 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00006144 Opc == UnaryOperator::PreInc ||
6145 Opc == UnaryOperator::PostInc);
Steve Naroff35d85152007-05-07 00:24:15 +00006146 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006147 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00006148 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006149 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006150 case UnaryOperator::Deref:
Steve Naroffb7235642007-12-18 04:06:57 +00006151 DefaultFunctionArrayConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00006152 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00006153 break;
6154 case UnaryOperator::Plus:
6155 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00006156 UsualUnaryConversions(Input);
6157 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006158 if (resultType->isDependentType())
6159 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006160 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
6161 break;
6162 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6163 resultType->isEnumeralType())
6164 break;
6165 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6166 Opc == UnaryOperator::Plus &&
6167 resultType->isPointerType())
6168 break;
6169
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006170 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6171 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006172 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00006173 UsualUnaryConversions(Input);
6174 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006175 if (resultType->isDependentType())
6176 break;
Chris Lattner0d707612008-07-25 23:52:49 +00006177 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6178 if (resultType->isComplexType() || resultType->isComplexIntegerType())
6179 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00006180 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006181 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00006182 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006183 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6184 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00006185 break;
6186 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00006187 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroff31090012007-07-16 21:54:35 +00006188 DefaultFunctionArrayConversion(Input);
6189 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006190 if (resultType->isDependentType())
6191 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006192 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006193 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6194 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00006195 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006196 // In C++, it's bool. C++ 5.3.1p8
6197 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00006198 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00006199 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00006200 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00006201 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00006202 break;
Chris Lattner86554282007-06-08 22:32:33 +00006203 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00006204 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00006205 break;
Steve Naroff35d85152007-05-07 00:24:15 +00006206 }
6207 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006208 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00006209
6210 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00006211 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00006212}
Chris Lattnereefa10e2007-05-28 06:56:27 +00006213
Douglas Gregor5287f092009-11-05 00:51:44 +00006214Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6215 UnaryOperator::Opcode Opc,
6216 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006217 Expr *Input = (Expr*)input.get();
Anders Carlsson461a2c02009-11-14 21:26:41 +00006218 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6219 Opc != UnaryOperator::Extension) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006220 // Find all of the overloaded operators visible from this
6221 // point. We perform both an operator-name lookup from the local
6222 // scope and an argument-dependent lookup based on the types of
6223 // the arguments.
6224 FunctionSet Functions;
6225 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6226 if (OverOp != OO_None) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006227 if (S)
6228 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6229 Functions);
Mike Stump11289f42009-09-09 15:08:12 +00006230 DeclarationName OpName
Douglas Gregor084d8552009-03-13 23:49:33 +00006231 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00006232 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregor084d8552009-03-13 23:49:33 +00006233 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006234
Douglas Gregor084d8552009-03-13 23:49:33 +00006235 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6236 }
Douglas Gregor5287f092009-11-05 00:51:44 +00006237
Douglas Gregor084d8552009-03-13 23:49:33 +00006238 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6239}
6240
Douglas Gregor5287f092009-11-05 00:51:44 +00006241// Unary Operators. 'Tok' is the token for the operator.
6242Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6243 tok::TokenKind Op, ExprArg input) {
6244 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6245}
6246
Steve Naroff66356bd2007-09-16 14:56:35 +00006247/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006248Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6249 SourceLocation LabLoc,
6250 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00006251 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00006252 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00006253
Daniel Dunbar88402ce2008-08-04 16:51:22 +00006254 // If we haven't seen this label yet, create a forward reference. It
6255 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00006256 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00006257 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006258
Chris Lattnereefa10e2007-05-28 06:56:27 +00006259 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006260 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6261 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00006262}
6263
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006264Sema::OwningExprResult
6265Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6266 SourceLocation RPLoc) { // "({..})"
6267 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00006268 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6269 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6270
Eli Friedman52cc0162009-01-24 23:09:00 +00006271 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattnera69b0762009-04-25 19:11:05 +00006272 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006273 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00006274
Chris Lattner366727f2007-07-24 16:58:17 +00006275 // FIXME: there are a variety of strange constraints to enforce here, for
6276 // example, it is not possible to goto into a stmt expression apparently.
6277 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006278
Chris Lattner366727f2007-07-24 16:58:17 +00006279 // If there are sub stmts in the compound stmt, take the type of the last one
6280 // as the type of the stmtexpr.
6281 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006282
Chris Lattner944d3062008-07-26 19:51:01 +00006283 if (!Compound->body_empty()) {
6284 Stmt *LastStmt = Compound->body_back();
6285 // If LastStmt is a label, skip down through into the body.
6286 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6287 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006288
Chris Lattner944d3062008-07-26 19:51:01 +00006289 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00006290 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00006291 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006292
Eli Friedmanba961a92009-03-23 00:24:07 +00006293 // FIXME: Check that expression type is complete/non-abstract; statement
6294 // expressions are not lvalues.
6295
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006296 substmt.release();
6297 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00006298}
Steve Naroff78864672007-08-01 22:05:33 +00006299
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006300Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6301 SourceLocation BuiltinLoc,
6302 SourceLocation TypeLoc,
6303 TypeTy *argty,
6304 OffsetOfComponent *CompPtr,
6305 unsigned NumComponents,
6306 SourceLocation RPLoc) {
6307 // FIXME: This function leaks all expressions in the offset components on
6308 // error.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006309 // FIXME: Preserve type source info.
6310 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattnerf17bd422007-08-30 17:45:32 +00006311 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006312
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006313 bool Dependent = ArgTy->isDependentType();
6314
Chris Lattnerf17bd422007-08-30 17:45:32 +00006315 // We must have at least one component that refers to the type, and the first
6316 // one is known to be a field designator. Verify that the ArgTy represents
6317 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006318 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006319 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006320
Eli Friedmanba961a92009-03-23 00:24:07 +00006321 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6322 // with an incomplete type would be illegal.
Douglas Gregor26897462009-03-11 16:48:53 +00006323
Eli Friedman988a16b2009-02-27 06:44:11 +00006324 // Otherwise, create a null pointer as the base, and iteratively process
6325 // the offsetof designators.
6326 QualType ArgTyPtr = Context.getPointerType(ArgTy);
6327 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006328 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman988a16b2009-02-27 06:44:11 +00006329 ArgTy, SourceLocation());
Eli Friedman16c88df2009-01-26 01:33:06 +00006330
Chris Lattner78502cf2007-08-31 21:49:13 +00006331 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6332 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00006333 // FIXME: This diagnostic isn't actually visible because the location is in
6334 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00006335 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00006336 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6337 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006338
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006339 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00006340 bool DidWarnAboutNonPOD = false;
Mike Stump11289f42009-09-09 15:08:12 +00006341
John McCall9eff4e62009-11-04 03:03:43 +00006342 if (RequireCompleteType(TypeLoc, Res->getType(),
6343 diag::err_offsetof_incomplete_type))
6344 return ExprError();
6345
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006346 // FIXME: Dependent case loses a lot of information here. And probably
6347 // leaks like a sieve.
6348 for (unsigned i = 0; i != NumComponents; ++i) {
6349 const OffsetOfComponent &OC = CompPtr[i];
6350 if (OC.isBrackets) {
6351 // Offset of an array sub-field. TODO: Should we allow vector elements?
6352 const ArrayType *AT = Context.getAsArrayType(Res->getType());
6353 if (!AT) {
6354 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006355 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6356 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006357 }
6358
6359 // FIXME: C++: Verify that operator[] isn't overloaded.
6360
Eli Friedman988a16b2009-02-27 06:44:11 +00006361 // Promote the array so it looks more like a normal array subscript
6362 // expression.
6363 DefaultFunctionArrayConversion(Res);
6364
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006365 // C99 6.5.2.1p1
6366 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006367 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006368 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006369 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00006370 diag::err_typecheck_subscript_not_integer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006371 << Idx->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006372
6373 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6374 OC.LocEnd);
6375 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00006376 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006377
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006378 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006379 if (!RC) {
6380 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006381 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6382 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006383 }
Chris Lattner98dbf0a2007-08-30 17:59:59 +00006384
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006385 // Get the decl corresponding to this.
6386 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006387 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00006388 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlsson8b98d022009-05-02 17:45:47 +00006389 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
6390 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6391 << Res->getType());
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00006392 DidWarnAboutNonPOD = true;
6393 }
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00006394 }
Mike Stump11289f42009-09-09 15:08:12 +00006395
John McCall27b18f82009-11-17 02:14:36 +00006396 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6397 LookupQualifiedName(R, RD);
John McCall9f3059a2009-10-09 21:13:30 +00006398
John McCall67c00872009-12-02 08:25:40 +00006399 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006400 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006401 if (!MemberDecl)
Douglas Gregore40876a2009-10-13 21:16:44 +00006402 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6403 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump4e1f26a2009-02-19 03:04:26 +00006404
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006405 // FIXME: C++: Verify that MemberDecl isn't a static field.
6406 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00006407 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00006408 Res = BuildAnonymousStructUnionMemberReference(
John McCall7e1d6d72009-11-11 03:23:23 +00006409 OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00006410 } else {
Eli Friedman78cde142009-12-04 07:18:51 +00006411 PerformObjectMemberConversion(Res, MemberDecl);
Eli Friedman64fc3c62009-04-26 20:50:44 +00006412 // MemberDecl->getType() doesn't get the right qualifiers, but it
6413 // doesn't matter here.
6414 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6415 MemberDecl->getType().getNonReferenceType());
6416 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006417 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00006418 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006419
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006420 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6421 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00006422}
6423
6424
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006425Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6426 TypeTy *arg1,TypeTy *arg2,
6427 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006428 // FIXME: Preserve type source info.
6429 QualType argT1 = GetTypeFromParser(arg1);
6430 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006431
Steve Naroff78864672007-08-01 22:05:33 +00006432 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00006433
Douglas Gregorf907cbf2009-05-19 22:28:02 +00006434 if (getLangOptions().CPlusPlus) {
6435 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6436 << SourceRange(BuiltinLoc, RPLoc);
6437 return ExprError();
6438 }
6439
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006440 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6441 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00006442}
6443
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006444Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6445 ExprArg cond,
6446 ExprArg expr1, ExprArg expr2,
6447 SourceLocation RPLoc) {
6448 Expr *CondExpr = static_cast<Expr*>(cond.get());
6449 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
6450 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006451
Steve Naroff9efdabc2007-08-03 21:21:27 +00006452 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
6453
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006454 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00006455 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00006456 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006457 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00006458 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006459 } else {
6460 // The conditional expression is required to be a constant expression.
6461 llvm::APSInt condEval(32);
6462 SourceLocation ExpLoc;
6463 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006464 return ExprError(Diag(ExpLoc,
6465 diag::err_typecheck_choose_expr_requires_constant)
6466 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00006467
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006468 // If the condition is > zero, then the AST type is the same as the LSHExpr.
6469 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00006470 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
6471 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00006472 }
6473
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006474 cond.release(); expr1.release(); expr2.release();
6475 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00006476 resType, RPLoc,
6477 resType->isDependentType(),
6478 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00006479}
6480
Steve Naroffc540d662008-09-03 18:15:37 +00006481//===----------------------------------------------------------------------===//
6482// Clang Extensions.
6483//===----------------------------------------------------------------------===//
6484
6485/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006486void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00006487 // Analyze block parameters.
6488 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006489
Steve Naroffc540d662008-09-03 18:15:37 +00006490 // Add BSI to CurBlock.
6491 BSI->PrevBlockInfo = CurBlock;
6492 CurBlock = BSI;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006493
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006494 BSI->ReturnType = QualType();
Steve Naroffc540d662008-09-03 18:15:37 +00006495 BSI->TheScope = BlockScope;
Mike Stumpa6703322009-02-19 22:01:56 +00006496 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarb9a68612009-07-29 01:59:17 +00006497 BSI->hasPrototype = false;
Chris Lattner45542ea2009-04-19 05:28:12 +00006498 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
6499 CurFunctionNeedsScopeChecking = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006500
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006501 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006502 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006503}
6504
Mike Stump82f071f2009-02-04 22:31:32 +00006505void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00006506 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump82f071f2009-02-04 22:31:32 +00006507
6508 if (ParamInfo.getNumTypeObjects() == 0
6509 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor758a8692009-06-17 21:51:59 +00006510 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump82f071f2009-02-04 22:31:32 +00006511 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
6512
Mike Stumpd456c482009-04-28 01:10:27 +00006513 if (T->isArrayType()) {
6514 Diag(ParamInfo.getSourceRange().getBegin(),
6515 diag::err_block_returns_array);
6516 return;
6517 }
6518
Mike Stump82f071f2009-02-04 22:31:32 +00006519 // The parameter list is optional, if there was none, assume ().
6520 if (!T->isFunctionType())
6521 T = Context.getFunctionType(T, NULL, 0, 0, 0);
6522
6523 CurBlock->hasPrototype = true;
6524 CurBlock->isVariadic = false;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006525 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006526 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006527 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006528 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006529 // FIXME: remove the attribute.
6530 }
John McCall9dd450b2009-09-21 23:43:11 +00006531 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006532
Chris Lattner6de05082009-04-11 19:27:54 +00006533 // Do not allow returning a objc interface by-value.
6534 if (RetTy->isObjCInterfaceType()) {
6535 Diag(ParamInfo.getSourceRange().getBegin(),
6536 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6537 return;
6538 }
Mike Stump82f071f2009-02-04 22:31:32 +00006539 return;
6540 }
6541
Steve Naroffc540d662008-09-03 18:15:37 +00006542 // Analyze arguments to block.
6543 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
6544 "Not a function declarator!");
6545 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006546
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006547 CurBlock->hasPrototype = FTI.hasPrototype;
6548 CurBlock->isVariadic = true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006549
Steve Naroffc540d662008-09-03 18:15:37 +00006550 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
6551 // no arguments, not a function that takes a single void argument.
6552 if (FTI.hasPrototype &&
6553 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner83f095c2009-03-28 19:18:32 +00006554 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
6555 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00006556 // empty arg list, don't push any params.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006557 CurBlock->isVariadic = false;
Steve Naroffc540d662008-09-03 18:15:37 +00006558 } else if (FTI.hasPrototype) {
6559 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner83f095c2009-03-28 19:18:32 +00006560 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006561 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroffc540d662008-09-03 18:15:37 +00006562 }
Jay Foad7d0479f2009-05-21 09:52:38 +00006563 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner6de05082009-04-11 19:27:54 +00006564 CurBlock->Params.size());
Fariborz Jahanian960910a2009-05-19 17:08:59 +00006565 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor758a8692009-06-17 21:51:59 +00006566 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006567 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
6568 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
6569 // If this has an identifier, add it to the scope stack.
6570 if ((*AI)->getIdentifier())
6571 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner6de05082009-04-11 19:27:54 +00006572
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006573 // Check for a valid sentinel attribute on this block.
Mike Stump11289f42009-09-09 15:08:12 +00006574 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006575 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00006576 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00006577 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00006578 // FIXME: remove the attribute.
6579 }
Mike Stump11289f42009-09-09 15:08:12 +00006580
Chris Lattner6de05082009-04-11 19:27:54 +00006581 // Analyze the return type.
6582 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall9dd450b2009-09-21 23:43:11 +00006583 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006584
Chris Lattner6de05082009-04-11 19:27:54 +00006585 // Do not allow returning a objc interface by-value.
6586 if (RetTy->isObjCInterfaceType()) {
6587 Diag(ParamInfo.getSourceRange().getBegin(),
6588 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
6589 } else if (!RetTy->isDependentType())
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006590 CurBlock->ReturnType = RetTy;
Steve Naroffc540d662008-09-03 18:15:37 +00006591}
6592
6593/// ActOnBlockError - If there is an error parsing a block, this callback
6594/// is invoked to pop the information about the block from the action impl.
6595void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
6596 // Ensure that CurBlock is deleted.
6597 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006598
Chris Lattner45542ea2009-04-19 05:28:12 +00006599 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
6600
Steve Naroffc540d662008-09-03 18:15:37 +00006601 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00006602 PopDeclContext();
Steve Naroffc540d662008-09-03 18:15:37 +00006603 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroffc540d662008-09-03 18:15:37 +00006604 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00006605}
6606
6607/// ActOnBlockStmtExpr - This is called when the body of a block statement
6608/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006609Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
6610 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00006611 // If blocks are disabled, emit an error.
6612 if (!LangOpts.Blocks)
6613 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00006614
Steve Naroffc540d662008-09-03 18:15:37 +00006615 // Ensure that CurBlock is deleted.
6616 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroffc540d662008-09-03 18:15:37 +00006617
Steve Naroff1d95e5a2008-10-10 01:28:17 +00006618 PopDeclContext();
6619
Steve Naroffc540d662008-09-03 18:15:37 +00006620 // Pop off CurBlock, handle nested blocks.
6621 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006622
Steve Naroffc540d662008-09-03 18:15:37 +00006623 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00006624 if (!BSI->ReturnType.isNull())
6625 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006626
Steve Naroffc540d662008-09-03 18:15:37 +00006627 llvm::SmallVector<QualType, 8> ArgTypes;
6628 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
6629 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006630
Mike Stump3bf1ab42009-07-28 22:04:01 +00006631 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00006632 QualType BlockTy;
6633 if (!BSI->hasPrototype)
Mike Stump3bf1ab42009-07-28 22:04:01 +00006634 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
6635 NoReturn);
Steve Naroffc540d662008-09-03 18:15:37 +00006636 else
Jay Foad7d0479f2009-05-21 09:52:38 +00006637 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump3bf1ab42009-07-28 22:04:01 +00006638 BSI->isVariadic, 0, false, false, 0, 0,
6639 NoReturn);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006640
Eli Friedmanba961a92009-03-23 00:24:07 +00006641 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006642 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroffc540d662008-09-03 18:15:37 +00006643 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006644
Chris Lattner45542ea2009-04-19 05:28:12 +00006645 // If needed, diagnose invalid gotos and switches in the block.
6646 if (CurFunctionNeedsScopeChecking)
6647 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
6648 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump11289f42009-09-09 15:08:12 +00006649
Anders Carlssonb781bcd2009-05-01 19:49:17 +00006650 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump3bf1ab42009-07-28 22:04:01 +00006651 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006652 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
6653 BSI->hasBlockDeclRefExprs));
Steve Naroffc540d662008-09-03 18:15:37 +00006654}
6655
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006656Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
6657 ExprArg expr, TypeTy *type,
6658 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00006659 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00006660 Expr *E = static_cast<Expr*>(expr.get());
6661 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00006662
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006663 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00006664
6665 // Get the va_list type
6666 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00006667 if (VaListType->isArrayType()) {
6668 // Deal with implicit array decay; for example, on x86-64,
6669 // va_list is an array, but it's supposed to decay to
6670 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00006671 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00006672 // Make sure the input expression also decays appropriately.
6673 UsualUnaryConversions(E);
6674 } else {
6675 // Otherwise, the va_list argument must be an l-value because
6676 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00006677 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00006678 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00006679 return ExprError();
6680 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00006681
Douglas Gregorad3150c2009-05-19 23:10:31 +00006682 if (!E->isTypeDependent() &&
6683 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006684 return ExprError(Diag(E->getLocStart(),
6685 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00006686 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00006687 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006688
Eli Friedmanba961a92009-03-23 00:24:07 +00006689 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006690 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006691
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006692 expr.release();
6693 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6694 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006695}
6696
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006697Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00006698 // The type of __null will be int or long, depending on the size of
6699 // pointers on the target.
6700 QualType Ty;
6701 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6702 Ty = Context.IntTy;
6703 else
6704 Ty = Context.LongTy;
6705
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006706 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00006707}
6708
Anders Carlssonace5d072009-11-10 04:46:30 +00006709static void
6710MakeObjCStringLiteralCodeModificationHint(Sema& SemaRef,
6711 QualType DstType,
6712 Expr *SrcExpr,
6713 CodeModificationHint &Hint) {
6714 if (!SemaRef.getLangOptions().ObjC1)
6715 return;
6716
6717 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
6718 if (!PT)
6719 return;
6720
6721 // Check if the destination is of type 'id'.
6722 if (!PT->isObjCIdType()) {
6723 // Check if the destination is the 'NSString' interface.
6724 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
6725 if (!ID || !ID->getIdentifier()->isStr("NSString"))
6726 return;
6727 }
6728
6729 // Strip off any parens and casts.
6730 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
6731 if (!SL || SL->isWide())
6732 return;
6733
6734 Hint = CodeModificationHint::CreateInsertion(SL->getLocStart(), "@");
6735}
6736
Chris Lattner9bad62c2008-01-04 18:04:52 +00006737bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6738 SourceLocation Loc,
6739 QualType DstType, QualType SrcType,
6740 Expr *SrcExpr, const char *Flavor) {
6741 // Decode the result (notice that AST's are still created for extensions).
6742 bool isInvalid = false;
6743 unsigned DiagKind;
Anders Carlssonace5d072009-11-10 04:46:30 +00006744 CodeModificationHint Hint;
6745
Chris Lattner9bad62c2008-01-04 18:04:52 +00006746 switch (ConvTy) {
6747 default: assert(0 && "Unknown conversion type");
6748 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006749 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00006750 DiagKind = diag::ext_typecheck_convert_pointer_int;
6751 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006752 case IntToPointer:
6753 DiagKind = diag::ext_typecheck_convert_int_pointer;
6754 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006755 case IncompatiblePointer:
Anders Carlssonace5d072009-11-10 04:46:30 +00006756 MakeObjCStringLiteralCodeModificationHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00006757 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6758 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00006759 case IncompatiblePointerSign:
6760 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6761 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006762 case FunctionVoidPointer:
6763 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6764 break;
6765 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00006766 // If the qualifiers lost were because we were applying the
6767 // (deprecated) C++ conversion from a string literal to a char*
6768 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6769 // Ideally, this check would be performed in
6770 // CheckPointerTypesForAssignment. However, that would require a
6771 // bit of refactoring (so that the second argument is an
6772 // expression, rather than a type), which should be done as part
6773 // of a larger effort to fix CheckPointerTypesForAssignment for
6774 // C++ semantics.
6775 if (getLangOptions().CPlusPlus &&
6776 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6777 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006778 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6779 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00006780 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00006781 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00006782 break;
Steve Naroff081c7422008-09-04 15:10:53 +00006783 case IntToBlockPointer:
6784 DiagKind = diag::err_int_to_block_pointer;
6785 break;
6786 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00006787 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00006788 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00006789 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00006790 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00006791 // it can give a more specific diagnostic.
6792 DiagKind = diag::warn_incompatible_qualified_id;
6793 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006794 case IncompatibleVectors:
6795 DiagKind = diag::warn_incompatible_vectors;
6796 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006797 case Incompatible:
6798 DiagKind = diag::err_typecheck_convert_incompatible;
6799 isInvalid = true;
6800 break;
6801 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006802
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006803 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
Anders Carlssonace5d072009-11-10 04:46:30 +00006804 << SrcExpr->getSourceRange() << Hint;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006805 return isInvalid;
6806}
Anders Carlssone54e8a12008-11-30 19:50:32 +00006807
Chris Lattnerc71d08b2009-04-25 21:59:05 +00006808bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006809 llvm::APSInt ICEResult;
6810 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6811 if (Result)
6812 *Result = ICEResult;
6813 return false;
6814 }
6815
Anders Carlssone54e8a12008-11-30 19:50:32 +00006816 Expr::EvalResult EvalResult;
6817
Mike Stump4e1f26a2009-02-19 03:04:26 +00006818 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00006819 EvalResult.HasSideEffects) {
6820 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6821
6822 if (EvalResult.Diag) {
6823 // We only show the note if it's not the usual "invalid subexpression"
6824 // or if it's actually in a subexpression.
6825 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6826 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6827 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6828 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006829
Anders Carlssone54e8a12008-11-30 19:50:32 +00006830 return true;
6831 }
6832
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006833 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6834 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00006835
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006836 if (EvalResult.Diag &&
6837 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6838 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006839
Anders Carlssone54e8a12008-11-30 19:50:32 +00006840 if (Result)
6841 *Result = EvalResult.Val.getInt();
6842 return false;
6843}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006844
Douglas Gregorff790f12009-11-26 00:44:06 +00006845void
Mike Stump11289f42009-09-09 15:08:12 +00006846Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregorff790f12009-11-26 00:44:06 +00006847 ExprEvalContexts.push_back(
6848 ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006849}
6850
Mike Stump11289f42009-09-09 15:08:12 +00006851void
Douglas Gregorff790f12009-11-26 00:44:06 +00006852Sema::PopExpressionEvaluationContext() {
6853 // Pop the current expression evaluation context off the stack.
6854 ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
6855 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006856
Douglas Gregorff790f12009-11-26 00:44:06 +00006857 if (Rec.Context == PotentiallyPotentiallyEvaluated &&
6858 Rec.PotentiallyReferenced) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006859 // Mark any remaining declarations in the current position of the stack
6860 // as "referenced". If they were not meant to be referenced, semantic
6861 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
Douglas Gregorff790f12009-11-26 00:44:06 +00006862 for (PotentiallyReferencedDecls::iterator
6863 I = Rec.PotentiallyReferenced->begin(),
6864 IEnd = Rec.PotentiallyReferenced->end();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006865 I != IEnd; ++I)
6866 MarkDeclarationReferenced(I->first, I->second);
Douglas Gregorff790f12009-11-26 00:44:06 +00006867 }
6868
6869 // When are coming out of an unevaluated context, clear out any
6870 // temporaries that we may have created as part of the evaluation of
6871 // the expression in that context: they aren't relevant because they
6872 // will never be constructed.
6873 if (Rec.Context == Unevaluated &&
6874 ExprTemporaries.size() > Rec.NumTemporaries)
6875 ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
6876 ExprTemporaries.end());
6877
6878 // Destroy the popped expression evaluation record.
6879 Rec.Destroy();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006880}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006881
6882/// \brief Note that the given declaration was referenced in the source code.
6883///
6884/// This routine should be invoke whenever a given declaration is referenced
6885/// in the source code, and where that reference occurred. If this declaration
6886/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6887/// C99 6.9p3), then the declaration will be marked as used.
6888///
6889/// \param Loc the location where the declaration was referenced.
6890///
6891/// \param D the declaration that has been referenced by the source code.
6892void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6893 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00006894
Douglas Gregor77b50e12009-06-22 23:06:13 +00006895 if (D->isUsed())
6896 return;
Mike Stump11289f42009-09-09 15:08:12 +00006897
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00006898 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6899 // template or not. The reason for this is that unevaluated expressions
6900 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6901 // -Wunused-parameters)
6902 if (isa<ParmVarDecl>(D) ||
6903 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006904 D->setUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00006905
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006906 // Do not mark anything as "used" within a dependent context; wait for
6907 // an instantiation.
6908 if (CurContext->isDependentContext())
6909 return;
Mike Stump11289f42009-09-09 15:08:12 +00006910
Douglas Gregorff790f12009-11-26 00:44:06 +00006911 switch (ExprEvalContexts.back().Context) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006912 case Unevaluated:
6913 // We are in an expression that is not potentially evaluated; do nothing.
6914 return;
Mike Stump11289f42009-09-09 15:08:12 +00006915
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006916 case PotentiallyEvaluated:
6917 // We are in a potentially-evaluated expression, so this declaration is
6918 // "used"; handle this below.
6919 break;
Mike Stump11289f42009-09-09 15:08:12 +00006920
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006921 case PotentiallyPotentiallyEvaluated:
6922 // We are in an expression that may be potentially evaluated; queue this
6923 // declaration reference until we know whether the expression is
6924 // potentially evaluated.
Douglas Gregorff790f12009-11-26 00:44:06 +00006925 ExprEvalContexts.back().addReferencedDecl(Loc, D);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006926 return;
6927 }
Mike Stump11289f42009-09-09 15:08:12 +00006928
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006929 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00006930 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006931 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00006932 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6933 if (!Constructor->isUsed())
6934 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00006935 } else if (Constructor->isImplicit() &&
Mike Stump12b8ce12009-08-04 21:02:39 +00006936 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006937 if (!Constructor->isUsed())
6938 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6939 }
Anders Carlsson82fccd02009-12-07 08:24:59 +00006940
6941 MaybeMarkVirtualMembersReferenced(Loc, Constructor);
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006942 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6943 if (Destructor->isImplicit() && !Destructor->isUsed())
6944 DefineImplicitDestructor(Loc, Destructor);
Mike Stump11289f42009-09-09 15:08:12 +00006945
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006946 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6947 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6948 MethodDecl->getOverloadedOperator() == OO_Equal) {
6949 if (!MethodDecl->isUsed())
6950 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6951 }
6952 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00006953 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00006954 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00006955 // class templates.
Douglas Gregorafca3b42009-10-27 20:53:28 +00006956 if (!Function->getBody() && Function->isImplicitlyInstantiable()) {
Douglas Gregor06db9f52009-10-12 20:18:28 +00006957 bool AlreadyInstantiated = false;
6958 if (FunctionTemplateSpecializationInfo *SpecInfo
6959 = Function->getTemplateSpecializationInfo()) {
6960 if (SpecInfo->getPointOfInstantiation().isInvalid())
6961 SpecInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00006962 else if (SpecInfo->getTemplateSpecializationKind()
6963 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00006964 AlreadyInstantiated = true;
6965 } else if (MemberSpecializationInfo *MSInfo
6966 = Function->getMemberSpecializationInfo()) {
6967 if (MSInfo->getPointOfInstantiation().isInvalid())
6968 MSInfo->setPointOfInstantiation(Loc);
Douglas Gregorafca3b42009-10-27 20:53:28 +00006969 else if (MSInfo->getTemplateSpecializationKind()
6970 == TSK_ImplicitInstantiation)
Douglas Gregor06db9f52009-10-12 20:18:28 +00006971 AlreadyInstantiated = true;
6972 }
6973
6974 if (!AlreadyInstantiated)
6975 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6976 }
6977
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006978 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006979 Function->setUsed(true);
6980 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00006981 }
Mike Stump11289f42009-09-09 15:08:12 +00006982
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006983 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006984 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00006985 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00006986 Var->getInstantiatedFromStaticDataMember()) {
6987 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6988 assert(MSInfo && "Missing member specialization information?");
6989 if (MSInfo->getPointOfInstantiation().isInvalid() &&
6990 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6991 MSInfo->setPointOfInstantiation(Loc);
6992 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6993 }
6994 }
Mike Stump11289f42009-09-09 15:08:12 +00006995
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006996 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006997
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006998 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006999 return;
Sam Weinigbae69142009-09-11 03:29:30 +00007000 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007001}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00007002
7003bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7004 CallExpr *CE, FunctionDecl *FD) {
7005 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7006 return false;
7007
7008 PartialDiagnostic Note =
7009 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7010 << FD->getDeclName() : PDiag();
7011 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7012
7013 if (RequireCompleteType(Loc, ReturnType,
7014 FD ?
7015 PDiag(diag::err_call_function_incomplete_return)
7016 << CE->getSourceRange() << FD->getDeclName() :
7017 PDiag(diag::err_call_incomplete_return)
7018 << CE->getSourceRange(),
7019 std::make_pair(NoteLoc, Note)))
7020 return true;
7021
7022 return false;
7023}
7024
John McCalld5707ab2009-10-12 21:59:07 +00007025// Diagnose the common s/=/==/ typo. Note that adding parentheses
7026// will prevent this condition from triggering, which is what we want.
7027void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7028 SourceLocation Loc;
7029
John McCall0506e4a2009-11-11 02:41:58 +00007030 unsigned diagnostic = diag::warn_condition_is_assignment;
7031
John McCalld5707ab2009-10-12 21:59:07 +00007032 if (isa<BinaryOperator>(E)) {
7033 BinaryOperator *Op = cast<BinaryOperator>(E);
7034 if (Op->getOpcode() != BinaryOperator::Assign)
7035 return;
7036
John McCallb0e419e2009-11-12 00:06:05 +00007037 // Greylist some idioms by putting them into a warning subcategory.
7038 if (ObjCMessageExpr *ME
7039 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7040 Selector Sel = ME->getSelector();
7041
John McCallb0e419e2009-11-12 00:06:05 +00007042 // self = [<foo> init...]
7043 if (isSelfExpr(Op->getLHS())
7044 && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7045 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7046
7047 // <foo> = [<bar> nextObject]
7048 else if (Sel.isUnarySelector() &&
7049 Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7050 diagnostic = diag::warn_condition_is_idiomatic_assignment;
7051 }
John McCall0506e4a2009-11-11 02:41:58 +00007052
John McCalld5707ab2009-10-12 21:59:07 +00007053 Loc = Op->getOperatorLoc();
7054 } else if (isa<CXXOperatorCallExpr>(E)) {
7055 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7056 if (Op->getOperator() != OO_Equal)
7057 return;
7058
7059 Loc = Op->getOperatorLoc();
7060 } else {
7061 // Not an assignment.
7062 return;
7063 }
7064
John McCalld5707ab2009-10-12 21:59:07 +00007065 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00007066 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCalld5707ab2009-10-12 21:59:07 +00007067
John McCall0506e4a2009-11-11 02:41:58 +00007068 Diag(Loc, diagnostic)
John McCalld5707ab2009-10-12 21:59:07 +00007069 << E->getSourceRange()
7070 << CodeModificationHint::CreateInsertion(Open, "(")
7071 << CodeModificationHint::CreateInsertion(Close, ")");
7072}
7073
7074bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7075 DiagnoseAssignmentAsCondition(E);
7076
7077 if (!E->isTypeDependent()) {
7078 DefaultFunctionArrayConversion(E);
7079
7080 QualType T = E->getType();
7081
7082 if (getLangOptions().CPlusPlus) {
7083 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7084 return true;
7085 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7086 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7087 << T << E->getSourceRange();
7088 return true;
7089 }
7090 }
7091
7092 return false;
7093}