blob: 17956e65ae583c1548e90e1c55d0116d84d396d1 [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"
Chris Lattnercb6a3822006-11-10 06:20:45 +000015#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000017#include "clang/AST/DeclTemplate.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000018#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000019#include "clang/AST/ExprObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000020#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000021#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000022#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/Lex/LiteralSupport.h"
24#include "clang/Lex/Preprocessor.h"
Steve Naroffc540d662008-09-03 18:15:37 +000025#include "clang/Parse/DeclSpec.h"
Chris Lattner07d754a2008-10-26 23:43:26 +000026#include "clang/Parse/Designator.h"
Steve Naroffc540d662008-09-03 18:15:37 +000027#include "clang/Parse/Scope.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000028using namespace clang;
29
David Chisnall9f57c292009-08-17 16:35:33 +000030
Douglas Gregor171c45a2009-02-18 21:56:37 +000031/// \brief Determine whether the use of this declaration is valid, and
32/// emit any corresponding diagnostics.
33///
34/// This routine diagnoses various problems with referencing
35/// declarations that can occur when using a declaration. For example,
36/// it might warn if a deprecated or unavailable declaration is being
37/// used, or produce an error (and return true) if a C++0x deleted
38/// function is being used.
39///
40/// \returns true if there was an error (this declaration cannot be
41/// referenced), false otherwise.
42bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000043 // See if the decl is deprecated.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000044 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000045 // Implementing deprecated stuff requires referencing deprecated
46 // stuff. Don't warn if we are implementing a deprecated
47 // construct.
Chris Lattner46d6b132009-02-16 19:35:30 +000048 bool isSilenced = false;
Mike Stump11289f42009-09-09 15:08:12 +000049
Chris Lattner46d6b132009-02-16 19:35:30 +000050 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
51 // If this reference happens *in* a deprecated function or method, don't
52 // warn.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000053 isSilenced = ND->getAttr<DeprecatedAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000054
Chris Lattner46d6b132009-02-16 19:35:30 +000055 // If this is an Objective-C method implementation, check to see if the
56 // method was deprecated on the declaration, not the definition.
57 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
58 // The semantic decl context of a ObjCMethodDecl is the
59 // ObjCImplementationDecl.
60 if (ObjCImplementationDecl *Impl
61 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
Mike Stump11289f42009-09-09 15:08:12 +000062
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +000063 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
Chris Lattner46d6b132009-02-16 19:35:30 +000064 MD->isInstanceMethod());
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000065 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
Chris Lattner46d6b132009-02-16 19:35:30 +000066 }
67 }
68 }
Mike Stump11289f42009-09-09 15:08:12 +000069
Chris Lattner46d6b132009-02-16 19:35:30 +000070 if (!isSilenced)
Chris Lattner4bf74fd2009-02-15 22:43:40 +000071 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
72 }
73
Douglas Gregor171c45a2009-02-18 21:56:37 +000074 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +000075 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +000076 if (FD->isDeleted()) {
77 Diag(Loc, diag::err_deleted_function_use);
78 Diag(D->getLocation(), diag::note_unavailable_here) << true;
79 return true;
80 }
Douglas Gregorde681d42009-02-24 04:26:15 +000081 }
Douglas Gregor171c45a2009-02-18 21:56:37 +000082
83 // See if the decl is unavailable
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000084 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner4bf74fd2009-02-15 22:43:40 +000085 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregor171c45a2009-02-18 21:56:37 +000086 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
87 }
88
Douglas Gregor171c45a2009-02-18 21:56:37 +000089 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +000090}
91
Fariborz Jahanian027b8862009-05-13 18:09:35 +000092/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
Mike Stump11289f42009-09-09 15:08:12 +000093/// (and other functions in future), which have been declared with sentinel
Fariborz Jahanian027b8862009-05-13 18:09:35 +000094/// attribute. It warns if call does not have the sentinel argument.
95///
96void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +000097 Expr **Args, unsigned NumArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +000098 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +000099 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000100 return;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000101 int sentinelPos = attr->getSentinel();
102 int nullPos = attr->getNullPos();
Mike Stump11289f42009-09-09 15:08:12 +0000103
Mike Stump87c57ac2009-05-16 07:39:55 +0000104 // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
105 // base class. Then we won't be needing two versions of the same code.
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000106 unsigned int i = 0;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000107 bool warnNotEnoughArgs = false;
108 int isMethod = 0;
109 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
110 // skip over named parameters.
111 ObjCMethodDecl::param_iterator P, E = MD->param_end();
112 for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
113 if (nullPos)
114 --nullPos;
115 else
116 ++i;
117 }
118 warnNotEnoughArgs = (P != E || i >= NumArgs);
119 isMethod = 1;
Mike Stump12b8ce12009-08-04 21:02:39 +0000120 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000121 // skip over named parameters.
122 ObjCMethodDecl::param_iterator P, E = FD->param_end();
123 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
124 if (nullPos)
125 --nullPos;
126 else
127 ++i;
128 }
129 warnNotEnoughArgs = (P != E || i >= NumArgs);
Mike Stump12b8ce12009-08-04 21:02:39 +0000130 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000131 // block or function pointer call.
132 QualType Ty = V->getType();
133 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000134 const FunctionType *FT = Ty->isFunctionPointerType()
John McCall9dd450b2009-09-21 23:43:11 +0000135 ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
136 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000137 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
138 unsigned NumArgsInProto = Proto->getNumArgs();
139 unsigned k;
140 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
141 if (nullPos)
142 --nullPos;
143 else
144 ++i;
145 }
146 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
147 }
148 if (Ty->isBlockPointerType())
149 isMethod = 2;
Mike Stump12b8ce12009-08-04 21:02:39 +0000150 } else
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000151 return;
Mike Stump12b8ce12009-08-04 21:02:39 +0000152 } else
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000153 return;
154
155 if (warnNotEnoughArgs) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000156 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000157 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000158 return;
159 }
160 int sentinel = i;
161 while (sentinelPos > 0 && i < NumArgs-1) {
162 --sentinelPos;
163 ++i;
164 }
165 if (sentinelPos > 0) {
166 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000167 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000168 return;
169 }
170 while (i < NumArgs-1) {
171 ++i;
172 ++sentinel;
173 }
174 Expr *sentinelExpr = Args[sentinel];
175 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
Douglas Gregor56751b52009-09-25 04:25:58 +0000176 !sentinelExpr->isNullPointerConstant(Context,
177 Expr::NPC_ValueDependentIsNull))) {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000178 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000179 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000180 }
181 return;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000182}
183
Douglas Gregor87f95b02009-02-26 21:00:50 +0000184SourceRange Sema::getExprRange(ExprTy *E) const {
185 Expr *Ex = (Expr *)E;
186 return Ex? Ex->getSourceRange() : SourceRange();
187}
188
Chris Lattner513165e2008-07-25 21:10:04 +0000189//===----------------------------------------------------------------------===//
190// Standard Promotions and Conversions
191//===----------------------------------------------------------------------===//
192
Chris Lattner513165e2008-07-25 21:10:04 +0000193/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
194void Sema::DefaultFunctionArrayConversion(Expr *&E) {
195 QualType Ty = E->getType();
196 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
197
Chris Lattner513165e2008-07-25 21:10:04 +0000198 if (Ty->isFunctionType())
Mike Stump11289f42009-09-09 15:08:12 +0000199 ImpCastExprToType(E, Context.getPointerType(Ty),
Anders Carlsson6904f642009-09-01 20:37:18 +0000200 CastExpr::CK_FunctionToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000201 else if (Ty->isArrayType()) {
202 // In C90 mode, arrays only promote to pointers if the array expression is
203 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
204 // type 'array of type' is converted to an expression that has type 'pointer
205 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
206 // that has type 'array of type' ...". The relevant change is "an lvalue"
207 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000208 //
209 // C++ 4.2p1:
210 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
211 // T" can be converted to an rvalue of type "pointer to T".
212 //
213 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
214 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000215 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
216 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner61f60a02008-07-25 21:33:13 +0000217 }
Chris Lattner513165e2008-07-25 21:10:04 +0000218}
219
220/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000221/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner513165e2008-07-25 21:10:04 +0000222/// sometimes surpressed. For example, the array->pointer conversion doesn't
223/// apply if the array is an argument to the sizeof or address (&) operators.
224/// In these instances, this routine should *not* be called.
225Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
226 QualType Ty = Expr->getType();
227 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000228
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000229 // C99 6.3.1.1p2:
230 //
231 // The following may be used in an expression wherever an int or
232 // unsigned int may be used:
233 // - an object or expression with an integer type whose integer
234 // conversion rank is less than or equal to the rank of int
235 // and unsigned int.
236 // - A bit-field of type _Bool, int, signed int, or unsigned int.
237 //
238 // If an int can represent all values of the original type, the
239 // value is converted to an int; otherwise, it is converted to an
240 // unsigned int. These are called the integer promotions. All
241 // other types are unchanged by the integer promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000242 QualType PTy = Context.isPromotableBitField(Expr);
243 if (!PTy.isNull()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +0000244 ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
Eli Friedman629ffb92009-08-20 04:21:42 +0000245 return Expr;
246 }
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000247 if (Ty->isPromotableIntegerType()) {
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000248 QualType PT = Context.getPromotedIntegerType(Ty);
Eli Friedman06ed2a52009-10-20 08:27:19 +0000249 ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000250 return Expr;
Eli Friedman629ffb92009-08-20 04:21:42 +0000251 }
252
Douglas Gregor8d9c5092009-05-01 20:41:21 +0000253 DefaultFunctionArrayConversion(Expr);
Chris Lattner513165e2008-07-25 21:10:04 +0000254 return Expr;
255}
256
Chris Lattner2ce500f2008-07-25 22:25:12 +0000257/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000258/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000259/// double. All other argument types are converted by UsualUnaryConversions().
260void Sema::DefaultArgumentPromotion(Expr *&Expr) {
261 QualType Ty = Expr->getType();
262 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000263
Chris Lattner2ce500f2008-07-25 22:25:12 +0000264 // If this is a 'float' (CVR qualified or typedef) promote to double.
John McCall9dd450b2009-09-21 23:43:11 +0000265 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
Chris Lattner2ce500f2008-07-25 22:25:12 +0000266 if (BT->getKind() == BuiltinType::Float)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000267 return ImpCastExprToType(Expr, Context.DoubleTy,
268 CastExpr::CK_FloatingCast);
Mike Stump11289f42009-09-09 15:08:12 +0000269
Chris Lattner2ce500f2008-07-25 22:25:12 +0000270 UsualUnaryConversions(Expr);
271}
272
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000273/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
274/// will warn if the resulting type is not a POD type, and rejects ObjC
275/// interfaces passed by value. This returns true if the argument type is
276/// completely illegal.
277bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlssona7d069d2009-01-16 16:48:51 +0000278 DefaultArgumentPromotion(Expr);
Mike Stump11289f42009-09-09 15:08:12 +0000279
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000280 if (Expr->getType()->isObjCInterfaceType()) {
281 Diag(Expr->getLocStart(),
282 diag::err_cannot_pass_objc_interface_to_vararg)
283 << Expr->getType() << CT;
284 return true;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000285 }
Mike Stump11289f42009-09-09 15:08:12 +0000286
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000287 if (!Expr->getType()->isPODType())
288 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
289 << Expr->getType() << CT;
290
291 return false;
Anders Carlssona7d069d2009-01-16 16:48:51 +0000292}
293
294
Chris Lattner513165e2008-07-25 21:10:04 +0000295/// UsualArithmeticConversions - Performs various conversions that are common to
296/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000297/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000298/// responsible for emitting appropriate error diagnostics.
299/// FIXME: verify the conversion rules for "complex int" are consistent with
300/// GCC.
301QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
302 bool isCompAssign) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000303 if (!isCompAssign)
Chris Lattner513165e2008-07-25 21:10:04 +0000304 UsualUnaryConversions(lhsExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000305
306 UsualUnaryConversions(rhsExpr);
Douglas Gregora11693b2008-11-12 17:17:38 +0000307
Mike Stump11289f42009-09-09 15:08:12 +0000308 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000309 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +0000310 QualType lhs =
311 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000312 QualType rhs =
Chris Lattner574dee62008-07-26 22:17:49 +0000313 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000314
315 // If both types are identical, no conversion is needed.
316 if (lhs == rhs)
317 return lhs;
318
319 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
320 // The caller can deal with this (e.g. pointer + int).
321 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
322 return lhs;
323
Douglas Gregord2c2d172009-05-02 00:36:19 +0000324 // Perform bitfield promotions.
Eli Friedman629ffb92009-08-20 04:21:42 +0000325 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000326 if (!LHSBitfieldPromoteTy.isNull())
327 lhs = LHSBitfieldPromoteTy;
Eli Friedman629ffb92009-08-20 04:21:42 +0000328 QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000329 if (!RHSBitfieldPromoteTy.isNull())
330 rhs = RHSBitfieldPromoteTy;
331
Eli Friedman5ae98ee2009-08-19 07:44:53 +0000332 QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000333 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +0000334 ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
335 ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
Douglas Gregora11693b2008-11-12 17:17:38 +0000336 return destType;
337}
338
Chris Lattner513165e2008-07-25 21:10:04 +0000339//===----------------------------------------------------------------------===//
340// Semantic Analysis for various Expression Types
341//===----------------------------------------------------------------------===//
342
343
Steve Naroff83895f72007-09-16 03:34:24 +0000344/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +0000345/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
346/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
347/// multiple tokens. However, the common case is that StringToks points to one
348/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000349///
350Action::OwningExprResult
Steve Naroff83895f72007-09-16 03:34:24 +0000351Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +0000352 assert(NumStringToks && "Must have at least one string!");
353
Chris Lattner8a24e582009-01-16 18:51:42 +0000354 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +0000355 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000356 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +0000357
Chris Lattner23b7eb62007-06-15 23:05:46 +0000358 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +0000359 for (unsigned i = 0; i != NumStringToks; ++i)
360 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +0000361
Chris Lattner36fc8792008-02-11 00:02:17 +0000362 QualType StrTy = Context.CharTy;
Argyrios Kyrtzidiscbad7252008-08-09 17:20:01 +0000363 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattner36fc8792008-02-11 00:02:17 +0000364 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +0000365
366 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
367 if (getLangOptions().CPlusPlus)
368 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +0000369
Chris Lattner36fc8792008-02-11 00:02:17 +0000370 // Get an array type for the string, according to C99 6.4.5. This includes
371 // the nul terminator character as well as the string length for pascal
372 // strings.
373 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +0000374 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +0000375 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +0000376
Chris Lattner5b183d82006-11-10 05:03:26 +0000377 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Mike Stump11289f42009-09-09 15:08:12 +0000378 return Owned(StringLiteral::Create(Context, Literal.GetString(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +0000379 Literal.GetStringLength(),
380 Literal.AnyWide, StrTy,
381 &StringTokLocs[0],
382 StringTokLocs.size()));
Chris Lattner5b183d82006-11-10 05:03:26 +0000383}
384
Chris Lattner2a9d9892008-10-20 05:16:36 +0000385/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
386/// CurBlock to VD should cause it to be snapshotted (as we do for auto
387/// variables defined outside the block) or false if this is not needed (e.g.
388/// for values inside the block or for globals).
389///
Chris Lattner497d7b02009-04-21 22:26:47 +0000390/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
391/// up-to-date.
392///
Chris Lattner2a9d9892008-10-20 05:16:36 +0000393static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
394 ValueDecl *VD) {
395 // If the value is defined inside the block, we couldn't snapshot it even if
396 // we wanted to.
397 if (CurBlock->TheDecl == VD->getDeclContext())
398 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000399
Chris Lattner2a9d9892008-10-20 05:16:36 +0000400 // If this is an enum constant or function, it is constant, don't snapshot.
401 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
402 return false;
403
404 // If this is a reference to an extern, static, or global variable, no need to
405 // snapshot it.
406 // FIXME: What about 'const' variables in C++?
407 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner497d7b02009-04-21 22:26:47 +0000408 if (!Var->hasLocalStorage())
409 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000410
Chris Lattner497d7b02009-04-21 22:26:47 +0000411 // Blocks that have these can't be constant.
412 CurBlock->hasBlockDeclRefExprs = true;
413
414 // If we have nested blocks, the decl may be declared in an outer block (in
415 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
416 // be defined outside all of the current blocks (in which case the blocks do
417 // all get the bit). Walk the nesting chain.
418 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
419 NextBlock = NextBlock->PrevBlockInfo) {
420 // If we found the defining block for the variable, don't mark the block as
421 // having a reference outside it.
422 if (NextBlock->TheDecl == VD->getDeclContext())
423 break;
Mike Stump11289f42009-09-09 15:08:12 +0000424
Chris Lattner497d7b02009-04-21 22:26:47 +0000425 // Otherwise, the DeclRef from the inner block causes the outer one to need
426 // a snapshot as well.
427 NextBlock->hasBlockDeclRefExprs = true;
428 }
Mike Stump11289f42009-09-09 15:08:12 +0000429
Chris Lattner2a9d9892008-10-20 05:16:36 +0000430 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000431}
432
Chris Lattner2a9d9892008-10-20 05:16:36 +0000433
434
Steve Naroff30d242c2007-09-15 18:49:24 +0000435/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattnerac18be92006-11-20 06:49:47 +0000436/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroff157c4032008-03-19 23:46:26 +0000437/// identifier is used in a function call context.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000438/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000439/// class or namespace that the identifier must be a member of.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000440Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
441 IdentifierInfo &II,
442 bool HasTrailingLParen,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000443 const CXXScopeSpec *SS,
444 bool isAddressOfOperand) {
445 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregorb8a9a412009-02-04 15:01:18 +0000446 isAddressOfOperand);
Douglas Gregor4ea80432008-11-18 15:03:34 +0000447}
448
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000449/// BuildDeclRefExpr - Build a DeclRefExpr.
Anders Carlsson946b86d2009-06-24 00:10:43 +0000450Sema::OwningExprResult
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000451Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
452 bool TypeDependent, bool ValueDependent,
453 const CXXScopeSpec *SS) {
Anders Carlsson364035d12009-06-26 19:16:07 +0000454 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
455 Diag(Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000456 diag::err_auto_variable_cannot_appear_in_own_initializer)
Anders Carlsson364035d12009-06-26 19:16:07 +0000457 << D->getDeclName();
458 return ExprError();
459 }
Mike Stump11289f42009-09-09 15:08:12 +0000460
Anders Carlsson946b86d2009-06-24 00:10:43 +0000461 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
462 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
463 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
464 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
Mike Stump11289f42009-09-09 15:08:12 +0000465 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000466 << D->getIdentifier() << FD->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000467 Diag(D->getLocation(), diag::note_local_variable_declared_here)
Anders Carlsson946b86d2009-06-24 00:10:43 +0000468 << D->getIdentifier();
469 return ExprError();
470 }
471 }
472 }
473 }
Mike Stump11289f42009-09-09 15:08:12 +0000474
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000475 MarkDeclarationReferenced(Loc, D);
Mike Stump11289f42009-09-09 15:08:12 +0000476
Douglas Gregor4bd90e52009-10-23 18:54:35 +0000477 return Owned(DeclRefExpr::Create(Context,
478 SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
479 SS? SS->getRange() : SourceRange(),
480 D, Loc,
481 Ty, TypeDependent, ValueDependent));
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000482}
483
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000484/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
485/// variable corresponding to the anonymous union or struct whose type
486/// is Record.
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000487static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
488 RecordDecl *Record) {
Mike Stump11289f42009-09-09 15:08:12 +0000489 assert(Record->isAnonymousStructOrUnion() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000490 "Record must be an anonymous struct or union!");
Mike Stump11289f42009-09-09 15:08:12 +0000491
Mike Stump87c57ac2009-05-16 07:39:55 +0000492 // FIXME: Once Decls are directly linked together, this will be an O(1)
493 // operation rather than a slow walk through DeclContext's vector (which
494 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000495 DeclContext *Ctx = Record->getDeclContext();
Mike Stump11289f42009-09-09 15:08:12 +0000496 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000497 DEnd = Ctx->decls_end();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000498 D != DEnd; ++D) {
499 if (*D == Record) {
500 // The object for the anonymous struct/union directly
501 // follows its type in the list of declarations.
502 ++D;
503 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000504 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000505 return *D;
506 }
507 }
508
509 assert(false && "Missing object for anonymous record");
510 return 0;
511}
512
Douglas Gregord5846a12009-04-15 06:41:24 +0000513/// \brief Given a field that represents a member of an anonymous
514/// struct/union, build the path from that field's context to the
515/// actual member.
516///
517/// Construct the sequence of field member references we'll have to
518/// perform to get to the field in the anonymous union/struct. The
519/// list of members is built from the field outward, so traverse it
520/// backwards to go from an object in the current context to the field
521/// we found.
522///
523/// \returns The variable from which the field access should begin,
524/// for an anonymous struct/union that is not a member of another
525/// class. Otherwise, returns NULL.
526VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
527 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000528 assert(Field->getDeclContext()->isRecord() &&
529 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
530 && "Field must be stored inside an anonymous struct or union");
531
Douglas Gregord5846a12009-04-15 06:41:24 +0000532 Path.push_back(Field);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000533 VarDecl *BaseObject = 0;
534 DeclContext *Ctx = Field->getDeclContext();
535 do {
536 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000537 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000538 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregord5846a12009-04-15 06:41:24 +0000539 Path.push_back(AnonField);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000540 else {
541 BaseObject = cast<VarDecl>(AnonObject);
542 break;
543 }
544 Ctx = Ctx->getParent();
Mike Stump11289f42009-09-09 15:08:12 +0000545 } while (Ctx->isRecord() &&
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000546 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregord5846a12009-04-15 06:41:24 +0000547
548 return BaseObject;
549}
550
551Sema::OwningExprResult
552Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
553 FieldDecl *Field,
554 Expr *BaseObjectExpr,
555 SourceLocation OpLoc) {
556 llvm::SmallVector<FieldDecl *, 4> AnonFields;
Mike Stump11289f42009-09-09 15:08:12 +0000557 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
Douglas Gregord5846a12009-04-15 06:41:24 +0000558 AnonFields);
559
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000560 // Build the expression that refers to the base object, from
561 // which we will build a sequence of member references to each
562 // of the anonymous union objects and, eventually, the field we
563 // found via name lookup.
564 bool BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000565 Qualifiers BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000566 if (BaseObject) {
567 // BaseObject is an anonymous struct/union variable (and is,
568 // therefore, not part of another non-anonymous record).
Ted Kremenek5a201952009-02-07 01:47:29 +0000569 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000570 MarkDeclarationReferenced(Loc, BaseObject);
Steve Narofff6009ed2009-01-21 00:14:39 +0000571 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000572 SourceLocation());
John McCall8ccfcb52009-09-24 19:53:00 +0000573 BaseQuals
574 = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000575 } else if (BaseObjectExpr) {
576 // The caller provided the base object expression. Determine
577 // whether its a pointer and whether it adds any qualifiers to the
578 // anonymous struct/union fields we're looking into.
579 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000580 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000581 BaseObjectIsPointer = true;
582 ObjectType = ObjectPtr->getPointeeType();
583 }
John McCall8ccfcb52009-09-24 19:53:00 +0000584 BaseQuals
585 = Context.getCanonicalType(ObjectType).getQualifiers();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000586 } else {
587 // We've found a member of an anonymous struct/union that is
588 // inside a non-anonymous struct/union, so in a well-formed
589 // program our base object expression is "this".
590 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
591 if (!MD->isStatic()) {
Mike Stump11289f42009-09-09 15:08:12 +0000592 QualType AnonFieldType
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000593 = Context.getTagDeclType(
594 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
595 QualType ThisType = Context.getTagDeclType(MD->getParent());
Mike Stump11289f42009-09-09 15:08:12 +0000596 if ((Context.getCanonicalType(AnonFieldType)
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000597 == Context.getCanonicalType(ThisType)) ||
598 IsDerivedFrom(ThisType, AnonFieldType)) {
599 // Our base object expression is "this".
Steve Narofff6009ed2009-01-21 00:14:39 +0000600 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump4e1f26a2009-02-19 03:04:26 +0000601 MD->getThisType(Context));
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000602 BaseObjectIsPointer = true;
603 }
604 } else {
Sebastian Redlffbcf962009-01-18 18:53:16 +0000605 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
606 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000607 }
John McCall8ccfcb52009-09-24 19:53:00 +0000608 BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000609 }
610
Mike Stump11289f42009-09-09 15:08:12 +0000611 if (!BaseObjectExpr)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000612 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
613 << Field->getDeclName());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000614 }
615
616 // Build the implicit member references to the field of the
617 // anonymous struct/union.
618 Expr *Result = BaseObjectExpr;
John McCall8ccfcb52009-09-24 19:53:00 +0000619 Qualifiers ResultQuals = BaseQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000620 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
621 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
622 FI != FIEnd; ++FI) {
623 QualType MemberType = (*FI)->getType();
John McCall8ccfcb52009-09-24 19:53:00 +0000624 Qualifiers MemberTypeQuals =
625 Context.getCanonicalType(MemberType).getQualifiers();
626
627 // CVR attributes from the base are picked up by members,
628 // except that 'mutable' members don't pick up 'const'.
629 if ((*FI)->isMutable())
630 ResultQuals.removeConst();
631
632 // GC attributes are never picked up by members.
633 ResultQuals.removeObjCGCAttr();
634
635 // TR 18037 does not allow fields to be declared with address spaces.
636 assert(!MemberTypeQuals.hasAddressSpace());
637
638 Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
639 if (NewQuals != MemberTypeQuals)
640 MemberType = Context.getQualifiedType(MemberType, NewQuals);
641
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000642 MarkDeclarationReferenced(Loc, *FI);
Douglas Gregorc1905232009-08-26 22:36:53 +0000643 // FIXME: Might this end up being a qualified name?
Steve Narofff6009ed2009-01-21 00:14:39 +0000644 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
645 OpLoc, MemberType);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000646 BaseObjectIsPointer = false;
John McCall8ccfcb52009-09-24 19:53:00 +0000647 ResultQuals = NewQuals;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000648 }
649
Sebastian Redlffbcf962009-01-18 18:53:16 +0000650 return Owned(Result);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000651}
652
Douglas Gregor4ea80432008-11-18 15:03:34 +0000653/// ActOnDeclarationNameExpr - The parser has read some kind of name
654/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
655/// performs lookup on that name and returns an expression that refers
656/// to that name. This routine isn't directly called from the parser,
657/// because the parser doesn't know about DeclarationName. Rather,
658/// this routine is called by ActOnIdentifierExpr,
659/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
660/// which form the DeclarationName from the corresponding syntactic
661/// forms.
662///
663/// HasTrailingLParen indicates whether this identifier is used in a
664/// function call context. LookupCtx is only used for a C++
665/// qualified-id (foo::bar) to indicate the class or namespace that
666/// the identifier must be a member of.
Douglas Gregorb0846b02008-12-06 00:22:45 +0000667///
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000668/// isAddressOfOperand means that this expression is the direct operand
669/// of an address-of operator. This matters because this is the only
670/// situation where a qualified name referencing a non-static member may
671/// appear outside a member function of this class.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000672Sema::OwningExprResult
673Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
674 DeclarationName Name, bool HasTrailingLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000675 const CXXScopeSpec *SS,
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000676 bool isAddressOfOperand) {
Chris Lattner59a25942008-03-31 00:36:02 +0000677 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregored8f2882009-01-30 01:04:22 +0000678 if (SS && SS->isInvalid())
679 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +0000680
681 // C++ [temp.dep.expr]p3:
682 // An id-expression is type-dependent if it contains:
683 // -- a nested-name-specifier that contains a class-name that
684 // names a dependent type.
Douglas Gregor82dbbd72009-05-29 14:49:33 +0000685 // FIXME: Member of the current instantiation.
Douglas Gregor90a1a652009-03-19 17:26:29 +0000686 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregorf21eb492009-03-26 23:50:42 +0000687 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
Mike Stump11289f42009-09-09 15:08:12 +0000688 Loc, SS->getRange(),
Anders Carlsson03f89b12009-07-09 00:05:08 +0000689 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
690 isAddressOfOperand));
Douglas Gregor90a1a652009-03-19 17:26:29 +0000691 }
692
John McCall9f3059a2009-10-09 21:13:30 +0000693 LookupResult Lookup;
694 LookupParsedName(Lookup, S, SS, Name, LookupOrdinaryName, false, true, Loc);
Douglas Gregor960b5bc2009-01-15 00:26:24 +0000695
Sebastian Redlffbcf962009-01-18 18:53:16 +0000696 if (Lookup.isAmbiguous()) {
697 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
698 SS && SS->isSet() ? SS->getRange()
699 : SourceRange());
700 return ExprError();
Chris Lattnercd2a8c52009-04-24 22:30:50 +0000701 }
Mike Stump11289f42009-09-09 15:08:12 +0000702
John McCall9f3059a2009-10-09 21:13:30 +0000703 NamedDecl *D = Lookup.getAsSingleDecl(Context);
Douglas Gregorb0846b02008-12-06 00:22:45 +0000704
Chris Lattner59a25942008-03-31 00:36:02 +0000705 // If this reference is in an Objective-C method, then ivar lookup happens as
706 // well.
Douglas Gregor4ea80432008-11-18 15:03:34 +0000707 IdentifierInfo *II = Name.getAsIdentifierInfo();
708 if (II && getCurMethodDecl()) {
Chris Lattner59a25942008-03-31 00:36:02 +0000709 // There are two cases to handle here. 1) scoped lookup could have failed,
710 // in which case we should look for an ivar. 2) scoped lookup could have
Mike Stump11289f42009-09-09 15:08:12 +0000711 // found a decl, but that decl is outside the current instance method (i.e.
712 // a global variable). In these two cases, we do a lookup for an ivar with
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000713 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000714 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +0000715 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +0000716 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000717 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner50afe312009-02-16 17:19:12 +0000718 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregor171c45a2009-02-18 21:56:37 +0000719 if (DiagnoseUseOfDecl(IV, Loc))
720 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000721
Chris Lattnercd2a8c52009-04-24 22:30:50 +0000722 // If we're referencing an invalid decl, just return this as a silent
723 // error node. The error diagnostic was already emitted on the decl.
724 if (IV->isInvalidDecl())
725 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000726
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000727 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
728 // If a class method attemps to use a free standing ivar, this is
729 // an error.
730 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
731 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
732 << IV->getDeclName());
733 // If a class method uses a global variable, even if an ivar with
734 // same name exists, use the global.
735 if (!IsClsMethod) {
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +0000736 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
737 ClassDeclared != IFace)
738 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stump87c57ac2009-05-16 07:39:55 +0000739 // FIXME: This should use a new expr for a direct reference, don't
740 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000741 IdentifierInfo &II = Context.Idents.get("self");
Argyrios Kyrtzidise1a8c622009-07-18 08:49:37 +0000742 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
743 II, false);
Douglas Gregorc9c02ed2009-06-19 23:52:42 +0000744 MarkDeclarationReferenced(Loc, IV);
Mike Stump11289f42009-09-09 15:08:12 +0000745 return Owned(new (Context)
746 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000747 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000748 }
Chris Lattner59a25942008-03-31 00:36:02 +0000749 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000750 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000751 // We should warn if a local variable hides an ivar.
752 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +0000753 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000754 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +0000755 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
756 IFace == ClassDeclared)
Chris Lattnercd2a8c52009-04-24 22:30:50 +0000757 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +0000758 }
Fariborz Jahanianbf8e8422009-03-02 21:55:29 +0000759 }
Steve Naroff0d7c6db2008-08-10 19:10:41 +0000760 // Needed to implement property "super.method" notation.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000761 if (D == 0 && II->isStr("super")) {
Steve Naroffe29c4dd2009-03-05 20:12:00 +0000762 QualType T;
Mike Stump11289f42009-09-09 15:08:12 +0000763
Steve Naroffe29c4dd2009-03-05 20:12:00 +0000764 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff7cae42b2009-07-10 23:34:53 +0000765 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
766 getCurMethodDecl()->getClassInterface()));
Steve Naroffe29c4dd2009-03-05 20:12:00 +0000767 else
768 T = Context.getObjCClassType();
Steve Narofff6009ed2009-01-21 00:14:39 +0000769 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroffebf4cb42008-06-02 23:03:37 +0000770 }
Chris Lattner59a25942008-03-31 00:36:02 +0000771 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +0000772
Douglas Gregor171c45a2009-02-18 21:56:37 +0000773 // Determine whether this name might be a candidate for
774 // argument-dependent lookup.
Mike Stump11289f42009-09-09 15:08:12 +0000775 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
Douglas Gregor171c45a2009-02-18 21:56:37 +0000776 HasTrailingLParen;
777
778 if (ADL && D == 0) {
Douglas Gregorf15f5d32009-02-16 19:28:42 +0000779 // We've seen something of the form
780 //
781 // identifier(
782 //
783 // and we did not find any entity by the name
784 // "identifier". However, this identifier is still subject to
785 // argument-dependent lookup, so keep track of the name.
786 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
787 Context.OverloadTy,
788 Loc));
789 }
790
Chris Lattner17ed4872006-11-20 04:58:19 +0000791 if (D == 0) {
Bill Wendling4073ed52007-02-13 01:51:42 +0000792 // Otherwise, this could be an implicitly declared function reference (legal
Chris Lattner9561a0b2007-01-28 08:20:04 +0000793 // in C90, extension in C99).
Douglas Gregor4ea80432008-11-18 15:03:34 +0000794 if (HasTrailingLParen && II &&
Chris Lattner59a25942008-03-31 00:36:02 +0000795 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregor4ea80432008-11-18 15:03:34 +0000796 D = ImplicitlyDefineFunction(Loc, *II, S);
Steve Naroff92e30f82007-04-02 22:35:25 +0000797 else {
Chris Lattnerac18be92006-11-20 06:49:47 +0000798 // If this name wasn't predeclared and if this is not a function call,
799 // diagnose the problem.
Douglas Gregore40876a2009-10-13 21:16:44 +0000800 if (SS && !SS->isEmpty())
801 return ExprError(Diag(Loc, diag::err_no_member)
802 << Name << computeDeclContext(*SS, false)
803 << SS->getRange());
804 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
Douglas Gregor4ea80432008-11-18 15:03:34 +0000805 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlffbcf962009-01-18 18:53:16 +0000806 return ExprError(Diag(Loc, diag::err_undeclared_use)
807 << Name.getAsString());
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000808 else
Sebastian Redlffbcf962009-01-18 18:53:16 +0000809 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Steve Naroff92e30f82007-04-02 22:35:25 +0000810 }
Chris Lattner17ed4872006-11-20 04:58:19 +0000811 }
Mike Stump11289f42009-09-09 15:08:12 +0000812
Douglas Gregor3256d042009-06-30 15:47:41 +0000813 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
814 // Warn about constructs like:
815 // if (void *X = foo()) { ... } else { X }.
816 // In the else block, the pointer is always false.
Mike Stump11289f42009-09-09 15:08:12 +0000817
Douglas Gregor3256d042009-06-30 15:47:41 +0000818 // FIXME: In a template instantiation, we don't have scope
819 // information to check this property.
820 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
821 Scope *CheckS = S;
822 while (CheckS) {
Mike Stump11289f42009-09-09 15:08:12 +0000823 if (CheckS->isWithinElse() &&
Douglas Gregor3256d042009-06-30 15:47:41 +0000824 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
825 if (Var->getType()->isBooleanType())
826 ExprError(Diag(Loc, diag::warn_value_always_false)
827 << Var->getDeclName());
828 else
829 ExprError(Diag(Loc, diag::warn_value_always_zero)
830 << Var->getDeclName());
831 break;
832 }
Mike Stump11289f42009-09-09 15:08:12 +0000833
Douglas Gregor3256d042009-06-30 15:47:41 +0000834 // Move up one more control parent to check again.
835 CheckS = CheckS->getControlParent();
836 if (CheckS)
837 CheckS = CheckS->getParent();
838 }
839 }
840 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
841 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
842 // C99 DR 316 says that, if a function type comes from a
843 // function definition (without a prototype), that type is only
844 // used for checking compatibility. Therefore, when referencing
845 // the function, we pretend that we don't have the full function
846 // type.
847 if (DiagnoseUseOfDecl(Func, Loc))
848 return ExprError();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000849
Douglas Gregor3256d042009-06-30 15:47:41 +0000850 QualType T = Func->getType();
851 QualType NoProtoType = T;
John McCall9dd450b2009-09-21 23:43:11 +0000852 if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
Douglas Gregor3256d042009-06-30 15:47:41 +0000853 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
854 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
855 }
856 }
Mike Stump11289f42009-09-09 15:08:12 +0000857
Douglas Gregor3256d042009-06-30 15:47:41 +0000858 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
859}
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000860/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian3f150832009-07-29 19:40:11 +0000861bool
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000862Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
863 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
Mike Stump11289f42009-09-09 15:08:12 +0000864 if (CXXRecordDecl *RD =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000865 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
Mike Stump11289f42009-09-09 15:08:12 +0000866 QualType DestType =
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000867 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +0000868 if (DestType->isDependentType() || From->getType()->isDependentType())
869 return false;
870 QualType FromRecordType = From->getType();
871 QualType DestRecordType = DestType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000872 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +0000873 DestType = Context.getPointerType(DestType);
874 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000875 }
Fariborz Jahanian4b12ed12009-07-29 20:41:46 +0000876 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
877 CheckDerivedToBaseConversion(FromRecordType,
878 DestRecordType,
879 From->getSourceRange().getBegin(),
880 From->getSourceRange()))
881 return true;
Anders Carlssona076d142009-07-31 01:23:52 +0000882 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
883 /*isLvalue=*/true);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000884 }
Fariborz Jahanian3f150832009-07-29 19:40:11 +0000885 return false;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +0000886}
Douglas Gregor3256d042009-06-30 15:47:41 +0000887
Douglas Gregorf405d7e2009-08-31 23:41:50 +0000888/// \brief Build a MemberExpr AST node.
Mike Stump11289f42009-09-09 15:08:12 +0000889static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
890 const CXXScopeSpec *SS, NamedDecl *Member,
Douglas Gregorc1905232009-08-26 22:36:53 +0000891 SourceLocation Loc, QualType Ty) {
892 if (SS && SS->isSet())
Mike Stump11289f42009-09-09 15:08:12 +0000893 return MemberExpr::Create(C, Base, isArrow,
Douglas Gregorf405d7e2009-08-31 23:41:50 +0000894 (NestedNameSpecifier *)SS->getScopeRep(),
Mike Stump11289f42009-09-09 15:08:12 +0000895 SS->getRange(), Member, Loc,
Douglas Gregor84f14dd2009-09-01 00:37:14 +0000896 // FIXME: Explicit template argument lists
897 false, SourceLocation(), 0, 0, SourceLocation(),
898 Ty);
Mike Stump11289f42009-09-09 15:08:12 +0000899
Douglas Gregorc1905232009-08-26 22:36:53 +0000900 return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
901}
902
Douglas Gregor3256d042009-06-30 15:47:41 +0000903/// \brief Complete semantic analysis for a reference to the given declaration.
904Sema::OwningExprResult
905Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
906 bool HasTrailingLParen,
Mike Stump11289f42009-09-09 15:08:12 +0000907 const CXXScopeSpec *SS,
Douglas Gregor3256d042009-06-30 15:47:41 +0000908 bool isAddressOfOperand) {
909 assert(D && "Cannot refer to a NULL declaration");
910 DeclarationName Name = D->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +0000911
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000912 // If this is an expression of the form &Class::member, don't build an
913 // implicit member ref, because we want a pointer to the member in general,
914 // not any specific instance's member.
915 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor52537682009-03-19 00:18:19 +0000916 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor2ada0482009-02-04 17:27:36 +0000917 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000918 QualType DType;
919 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
920 DType = FD->getType().getNonReferenceType();
921 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
922 DType = Method->getType();
923 } else if (isa<OverloadedFunctionDecl>(D)) {
924 DType = Context.OverloadTy;
925 }
926 // Could be an inner type. That's diagnosed below, so ignore it here.
927 if (!DType.isNull()) {
928 // The pointer is type- and value-dependent if it points into something
929 // dependent.
Douglas Gregor82dbbd72009-05-29 14:49:33 +0000930 bool Dependent = DC->isDependentContext();
Anders Carlsson946b86d2009-06-24 00:10:43 +0000931 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl3d3f75a2009-02-03 20:19:35 +0000932 }
933 }
934 }
935
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000936 // We may have found a field within an anonymous union or struct
937 // (C++ [class.union]).
Douglas Gregor6493d9c2009-10-22 07:08:30 +0000938 // FIXME: This needs to happen post-isImplicitMemberReference?
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000939 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
940 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
941 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlffbcf962009-01-18 18:53:16 +0000942
Douglas Gregor6493d9c2009-10-22 07:08:30 +0000943 // Cope with an implicit member access in a C++ non-static member function.
944 QualType ThisType, MemberType;
945 if (isImplicitMemberReference(SS, D, Loc, ThisType, MemberType)) {
946 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType);
947 MarkDeclarationReferenced(Loc, D);
948 if (PerformObjectMemberConversion(This, D))
949 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000950
Douglas Gregor6493d9c2009-10-22 07:08:30 +0000951 bool ShouldCheckUse = true;
952 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
953 // Don't diagnose the use of a virtual member function unless it's
954 // explicitly qualified.
955 if (MD->isVirtual() && (!SS || !SS->isSet()))
956 ShouldCheckUse = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000957 }
Douglas Gregor6493d9c2009-10-22 07:08:30 +0000958
959 if (ShouldCheckUse && DiagnoseUseOfDecl(D, Loc))
960 return ExprError();
961 return Owned(BuildMemberExpr(Context, This, true, SS, D,
962 Loc, MemberType));
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000963 }
964
Douglas Gregor91f84212008-12-11 16:49:14 +0000965 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000966 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
967 if (MD->isStatic())
968 // "invalid use of member 'x' in static member function"
Sebastian Redlffbcf962009-01-18 18:53:16 +0000969 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
970 << FD->getDeclName());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000971 }
972
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000973 // Any other ways we could have found the field in a well-formed
974 // program would have been turned into implicit member expressions
975 // above.
Sebastian Redlffbcf962009-01-18 18:53:16 +0000976 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
977 << FD->getDeclName());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000978 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +0000979
Steve Naroff46ba1eb2007-04-03 23:13:13 +0000980 if (isa<TypedefDecl>(D))
Sebastian Redlffbcf962009-01-18 18:53:16 +0000981 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000982 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlffbcf962009-01-18 18:53:16 +0000983 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +0000984 if (isa<NamespaceDecl>(D))
Sebastian Redlffbcf962009-01-18 18:53:16 +0000985 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Steve Narofff1e53692007-03-23 22:27:02 +0000986
Steve Naroff8de9c3a2008-09-05 22:11:13 +0000987 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000988 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson946b86d2009-06-24 00:10:43 +0000989 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
990 false, false, SS);
Douglas Gregord32e0282009-02-09 23:23:08 +0000991 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson946b86d2009-06-24 00:10:43 +0000992 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
993 false, false, SS);
Anders Carlsson938b1002009-08-29 01:06:32 +0000994 else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
Mike Stump11289f42009-09-09 15:08:12 +0000995 return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
996 /*TypeDependent=*/true,
Anders Carlsson938b1002009-08-29 01:06:32 +0000997 /*ValueDependent=*/true, SS);
998
Steve Naroff8de9c3a2008-09-05 22:11:13 +0000999 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001000
Douglas Gregor171c45a2009-02-18 21:56:37 +00001001 // Check whether this declaration can be used. Note that we suppress
1002 // this check when we're going to perform argument-dependent lookup
1003 // on this function name, because this might not be the function
1004 // that overload resolution actually selects.
Mike Stump11289f42009-09-09 15:08:12 +00001005 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
Douglas Gregor3256d042009-06-30 15:47:41 +00001006 HasTrailingLParen;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001007 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1008 return ExprError();
1009
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001010 // Only create DeclRefExpr's for valid Decl's.
1011 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001012 return ExprError();
1013
Chris Lattner2a9d9892008-10-20 05:16:36 +00001014 // If the identifier reference is inside a block, and it refers to a value
1015 // that is outside the block, create a BlockDeclRefExpr instead of a
1016 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1017 // the block is formed.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001018 //
Chris Lattner2a9d9892008-10-20 05:16:36 +00001019 // We do not do this for things like enum constants, global variables, etc,
1020 // as they do not get snapshotted.
1021 //
1022 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001023 MarkDeclarationReferenced(Loc, VD);
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001024 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001025 // The BlocksAttr indicates the variable is bound by-reference.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001026 if (VD->getAttr<BlocksAttr>())
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001027 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001028 // This is to record that a 'const' was actually synthesize and added.
1029 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001030 // Variable will be bound by-copy, make it const within the closure.
Mike Stump11289f42009-09-09 15:08:12 +00001031
Eli Friedman7fa3faa2009-03-22 23:00:19 +00001032 ExprTy.addConst();
Mike Stump11289f42009-09-09 15:08:12 +00001033 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00001034 constAdded));
Steve Naroff1d95e5a2008-10-10 01:28:17 +00001035 }
1036 // If this reference is not in a block or if the referenced variable is
1037 // within the block, create a normal DeclRefExpr.
Douglas Gregor4619e432008-12-05 23:32:09 +00001038
Douglas Gregor4619e432008-12-05 23:32:09 +00001039 bool TypeDependent = false;
Douglas Gregor872ffce2008-12-10 20:57:37 +00001040 bool ValueDependent = false;
1041 if (getLangOptions().CPlusPlus) {
1042 // C++ [temp.dep.expr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001043 // An id-expression is type-dependent if it contains:
Douglas Gregor872ffce2008-12-10 20:57:37 +00001044 // - an identifier that was declared with a dependent type,
1045 if (VD->getType()->isDependentType())
1046 TypeDependent = true;
1047 // - FIXME: a template-id that is dependent,
1048 // - a conversion-function-id that specifies a dependent type,
1049 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1050 Name.getCXXNameType()->isDependentType())
1051 TypeDependent = true;
1052 // - a nested-name-specifier that contains a class-name that
1053 // names a dependent type.
1054 else if (SS && !SS->isEmpty()) {
Douglas Gregor52537682009-03-19 00:18:19 +00001055 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor872ffce2008-12-10 20:57:37 +00001056 DC; DC = DC->getParent()) {
1057 // FIXME: could stop early at namespace scope.
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001058 if (DC->isRecord()) {
Douglas Gregor872ffce2008-12-10 20:57:37 +00001059 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1060 if (Context.getTypeDeclType(Record)->isDependentType()) {
1061 TypeDependent = true;
1062 break;
1063 }
Douglas Gregor4619e432008-12-05 23:32:09 +00001064 }
1065 }
1066 }
Douglas Gregor4619e432008-12-05 23:32:09 +00001067
Douglas Gregor872ffce2008-12-10 20:57:37 +00001068 // C++ [temp.dep.constexpr]p2:
1069 //
1070 // An identifier is value-dependent if it is:
1071 // - a name declared with a dependent type,
1072 if (TypeDependent)
1073 ValueDependent = true;
1074 // - the name of a non-type template parameter,
1075 else if (isa<NonTypeTemplateParmDecl>(VD))
1076 ValueDependent = true;
1077 // - a constant with integral or enumeration type and is
1078 // initialized with an expression that is value-dependent
Eli Friedmandd49ee32009-06-11 01:11:20 +00001079 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
John McCall8ccfcb52009-09-24 19:53:00 +00001080 if (Dcl->getType().getCVRQualifiers() == Qualifiers::Const &&
Eli Friedmandd49ee32009-06-11 01:11:20 +00001081 Dcl->getInit()) {
1082 ValueDependent = Dcl->getInit()->isValueDependent();
1083 }
1084 }
Douglas Gregor872ffce2008-12-10 20:57:37 +00001085 }
Douglas Gregor4619e432008-12-05 23:32:09 +00001086
Anders Carlsson946b86d2009-06-24 00:10:43 +00001087 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1088 TypeDependent, ValueDependent, SS);
Chris Lattner17ed4872006-11-20 04:58:19 +00001089}
Chris Lattnere168f762006-11-10 05:29:30 +00001090
Sebastian Redlffbcf962009-01-18 18:53:16 +00001091Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1092 tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00001093 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001094
Chris Lattnere168f762006-11-10 05:29:30 +00001095 switch (Kind) {
Chris Lattner317e6ba2008-01-12 18:39:25 +00001096 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00001097 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1098 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1099 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00001100 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00001101
Chris Lattnera81a0272008-01-12 08:14:25 +00001102 // Pre-defined identifiers are of type char[x], where x is the length of the
1103 // string.
Mike Stump11289f42009-09-09 15:08:12 +00001104
Anders Carlsson2fb08242009-09-08 18:24:21 +00001105 Decl *currentDecl = getCurFunctionOrMethodDecl();
1106 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001107 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00001108 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00001109 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001110
Anders Carlsson0b209a82009-09-11 01:22:35 +00001111 QualType ResTy;
1112 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1113 ResTy = Context.DependentTy;
1114 } else {
1115 unsigned Length =
1116 PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001117
Anders Carlsson0b209a82009-09-11 01:22:35 +00001118 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001119 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001120 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1121 }
Steve Narofff6009ed2009-01-21 00:14:39 +00001122 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00001123}
1124
Sebastian Redlffbcf962009-01-18 18:53:16 +00001125Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001126 llvm::SmallString<16> CharBuffer;
Steve Naroffae4143e2007-04-26 20:39:23 +00001127 CharBuffer.resize(Tok.getLength());
1128 const char *ThisTokBegin = &CharBuffer[0];
1129 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001130
Steve Naroffae4143e2007-04-26 20:39:23 +00001131 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1132 Tok.getLocation(), PP);
1133 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00001134 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00001135
1136 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1137
Sebastian Redl20614a72009-01-20 22:23:13 +00001138 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1139 Literal.isWide(),
1140 type, Tok.getLocation()));
Steve Naroffae4143e2007-04-26 20:39:23 +00001141}
1142
Sebastian Redlffbcf962009-01-18 18:53:16 +00001143Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1144 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00001145 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1146 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00001147 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerc4c18192009-01-16 07:10:29 +00001148 unsigned IntSize = Context.Target.getIntWidth();
Steve Narofff6009ed2009-01-21 00:14:39 +00001149 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroff5faaef72009-01-20 19:53:53 +00001150 Context.IntTy, Tok.getLocation()));
Steve Narofff2fb89e2007-03-13 20:29:44 +00001151 }
Ted Kremeneke9814182009-01-13 23:19:12 +00001152
Chris Lattner23b7eb62007-06-15 23:05:46 +00001153 llvm::SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00001154 // Add padding so that NumericLiteralParser can overread by one character.
1155 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00001156 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00001157
Chris Lattner67ca9252007-05-21 01:08:44 +00001158 // Get the spelling of the token, which eliminates trigraphs, etc.
Steve Naroff8160ea22007-03-06 01:09:46 +00001159 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001160
Mike Stump11289f42009-09-09 15:08:12 +00001161 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00001162 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00001163 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001164 return ExprError();
1165
Chris Lattner1c20a172007-08-26 03:42:43 +00001166 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00001167
Chris Lattner1c20a172007-08-26 03:42:43 +00001168 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001169 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001170 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001171 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001172 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00001173 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001174 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00001175 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00001176
1177 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1178
Ted Kremenek3a2c9502007-11-29 00:56:49 +00001179 // isExact will be set by GetFloatValue().
1180 bool isExact = false;
Chris Lattnere4edb8e2009-06-29 17:34:55 +00001181 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1182 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00001183
Chris Lattner1c20a172007-08-26 03:42:43 +00001184 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00001185 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00001186 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001187 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00001188
Neil Boothac582c52007-08-29 22:00:19 +00001189 // long long is a C99 feature.
1190 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth4a1ee052007-08-29 22:13:52 +00001191 Literal.isLongLong)
Neil Boothac582c52007-08-29 22:00:19 +00001192 Diag(Tok.getLocation(), diag::ext_longlong);
1193
Chris Lattner67ca9252007-05-21 01:08:44 +00001194 // Get the value in the widest-possible width.
Chris Lattner37e05872008-03-05 18:54:05 +00001195 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00001196
Chris Lattner67ca9252007-05-21 01:08:44 +00001197 if (Literal.GetIntegerValue(ResultVal)) {
1198 // If this value didn't fit into uintmax_t, warn and force to ull.
1199 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001200 Ty = Context.UnsignedLongLongTy;
1201 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00001202 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00001203 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00001204 // If this value fits into a ULL, try to figure out what else it fits into
1205 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001206
Chris Lattner67ca9252007-05-21 01:08:44 +00001207 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1208 // be an unsigned int.
1209 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1210
1211 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00001212 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00001213 if (!Literal.isLong && !Literal.isLongLong) {
1214 // Are int/unsigned possibilities?
Chris Lattner55258cf2008-05-09 05:59:00 +00001215 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001216
Chris Lattner67ca9252007-05-21 01:08:44 +00001217 // Does it fit in a unsigned int?
1218 if (ResultVal.isIntN(IntSize)) {
1219 // Does it fit in a signed int?
1220 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001221 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001222 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001223 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001224 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001225 }
Chris Lattner67ca9252007-05-21 01:08:44 +00001226 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001227
Chris Lattner67ca9252007-05-21 01:08:44 +00001228 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001229 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001230 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001231
Chris Lattner67ca9252007-05-21 01:08:44 +00001232 // Does it fit in a unsigned long?
1233 if (ResultVal.isIntN(LongSize)) {
1234 // Does it fit in a signed long?
1235 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001236 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001237 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001238 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001239 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001240 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001241 }
1242
Chris Lattner67ca9252007-05-21 01:08:44 +00001243 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001244 if (Ty.isNull()) {
Chris Lattner55258cf2008-05-09 05:59:00 +00001245 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001246
Chris Lattner67ca9252007-05-21 01:08:44 +00001247 // Does it fit in a unsigned long long?
1248 if (ResultVal.isIntN(LongLongSize)) {
1249 // Does it fit in a signed long long?
1250 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001251 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00001252 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001253 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001254 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00001255 }
1256 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001257
Chris Lattner67ca9252007-05-21 01:08:44 +00001258 // If we still couldn't decide a type, we probably have something that
1259 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001260 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00001261 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001262 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00001263 Width = Context.Target.getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00001264 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001265
Chris Lattner55258cf2008-05-09 05:59:00 +00001266 if (ResultVal.getBitWidth() != Width)
1267 ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00001268 }
Sebastian Redl20614a72009-01-20 22:23:13 +00001269 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00001270 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00001271
Chris Lattner1c20a172007-08-26 03:42:43 +00001272 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1273 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00001274 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00001275 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00001276
1277 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00001278}
1279
Sebastian Redlffbcf962009-01-18 18:53:16 +00001280Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1281 SourceLocation R, ExprArg Val) {
Anders Carlssonb781bcd2009-05-01 19:49:17 +00001282 Expr *E = Val.takeAs<Expr>();
Chris Lattner24d5bfe2008-04-02 04:24:33 +00001283 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00001284 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00001285}
1286
Steve Naroff71b59a92007-06-04 22:22:31 +00001287/// The UsualUnaryConversions() function is *not* called by this routine.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00001288/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001289bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl6f282892008-11-11 17:56:53 +00001290 SourceLocation OpLoc,
1291 const SourceRange &ExprRange,
1292 bool isSizeof) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001293 if (exprType->isDependentType())
1294 return false;
1295
Steve Naroff043d45d2007-05-15 02:32:35 +00001296 // C99 6.5.3.4p1:
Chris Lattnerb1355b12009-01-24 19:46:37 +00001297 if (isa<FunctionType>(exprType)) {
Chris Lattner62975a72009-04-24 00:30:45 +00001298 // alignof(function) is allowed as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001299 if (isSizeof)
1300 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1301 return false;
1302 }
Mike Stump11289f42009-09-09 15:08:12 +00001303
Chris Lattner62975a72009-04-24 00:30:45 +00001304 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattnerb1355b12009-01-24 19:46:37 +00001305 if (exprType->isVoidType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001306 Diag(OpLoc, diag::ext_sizeof_void_type)
1307 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattnerb1355b12009-01-24 19:46:37 +00001308 return false;
1309 }
Mike Stump11289f42009-09-09 15:08:12 +00001310
Chris Lattner62975a72009-04-24 00:30:45 +00001311 if (RequireCompleteType(OpLoc, exprType,
Mike Stump11289f42009-09-09 15:08:12 +00001312 isSizeof ? diag::err_sizeof_incomplete_type :
Anders Carlssond624e162009-08-26 23:45:07 +00001313 PDiag(diag::err_alignof_incomplete_type)
1314 << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00001315 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001316
Chris Lattner62975a72009-04-24 00:30:45 +00001317 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanian1dcb3222009-04-24 17:34:33 +00001318 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner62975a72009-04-24 00:30:45 +00001319 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnercd2a8c52009-04-24 22:30:50 +00001320 << exprType << isSizeof << ExprRange;
1321 return true;
Chris Lattner37920f52009-04-21 19:55:16 +00001322 }
Mike Stump11289f42009-09-09 15:08:12 +00001323
Chris Lattner62975a72009-04-24 00:30:45 +00001324 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00001325}
1326
Chris Lattner8dff0172009-01-24 20:17:12 +00001327bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1328 const SourceRange &ExprRange) {
1329 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001330
Mike Stump11289f42009-09-09 15:08:12 +00001331 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00001332 if (isa<DeclRefExpr>(E))
1333 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001334
1335 // Cannot know anything else if the expression is dependent.
1336 if (E->isTypeDependent())
1337 return false;
1338
Douglas Gregor71235ec2009-05-02 02:18:30 +00001339 if (E->getBitField()) {
1340 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1341 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00001342 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00001343
1344 // Alignment of a field access is always okay, so long as it isn't a
1345 // bit-field.
1346 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00001347 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00001348 return false;
1349
Chris Lattner8dff0172009-01-24 20:17:12 +00001350 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1351}
1352
Douglas Gregor0950e412009-03-13 21:01:28 +00001353/// \brief Build a sizeof or alignof expression given a type operand.
Mike Stump11289f42009-09-09 15:08:12 +00001354Action::OwningExprResult
1355Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001356 bool isSizeOf, SourceRange R) {
1357 if (T.isNull())
1358 return ExprError();
1359
1360 if (!T->isDependentType() &&
1361 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1362 return ExprError();
1363
1364 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1365 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1366 Context.getSizeType(), OpLoc,
1367 R.getEnd()));
1368}
1369
1370/// \brief Build a sizeof or alignof expression given an expression
1371/// operand.
Mike Stump11289f42009-09-09 15:08:12 +00001372Action::OwningExprResult
1373Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
Douglas Gregor0950e412009-03-13 21:01:28 +00001374 bool isSizeOf, SourceRange R) {
1375 // Verify that the operand is valid.
1376 bool isInvalid = false;
1377 if (E->isTypeDependent()) {
1378 // Delay type-checking for type-dependent expressions.
1379 } else if (!isSizeOf) {
1380 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor71235ec2009-05-02 02:18:30 +00001381 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor0950e412009-03-13 21:01:28 +00001382 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1383 isInvalid = true;
1384 } else {
1385 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1386 }
1387
1388 if (isInvalid)
1389 return ExprError();
1390
1391 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1392 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1393 Context.getSizeType(), OpLoc,
1394 R.getEnd()));
1395}
1396
Sebastian Redl6f282892008-11-11 17:56:53 +00001397/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1398/// the same for @c alignof and @c __alignof
1399/// Note that the ArgRange is invalid if isType is false.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001400Action::OwningExprResult
Sebastian Redl6f282892008-11-11 17:56:53 +00001401Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1402 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00001403 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001404 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00001405
Sebastian Redl6f282892008-11-11 17:56:53 +00001406 if (isType) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001407 // FIXME: Preserve type source info.
1408 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregor0950e412009-03-13 21:01:28 +00001409 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00001410 }
Sebastian Redl6f282892008-11-11 17:56:53 +00001411
Douglas Gregor0950e412009-03-13 21:01:28 +00001412 // Get the end location.
1413 Expr *ArgEx = (Expr *)TyOrEx;
1414 Action::OwningExprResult Result
1415 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1416
1417 if (Result.isInvalid())
1418 DeleteExpr(ArgEx);
1419
1420 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00001421}
1422
Chris Lattner709322b2009-02-17 08:12:06 +00001423QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001424 if (V->isTypeDependent())
1425 return Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00001426
Chris Lattnere267f5d2007-08-26 05:39:26 +00001427 // These operators return the element type of a complex type.
John McCall9dd450b2009-09-21 23:43:11 +00001428 if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00001429 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00001430
Chris Lattnere267f5d2007-08-26 05:39:26 +00001431 // Otherwise they pass through real integer and floating point types here.
1432 if (V->getType()->isArithmeticType())
1433 return V->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001434
Chris Lattnere267f5d2007-08-26 05:39:26 +00001435 // Reject anything else.
Chris Lattner709322b2009-02-17 08:12:06 +00001436 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1437 << (isReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00001438 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00001439}
1440
1441
Chris Lattnere168f762006-11-10 05:29:30 +00001442
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001443Action::OwningExprResult
1444Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1445 tok::TokenKind Kind, ExprArg Input) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00001446 // Since this might be a postfix expression, get rid of ParenListExprs.
1447 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001448 Expr *Arg = (Expr *)Input.get();
Douglas Gregord08452f2008-11-19 15:42:04 +00001449
Chris Lattnere168f762006-11-10 05:29:30 +00001450 UnaryOperator::Opcode Opc;
1451 switch (Kind) {
1452 default: assert(0 && "Unknown unary op!");
1453 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1454 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1455 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001456
Douglas Gregord08452f2008-11-19 15:42:04 +00001457 if (getLangOptions().CPlusPlus &&
1458 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1459 // Which overloaded operator?
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001460 OverloadedOperatorKind OverOp =
Douglas Gregord08452f2008-11-19 15:42:04 +00001461 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1462
1463 // C++ [over.inc]p1:
1464 //
1465 // [...] If the function is a member function with one
1466 // parameter (which shall be of type int) or a non-member
1467 // function with two parameters (the second of which shall be
1468 // of type int), it defines the postfix increment operator ++
1469 // for objects of that type. When the postfix increment is
1470 // called as a result of using the ++ operator, the int
1471 // argument will have value zero.
Mike Stump11289f42009-09-09 15:08:12 +00001472 Expr *Args[2] = {
1473 Arg,
1474 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
Steve Narofff6009ed2009-01-21 00:14:39 +00001475 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregord08452f2008-11-19 15:42:04 +00001476 };
1477
1478 // Build the candidate set for overloading
1479 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001480 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregord08452f2008-11-19 15:42:04 +00001481
1482 // Perform overload resolution.
1483 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001484 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregord08452f2008-11-19 15:42:04 +00001485 case OR_Success: {
1486 // We found a built-in operator or an overloaded operator.
1487 FunctionDecl *FnDecl = Best->Function;
1488
1489 if (FnDecl) {
1490 // We matched an overloaded operator. Build a call to that
1491 // operator.
1492
1493 // Convert the arguments.
1494 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1495 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001496 return ExprError();
Douglas Gregord08452f2008-11-19 15:42:04 +00001497 } else {
1498 // Convert the arguments.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001499 if (PerformCopyInitialization(Arg,
Douglas Gregord08452f2008-11-19 15:42:04 +00001500 FnDecl->getParamDecl(0)->getType(),
1501 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001502 return ExprError();
Douglas Gregord08452f2008-11-19 15:42:04 +00001503 }
1504
1505 // Determine the result type
Anders Carlsson3d5829c2009-10-13 21:49:31 +00001506 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001507
Douglas Gregord08452f2008-11-19 15:42:04 +00001508 // Build the actual expression node.
Steve Narofff6009ed2009-01-21 00:14:39 +00001509 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump82191d02009-02-19 02:54:59 +00001510 SourceLocation());
Douglas Gregord08452f2008-11-19 15:42:04 +00001511 UsualUnaryConversions(FnExpr);
1512
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001513 Input.release();
Douglas Gregor2517f332009-05-27 05:00:47 +00001514 Args[0] = Arg;
Anders Carlsson3d5829c2009-10-13 21:49:31 +00001515
1516 ExprOwningPtr<CXXOperatorCallExpr>
1517 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OverOp,
1518 FnExpr, Args, 2,
1519 ResultTy, OpLoc));
1520
1521 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
1522 FnDecl))
1523 return ExprError();
Anders Carlsson834facc2009-10-13 22:22:09 +00001524 return Owned(TheCall.release());
1525
Douglas Gregord08452f2008-11-19 15:42:04 +00001526 } else {
1527 // We matched a built-in operator. Convert the arguments, then
1528 // break out so that we will build the appropriate built-in
1529 // operator node.
1530 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1531 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001532 return ExprError();
Douglas Gregord08452f2008-11-19 15:42:04 +00001533
1534 break;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001535 }
Douglas Gregord08452f2008-11-19 15:42:04 +00001536 }
1537
Douglas Gregor66950a32009-09-30 21:46:01 +00001538 case OR_No_Viable_Function: {
1539 // No viable function; try checking this as a built-in operator, which
1540 // will fail and provide a diagnostic. Then, print the overload
1541 // candidates.
1542 OwningExprResult Result = CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
1543 assert(Result.isInvalid() &&
1544 "C++ postfix-unary operator overloading is missing candidates!");
1545 if (Result.isInvalid())
1546 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1547
1548 return move(Result);
1549 }
1550
Douglas Gregord08452f2008-11-19 15:42:04 +00001551 case OR_Ambiguous:
1552 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1553 << UnaryOperator::getOpcodeStr(Opc)
1554 << Arg->getSourceRange();
1555 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001556 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00001557
1558 case OR_Deleted:
1559 Diag(OpLoc, diag::err_ovl_deleted_oper)
1560 << Best->Function->isDeleted()
1561 << UnaryOperator::getOpcodeStr(Opc)
1562 << Arg->getSourceRange();
1563 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1564 return ExprError();
Douglas Gregord08452f2008-11-19 15:42:04 +00001565 }
1566
1567 // Either we found no viable overloaded operator or we matched a
1568 // built-in operator. In either case, fall through to trying to
1569 // build a built-in operation.
1570 }
1571
Eli Friedmanf32f0a72009-07-22 23:24:42 +00001572 Input.release();
1573 Input = Arg;
Eli Friedman6aea5752009-07-22 22:25:00 +00001574 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattnere168f762006-11-10 05:29:30 +00001575}
1576
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001577Action::OwningExprResult
1578Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1579 ExprArg Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00001580 // Since this might be a postfix expression, get rid of ParenListExprs.
1581 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1582
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001583 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1584 *RHSExp = static_cast<Expr*>(Idx.get());
Mike Stump11289f42009-09-09 15:08:12 +00001585
Douglas Gregor40412ac2008-11-19 17:17:41 +00001586 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00001587 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1588 Base.release();
1589 Idx.release();
1590 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1591 Context.DependentTy, RLoc));
1592 }
1593
Mike Stump11289f42009-09-09 15:08:12 +00001594 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001595 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00001596 LHSExp->getType()->isEnumeralType() ||
1597 RHSExp->getType()->isRecordType() ||
1598 RHSExp->getType()->isEnumeralType())) {
Mike Stump11289f42009-09-09 15:08:12 +00001599 // Add the appropriate overloaded operators (C++ [over.match.oper])
Douglas Gregor40412ac2008-11-19 17:17:41 +00001600 // to the candidate set.
1601 OverloadCandidateSet CandidateSet;
1602 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor1baf54e2009-03-13 18:40:31 +00001603 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1604 SourceRange(LLoc, RLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001605
Douglas Gregor40412ac2008-11-19 17:17:41 +00001606 // Perform overload resolution.
1607 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001608 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor40412ac2008-11-19 17:17:41 +00001609 case OR_Success: {
1610 // We found a built-in operator or an overloaded operator.
1611 FunctionDecl *FnDecl = Best->Function;
1612
1613 if (FnDecl) {
1614 // We matched an overloaded operator. Build a call to that
1615 // operator.
1616
1617 // Convert the arguments.
1618 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1619 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
Mike Stump11289f42009-09-09 15:08:12 +00001620 PerformCopyInitialization(RHSExp,
Douglas Gregor40412ac2008-11-19 17:17:41 +00001621 FnDecl->getParamDecl(0)->getType(),
1622 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001623 return ExprError();
Douglas Gregor40412ac2008-11-19 17:17:41 +00001624 } else {
1625 // Convert the arguments.
1626 if (PerformCopyInitialization(LHSExp,
1627 FnDecl->getParamDecl(0)->getType(),
1628 "passing") ||
1629 PerformCopyInitialization(RHSExp,
1630 FnDecl->getParamDecl(1)->getType(),
1631 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001632 return ExprError();
Douglas Gregor40412ac2008-11-19 17:17:41 +00001633 }
1634
1635 // Determine the result type
Anders Carlsson834facc2009-10-13 22:22:09 +00001636 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001637
Douglas Gregor40412ac2008-11-19 17:17:41 +00001638 // Build the actual expression node.
Mike Stump4e1f26a2009-02-19 03:04:26 +00001639 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1640 SourceLocation());
Douglas Gregor40412ac2008-11-19 17:17:41 +00001641 UsualUnaryConversions(FnExpr);
1642
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001643 Base.release();
1644 Idx.release();
Douglas Gregor2517f332009-05-27 05:00:47 +00001645 Args[0] = LHSExp;
1646 Args[1] = RHSExp;
Anders Carlsson834facc2009-10-13 22:22:09 +00001647
1648 ExprOwningPtr<CXXOperatorCallExpr>
1649 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1650 FnExpr, Args, 2,
1651 ResultTy, RLoc));
1652 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
1653 FnDecl))
1654 return ExprError();
1655
1656 return Owned(TheCall.release());
Douglas Gregor40412ac2008-11-19 17:17:41 +00001657 } else {
1658 // We matched a built-in operator. Convert the arguments, then
1659 // break out so that we will build the appropriate built-in
1660 // operator node.
1661 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1662 "passing") ||
1663 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1664 "passing"))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001665 return ExprError();
Douglas Gregor40412ac2008-11-19 17:17:41 +00001666
1667 break;
1668 }
1669 }
1670
1671 case OR_No_Viable_Function:
1672 // No viable function; fall through to handling this as a
1673 // built-in operator, which will produce an error message for us.
1674 break;
1675
1676 case OR_Ambiguous:
1677 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1678 << "[]"
1679 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1680 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001681 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00001682
1683 case OR_Deleted:
1684 Diag(LLoc, diag::err_ovl_deleted_oper)
1685 << Best->Function->isDeleted()
1686 << "[]"
1687 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1688 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1689 return ExprError();
Douglas Gregor40412ac2008-11-19 17:17:41 +00001690 }
1691
1692 // Either we found no viable overloaded operator or we matched a
1693 // built-in operator. In either case, fall through to trying to
1694 // build a built-in operation.
1695 }
1696
Chris Lattner36d572b2007-07-16 00:14:47 +00001697 // Perform default conversions.
1698 DefaultFunctionArrayConversion(LHSExp);
1699 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001700
Chris Lattner36d572b2007-07-16 00:14:47 +00001701 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
Steve Narofff1e53692007-03-23 22:27:02 +00001702
Steve Naroffc1aadb12007-03-28 21:49:40 +00001703 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00001704 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00001705 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00001706 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00001707 Expr *BaseExpr, *IndexExpr;
1708 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001709 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1710 BaseExpr = LHSExp;
1711 IndexExpr = RHSExp;
1712 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001713 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00001714 BaseExpr = LHSExp;
1715 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001716 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001717 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00001718 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00001719 BaseExpr = RHSExp;
1720 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00001721 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001722 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00001723 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001724 BaseExpr = LHSExp;
1725 IndexExpr = RHSExp;
1726 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00001727 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00001728 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001729 // Handle the uncommon case of "123[Ptr]".
1730 BaseExpr = RHSExp;
1731 IndexExpr = LHSExp;
1732 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00001733 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00001734 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00001735 IndexExpr = RHSExp;
Nate Begemanc1bf0612009-01-18 00:45:31 +00001736
Chris Lattner36d572b2007-07-16 00:14:47 +00001737 // FIXME: need to deal with const...
1738 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00001739 } else if (LHSTy->isArrayType()) {
1740 // If we see an array that wasn't promoted by
1741 // DefaultFunctionArrayConversion, it must be an array that
1742 // wasn't promoted because of the C90 rule that doesn't
1743 // allow promoting non-lvalue arrays. Warn, then
1744 // force the promotion here.
1745 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1746 LHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00001747 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
1748 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00001749 LHSTy = LHSExp->getType();
1750
1751 BaseExpr = LHSExp;
1752 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001753 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00001754 } else if (RHSTy->isArrayType()) {
1755 // Same as previous, except for 123[f().a] case
1756 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1757 RHSExp->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00001758 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
1759 CastExpr::CK_ArrayToPointerDecay);
Eli Friedmanab2784f2009-04-25 23:46:54 +00001760 RHSTy = RHSExp->getType();
1761
1762 BaseExpr = RHSExp;
1763 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001764 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00001765 } else {
Chris Lattner003af242009-04-25 22:50:55 +00001766 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1767 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001768 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00001769 // C99 6.5.2.1p1
Nate Begeman5ec4b312009-08-10 23:49:36 +00001770 if (!(IndexExpr->getType()->isIntegerType() &&
1771 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00001772 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1773 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00001774
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00001775 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00001776 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1777 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00001778 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1779
Douglas Gregorac1fb652009-03-24 19:52:54 +00001780 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00001781 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1782 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00001783 // incomplete types are not object types.
1784 if (ResultType->isFunctionType()) {
1785 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1786 << ResultType << BaseExpr->getSourceRange();
1787 return ExprError();
1788 }
Mike Stump11289f42009-09-09 15:08:12 +00001789
Douglas Gregorac1fb652009-03-24 19:52:54 +00001790 if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00001791 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00001792 PDiag(diag::err_subscript_incomplete_type)
1793 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00001794 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001795
Chris Lattner62975a72009-04-24 00:30:45 +00001796 // Diagnose bad cases where we step over interface counts.
1797 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1798 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1799 << ResultType << BaseExpr->getSourceRange();
1800 return ExprError();
1801 }
Mike Stump11289f42009-09-09 15:08:12 +00001802
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001803 Base.release();
1804 Idx.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00001805 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Narofff6009ed2009-01-21 00:14:39 +00001806 ResultType, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00001807}
1808
Steve Narofff8fd09e2007-07-27 22:15:19 +00001809QualType Sema::
Nate Begemance4d7fc2008-04-18 23:10:10 +00001810CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001811 const IdentifierInfo *CompName,
Anders Carlssonf571c112009-08-26 18:25:21 +00001812 SourceLocation CompLoc) {
Daniel Dunbarc0429402009-10-18 02:09:38 +00001813 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
1814 // see FIXME there.
1815 //
1816 // FIXME: This logic can be greatly simplified by splitting it along
1817 // halving/not halving and reworking the component checking.
John McCall9dd450b2009-09-21 23:43:11 +00001818 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
Nate Begemanf322eab2008-05-09 06:41:27 +00001819
Steve Narofff8fd09e2007-07-27 22:15:19 +00001820 // The vector accessor can't exceed the number of elements.
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001821 const char *compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00001822
Mike Stump4e1f26a2009-02-19 03:04:26 +00001823 // This flag determines whether or not the component is one of the four
Nate Begemanbb70bf62009-01-18 01:47:54 +00001824 // special names that indicate a subset of exactly half the elements are
1825 // to be selected.
1826 bool HalvingSwizzle = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00001827
Nate Begemanbb70bf62009-01-18 01:47:54 +00001828 // This flag determines whether or not CompName has an 's' char prefix,
1829 // indicating that it is a string of hex values to be used as vector indices.
Nate Begeman0359e122009-06-25 21:06:09 +00001830 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanf322eab2008-05-09 06:41:27 +00001831
1832 // Check that we've found one of the special components, or that the component
1833 // names must come from the same set.
Mike Stump4e1f26a2009-02-19 03:04:26 +00001834 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begemanbb70bf62009-01-18 01:47:54 +00001835 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1836 HalvingSwizzle = true;
Nate Begemanf322eab2008-05-09 06:41:27 +00001837 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00001838 do
1839 compStr++;
1840 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begemanbb70bf62009-01-18 01:47:54 +00001841 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner7e152db2007-08-02 22:33:49 +00001842 do
1843 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00001844 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner7e152db2007-08-02 22:33:49 +00001845 }
Nate Begemanbb70bf62009-01-18 01:47:54 +00001846
Mike Stump4e1f26a2009-02-19 03:04:26 +00001847 if (!HalvingSwizzle && *compStr) {
Steve Narofff8fd09e2007-07-27 22:15:19 +00001848 // We didn't get to the end of the string. This means the component names
1849 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner3b054132008-11-19 05:08:23 +00001850 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1851 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Narofff8fd09e2007-07-27 22:15:19 +00001852 return QualType();
1853 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00001854
Nate Begemanbb70bf62009-01-18 01:47:54 +00001855 // Ensure no component accessor exceeds the width of the vector type it
1856 // operates on.
1857 if (!HalvingSwizzle) {
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00001858 compStr = CompName->getNameStart();
Nate Begemanbb70bf62009-01-18 01:47:54 +00001859
1860 if (HexSwizzle)
Steve Narofff8fd09e2007-07-27 22:15:19 +00001861 compStr++;
Nate Begemanbb70bf62009-01-18 01:47:54 +00001862
1863 while (*compStr) {
1864 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1865 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1866 << baseType << SourceRange(CompLoc);
1867 return QualType();
1868 }
1869 }
Steve Narofff8fd09e2007-07-27 22:15:19 +00001870 }
Nate Begemanf322eab2008-05-09 06:41:27 +00001871
Nate Begemanbb70bf62009-01-18 01:47:54 +00001872 // If this is a halving swizzle, verify that the base type has an even
1873 // number of elements.
1874 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner3b054132008-11-19 05:08:23 +00001875 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner1e5665e2008-11-24 06:25:27 +00001876 << baseType << SourceRange(CompLoc);
Nate Begemanf322eab2008-05-09 06:41:27 +00001877 return QualType();
1878 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00001879
Steve Narofff8fd09e2007-07-27 22:15:19 +00001880 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump4e1f26a2009-02-19 03:04:26 +00001881 // The vector type is implied by the component accessor. For example,
Steve Narofff8fd09e2007-07-27 22:15:19 +00001882 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begemanbb70bf62009-01-18 01:47:54 +00001883 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanf322eab2008-05-09 06:41:27 +00001884 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begemanbb70bf62009-01-18 01:47:54 +00001885 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
Anders Carlssonf571c112009-08-26 18:25:21 +00001886 : CompName->getLength();
Nate Begemanbb70bf62009-01-18 01:47:54 +00001887 if (HexSwizzle)
1888 CompSize--;
1889
Steve Narofff8fd09e2007-07-27 22:15:19 +00001890 if (CompSize == 1)
1891 return vecType->getElementType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00001892
Nate Begemance4d7fc2008-04-18 23:10:10 +00001893 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump4e1f26a2009-02-19 03:04:26 +00001894 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemance4d7fc2008-04-18 23:10:10 +00001895 // diagostics look bad. We want extended vector types to appear built-in.
1896 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1897 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1898 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroffddf5a1d2007-07-29 16:33:31 +00001899 }
1900 return VT; // should never get here (a typedef type should always be found).
Steve Narofff8fd09e2007-07-27 22:15:19 +00001901}
1902
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001903static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
Anders Carlssonf571c112009-08-26 18:25:21 +00001904 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001905 const Selector &Sel,
1906 ASTContext &Context) {
Mike Stump11289f42009-09-09 15:08:12 +00001907
Anders Carlssonf571c112009-08-26 18:25:21 +00001908 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001909 return PD;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001910 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001911 return OMD;
Mike Stump11289f42009-09-09 15:08:12 +00001912
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001913 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1914 E = PDecl->protocol_end(); I != E; ++I) {
Mike Stump11289f42009-09-09 15:08:12 +00001915 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001916 Context))
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001917 return D;
1918 }
1919 return 0;
1920}
1921
Steve Narofffb4330f2009-06-17 22:40:22 +00001922static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Anders Carlssonf571c112009-08-26 18:25:21 +00001923 IdentifierInfo *Member,
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001924 const Selector &Sel,
1925 ASTContext &Context) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001926 // Check protocols on qualified interfaces.
1927 Decl *GDecl = 0;
Steve Narofffb4330f2009-06-17 22:40:22 +00001928 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001929 E = QIdTy->qual_end(); I != E; ++I) {
Anders Carlssonf571c112009-08-26 18:25:21 +00001930 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001931 GDecl = PD;
1932 break;
1933 }
1934 // Also must look for a getter name which uses property syntax.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001935 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001936 GDecl = OMD;
1937 break;
1938 }
1939 }
1940 if (!GDecl) {
Steve Narofffb4330f2009-06-17 22:40:22 +00001941 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001942 E = QIdTy->qual_end(); I != E; ++I) {
1943 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001944 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahaniand302bbd02009-03-19 18:15:34 +00001945 if (GDecl)
1946 return GDecl;
1947 }
1948 }
1949 return GDecl;
1950}
Chris Lattner4bf74fd2009-02-15 22:43:40 +00001951
Mike Stump11289f42009-09-09 15:08:12 +00001952Action::OwningExprResult
Anders Carlssonf571c112009-08-26 18:25:21 +00001953Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001954 tok::TokenKind OpKind, SourceLocation MemberLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001955 DeclarationName MemberName,
Douglas Gregor84f14dd2009-09-01 00:37:14 +00001956 bool HasExplicitTemplateArgs,
1957 SourceLocation LAngleLoc,
1958 const TemplateArgument *ExplicitTemplateArgs,
1959 unsigned NumExplicitTemplateArgs,
1960 SourceLocation RAngleLoc,
Douglas Gregor2b6ca462009-09-03 21:38:09 +00001961 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
1962 NamedDecl *FirstQualifierInScope) {
Douglas Gregord8061562009-08-06 03:17:00 +00001963 if (SS && SS->isInvalid())
1964 return ExprError();
1965
Nate Begeman5ec4b312009-08-10 23:49:36 +00001966 // Since this might be a postfix expression, get rid of ParenListExprs.
1967 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1968
Anders Carlsson3cbc8592009-05-01 19:30:39 +00001969 Expr *BaseExpr = Base.takeAs<Expr>();
Douglas Gregorad8a3362009-09-04 17:36:40 +00001970 assert(BaseExpr && "no base expression");
Mike Stump11289f42009-09-09 15:08:12 +00001971
Steve Naroffeaaae462007-12-16 21:42:28 +00001972 // Perform default conversions.
1973 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001974
Steve Naroff185616f2007-07-26 03:11:44 +00001975 QualType BaseType = BaseExpr->getType();
David Chisnall9f57c292009-08-17 16:35:33 +00001976 // If this is an Objective-C pseudo-builtin and a definition is provided then
1977 // use that.
1978 if (BaseType->isObjCIdType()) {
1979 // We have an 'id' type. Rather than fall through, we check if this
1980 // is a reference to 'isa'.
1981 if (BaseType != Context.ObjCIdRedefinitionType) {
1982 BaseType = Context.ObjCIdRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00001983 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00001984 }
David Chisnall9f57c292009-08-17 16:35:33 +00001985 }
Steve Naroff185616f2007-07-26 03:11:44 +00001986 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001987
Fariborz Jahaniane983d172009-09-22 16:48:37 +00001988 // Handle properties on ObjC 'Class' types.
1989 if (OpKind == tok::period && BaseType->isObjCClassType()) {
1990 // Also must look for a getter name which uses property syntax.
1991 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1992 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1993 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1994 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1995 ObjCMethodDecl *Getter;
1996 // FIXME: need to also look locally in the implementation.
1997 if ((Getter = IFace->lookupClassMethod(Sel))) {
1998 // Check the use of this method.
1999 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2000 return ExprError();
2001 }
2002 // If we found a getter then this may be a valid dot-reference, we
2003 // will look for the matching setter, in case it is needed.
2004 Selector SetterSel =
2005 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2006 PP.getSelectorTable(), Member);
2007 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2008 if (!Setter) {
2009 // If this reference is in an @implementation, also check for 'private'
2010 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002011 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002012 }
2013 // Look through local category implementations associated with the class.
2014 if (!Setter)
2015 Setter = IFace->getCategoryClassMethod(SetterSel);
2016
2017 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2018 return ExprError();
2019
2020 if (Getter || Setter) {
2021 QualType PType;
2022
2023 if (Getter)
2024 PType = Getter->getResultType();
2025 else
2026 // Get the expression type from Setter's incoming parameter.
2027 PType = (*(Setter->param_end() -1))->getType();
2028 // FIXME: we must check that the setter has property type.
2029 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2030 PType,
2031 Setter, MemberLoc, BaseExpr));
2032 }
2033 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2034 << MemberName << BaseType);
2035 }
2036 }
2037
2038 if (BaseType->isObjCClassType() &&
2039 BaseType != Context.ObjCClassRedefinitionType) {
2040 BaseType = Context.ObjCClassRedefinitionType;
Eli Friedman06ed2a52009-10-20 08:27:19 +00002041 ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002042 }
2043
Chris Lattner4befd732008-07-21 04:36:39 +00002044 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2045 // must have pointer type, and the accessed type is the pointee.
Steve Narofff1e53692007-03-23 22:27:02 +00002046 if (OpKind == tok::arrow) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002047 if (BaseType->isDependentType()) {
2048 NestedNameSpecifier *Qualifier = 0;
2049 if (SS) {
2050 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2051 if (!FirstQualifierInScope)
2052 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2053 }
Mike Stump11289f42009-09-09 15:08:12 +00002054
2055 return Owned(CXXUnresolvedMemberExpr::Create(Context, BaseExpr, true,
Douglas Gregor308047d2009-09-09 00:23:06 +00002056 OpLoc, Qualifier,
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002057 SS? SS->getRange() : SourceRange(),
Douglas Gregor308047d2009-09-09 00:23:06 +00002058 FirstQualifierInScope,
2059 MemberName,
2060 MemberLoc,
2061 HasExplicitTemplateArgs,
2062 LAngleLoc,
2063 ExplicitTemplateArgs,
2064 NumExplicitTemplateArgs,
2065 RAngleLoc));
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002066 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002067 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff185616f2007-07-26 03:11:44 +00002068 BaseType = PT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002069 else if (BaseType->isObjCObjectPointerType())
2070 ;
Steve Naroff185616f2007-07-26 03:11:44 +00002071 else
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002072 return ExprError(Diag(MemberLoc,
2073 diag::err_typecheck_member_reference_arrow)
2074 << BaseType << BaseExpr->getSourceRange());
Fariborz Jahaniane983d172009-09-22 16:48:37 +00002075 } else if (BaseType->isDependentType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002076 // Require that the base type isn't a pointer type
Anders Carlsson524d5a42009-05-16 20:31:20 +00002077 // (so we'll report an error for)
2078 // T* t;
2079 // t.f;
Mike Stump11289f42009-09-09 15:08:12 +00002080 //
Anders Carlsson524d5a42009-05-16 20:31:20 +00002081 // In Obj-C++, however, the above expression is valid, since it could be
2082 // accessing the 'f' property if T is an Obj-C interface. The extra check
2083 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002084 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson524d5a42009-05-16 20:31:20 +00002085
Mike Stump11289f42009-09-09 15:08:12 +00002086 if (!PT || (getLangOptions().ObjC1 &&
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002087 !PT->getPointeeType()->isRecordType())) {
2088 NestedNameSpecifier *Qualifier = 0;
2089 if (SS) {
2090 Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2091 if (!FirstQualifierInScope)
2092 FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2093 }
Mike Stump11289f42009-09-09 15:08:12 +00002094
Douglas Gregor308047d2009-09-09 00:23:06 +00002095 return Owned(CXXUnresolvedMemberExpr::Create(Context,
Mike Stump11289f42009-09-09 15:08:12 +00002096 BaseExpr, false,
2097 OpLoc,
Douglas Gregor308047d2009-09-09 00:23:06 +00002098 Qualifier,
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002099 SS? SS->getRange() : SourceRange(),
Douglas Gregor308047d2009-09-09 00:23:06 +00002100 FirstQualifierInScope,
2101 MemberName,
2102 MemberLoc,
2103 HasExplicitTemplateArgs,
2104 LAngleLoc,
2105 ExplicitTemplateArgs,
2106 NumExplicitTemplateArgs,
2107 RAngleLoc));
Douglas Gregor2b6ca462009-09-03 21:38:09 +00002108 }
Anders Carlsson524d5a42009-05-16 20:31:20 +00002109 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002110
Chris Lattner4befd732008-07-21 04:36:39 +00002111 // Handle field access to simple records. This also handles access to fields
2112 // of the ObjC 'id' struct.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002113 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff185616f2007-07-26 03:11:44 +00002114 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregored0cfbd2009-03-09 16:13:40 +00002115 if (RequireCompleteType(OpLoc, BaseType,
Anders Carlssond624e162009-08-26 23:45:07 +00002116 PDiag(diag::err_typecheck_incomplete_tag)
2117 << BaseExpr->getSourceRange()))
Douglas Gregordd430f72009-01-19 19:26:10 +00002118 return ExprError();
2119
Douglas Gregord8061562009-08-06 03:17:00 +00002120 DeclContext *DC = RDecl;
2121 if (SS && SS->isSet()) {
2122 // If the member name was a qualified-id, look into the
2123 // nested-name-specifier.
2124 DC = computeDeclContext(*SS, false);
Douglas Gregor0b3d95a2009-10-17 22:37:54 +00002125
2126 if (!isa<TypeDecl>(DC)) {
2127 Diag(MemberLoc, diag::err_qualified_member_nonclass)
2128 << DC << SS->getRange();
2129 return ExprError();
2130 }
Mike Stump11289f42009-09-09 15:08:12 +00002131
2132 // FIXME: If DC is not computable, we should build a
Douglas Gregord8061562009-08-06 03:17:00 +00002133 // CXXUnresolvedMemberExpr.
2134 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2135 }
2136
Steve Naroff185616f2007-07-26 03:11:44 +00002137 // The record definition is complete, now make sure the member is valid.
John McCall9f3059a2009-10-09 21:13:30 +00002138 LookupResult Result;
2139 LookupQualifiedName(Result, DC, MemberName, LookupMemberName, false);
Douglas Gregor960b5bc2009-01-15 00:26:24 +00002140
John McCall9f3059a2009-10-09 21:13:30 +00002141 if (Result.empty())
Douglas Gregore40876a2009-10-13 21:16:44 +00002142 return ExprError(Diag(MemberLoc, diag::err_no_member)
2143 << MemberName << DC << BaseExpr->getSourceRange());
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002144 if (Result.isAmbiguous()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002145 DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2146 BaseExpr->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002147 return ExprError();
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002148 }
Mike Stump11289f42009-09-09 15:08:12 +00002149
John McCall9f3059a2009-10-09 21:13:30 +00002150 NamedDecl *MemberDecl = Result.getAsSingleDecl(Context);
2151
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002152 if (SS && SS->isSet()) {
John McCall9f3059a2009-10-09 21:13:30 +00002153 TypeDecl* TyD = cast<TypeDecl>(MemberDecl->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00002154 QualType BaseTypeCanon
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002155 = Context.getCanonicalType(BaseType).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002156 QualType MemberTypeCanon
John McCall9f3059a2009-10-09 21:13:30 +00002157 = Context.getCanonicalType(Context.getTypeDeclType(TyD));
Mike Stump11289f42009-09-09 15:08:12 +00002158
Douglas Gregorc26e0f62009-09-03 16:14:30 +00002159 if (BaseTypeCanon != MemberTypeCanon &&
2160 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2161 return ExprError(Diag(SS->getBeginLoc(),
2162 diag::err_not_direct_base_or_virtual)
2163 << MemberTypeCanon << BaseTypeCanon);
2164 }
Mike Stump11289f42009-09-09 15:08:12 +00002165
Chris Lattner303284a2009-02-13 22:08:30 +00002166 // If the decl being referenced had an error, return an error for this
2167 // sub-expr without emitting another error, in order to avoid cascading
2168 // error cases.
2169 if (MemberDecl->isInvalidDecl())
2170 return ExprError();
Mike Stump4e1f26a2009-02-19 03:04:26 +00002171
Anders Carlsson04e1e222009-09-10 20:48:14 +00002172 bool ShouldCheckUse = true;
2173 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2174 // Don't diagnose the use of a virtual member function unless it's
2175 // explicitly qualified.
2176 if (MD->isVirtual() && (!SS || !SS->isSet()))
2177 ShouldCheckUse = false;
2178 }
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00002179
Douglas Gregor171c45a2009-02-18 21:56:37 +00002180 // Check the use of this field
Anders Carlsson04e1e222009-09-10 20:48:14 +00002181 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002182 return ExprError();
Chris Lattner303284a2009-02-13 22:08:30 +00002183
Douglas Gregor55297ac2008-12-23 00:26:44 +00002184 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002185 // We may have found a field within an anonymous union or struct
2186 // (C++ [class.union]).
2187 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002188 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002189 BaseExpr, OpLoc);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00002190
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002191 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregor55297ac2008-12-23 00:26:44 +00002192 QualType MemberType = FD->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002193 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002194 MemberType = Ref->getPointeeType();
2195 else {
John McCall8ccfcb52009-09-24 19:53:00 +00002196 Qualifiers BaseQuals = BaseType.getQualifiers();
2197 BaseQuals.removeObjCGCAttr();
2198 if (FD->isMutable()) BaseQuals.removeConst();
2199
2200 Qualifiers MemberQuals
2201 = Context.getCanonicalType(MemberType).getQualifiers();
2202
2203 Qualifiers Combined = BaseQuals + MemberQuals;
2204 if (Combined != MemberQuals)
2205 MemberType = Context.getQualifiedType(MemberType, Combined);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002206 }
Eli Friedman1242fff2008-02-06 22:48:16 +00002207
Douglas Gregor77b50e12009-06-22 23:06:13 +00002208 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian3f150832009-07-29 19:40:11 +00002209 if (PerformObjectMemberConversion(BaseExpr, FD))
2210 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002211 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
Douglas Gregorc1905232009-08-26 22:36:53 +00002212 FD, MemberLoc, MemberType));
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002213 }
Mike Stump11289f42009-09-09 15:08:12 +00002214
Douglas Gregor77b50e12009-06-22 23:06:13 +00002215 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2216 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorc1905232009-08-26 22:36:53 +00002217 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2218 Var, MemberLoc,
2219 Var->getType().getNonReferenceType()));
Douglas Gregor77b50e12009-06-22 23:06:13 +00002220 }
2221 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2222 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorc1905232009-08-26 22:36:53 +00002223 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2224 MemberFn, MemberLoc,
2225 MemberFn->getType()));
Douglas Gregor77b50e12009-06-22 23:06:13 +00002226 }
Mike Stump11289f42009-09-09 15:08:12 +00002227 if (FunctionTemplateDecl *FunTmpl
Douglas Gregor97628d62009-08-21 00:16:32 +00002228 = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2229 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002230
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002231 if (HasExplicitTemplateArgs)
Mike Stump11289f42009-09-09 15:08:12 +00002232 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2233 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002234 SS? SS->getRange() : SourceRange(),
Mike Stump11289f42009-09-09 15:08:12 +00002235 FunTmpl, MemberLoc, true,
2236 LAngleLoc, ExplicitTemplateArgs,
2237 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002238 Context.OverloadTy));
Mike Stump11289f42009-09-09 15:08:12 +00002239
Douglas Gregorc1905232009-08-26 22:36:53 +00002240 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2241 FunTmpl, MemberLoc,
2242 Context.OverloadTy));
Douglas Gregor97628d62009-08-21 00:16:32 +00002243 }
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002244 if (OverloadedFunctionDecl *Ovl
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002245 = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2246 if (HasExplicitTemplateArgs)
Mike Stump11289f42009-09-09 15:08:12 +00002247 return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2248 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002249 SS? SS->getRange() : SourceRange(),
Mike Stump11289f42009-09-09 15:08:12 +00002250 Ovl, MemberLoc, true,
2251 LAngleLoc, ExplicitTemplateArgs,
2252 NumExplicitTemplateArgs, RAngleLoc,
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002253 Context.OverloadTy));
2254
Douglas Gregorc1905232009-08-26 22:36:53 +00002255 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2256 Ovl, MemberLoc, Context.OverloadTy));
Douglas Gregor84f14dd2009-09-01 00:37:14 +00002257 }
Douglas Gregor77b50e12009-06-22 23:06:13 +00002258 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2259 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Douglas Gregorc1905232009-08-26 22:36:53 +00002260 return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2261 Enum, MemberLoc, Enum->getType()));
Douglas Gregor77b50e12009-06-22 23:06:13 +00002262 }
Chris Lattnerfe4847e2009-03-31 08:18:48 +00002263 if (isa<TypeDecl>(MemberDecl))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002264 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
Anders Carlssonf571c112009-08-26 18:25:21 +00002265 << MemberName << int(OpKind == tok::arrow));
Eli Friedman1242fff2008-02-06 22:48:16 +00002266
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00002267 // We found a declaration kind that we didn't expect. This is a
2268 // generic error message that tells the user that she can't refer
2269 // to this member with '.' or '->'.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002270 return ExprError(Diag(MemberLoc,
2271 diag::err_typecheck_member_reference_unknown)
Anders Carlssonf571c112009-08-26 18:25:21 +00002272 << MemberName << int(OpKind == tok::arrow));
Chris Lattnerb63a7452008-07-21 04:28:12 +00002273 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002274
Douglas Gregorad8a3362009-09-04 17:36:40 +00002275 // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2276 // into a record type was handled above, any destructor we see here is a
2277 // pseudo-destructor.
2278 if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2279 // C++ [expr.pseudo]p2:
Mike Stump11289f42009-09-09 15:08:12 +00002280 // The left hand side of the dot operator shall be of scalar type. The
2281 // left hand side of the arrow operator shall be of pointer to scalar
Douglas Gregorad8a3362009-09-04 17:36:40 +00002282 // type.
2283 if (!BaseType->isScalarType())
2284 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2285 << BaseType << BaseExpr->getSourceRange());
Mike Stump11289f42009-09-09 15:08:12 +00002286
Douglas Gregorad8a3362009-09-04 17:36:40 +00002287 // [...] The type designated by the pseudo-destructor-name shall be the
2288 // same as the object type.
2289 if (!MemberName.getCXXNameType()->isDependentType() &&
2290 !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2291 return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2292 << BaseType << MemberName.getCXXNameType()
2293 << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
Mike Stump11289f42009-09-09 15:08:12 +00002294
2295 // [...] Furthermore, the two type-names in a pseudo-destructor-name of
Douglas Gregorad8a3362009-09-04 17:36:40 +00002296 // the form
2297 //
Mike Stump11289f42009-09-09 15:08:12 +00002298 // ::[opt] nested-name-specifier[opt] type-name :: ̃ type-name
2299 //
Douglas Gregorad8a3362009-09-04 17:36:40 +00002300 // shall designate the same scalar type.
2301 //
2302 // FIXME: DPG can't see any way to trigger this particular clause, so it
2303 // isn't checked here.
Mike Stump11289f42009-09-09 15:08:12 +00002304
Douglas Gregorad8a3362009-09-04 17:36:40 +00002305 // FIXME: We've lost the precise spelling of the type by going through
2306 // DeclarationName. Can we do better?
2307 return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002308 OpKind == tok::arrow,
Douglas Gregorad8a3362009-09-04 17:36:40 +00002309 OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00002310 (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
Douglas Gregorad8a3362009-09-04 17:36:40 +00002311 SS? SS->getRange() : SourceRange(),
2312 MemberName.getCXXNameType(),
2313 MemberLoc));
2314 }
Mike Stump11289f42009-09-09 15:08:12 +00002315
Chris Lattnerdc420f42008-07-21 04:59:05 +00002316 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2317 // (*Obj).ivar.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002318 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2319 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002320 const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002321 const ObjCInterfaceType *IFaceT =
John McCall9dd450b2009-09-21 23:43:11 +00002322 OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
Steve Naroffa057ba92009-07-16 00:25:06 +00002323 if (IFaceT) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002324 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2325
Steve Naroffa057ba92009-07-16 00:25:06 +00002326 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2327 ObjCInterfaceDecl *ClassDeclared;
Anders Carlssonf571c112009-08-26 18:25:21 +00002328 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
Mike Stump11289f42009-09-09 15:08:12 +00002329
Steve Naroffa057ba92009-07-16 00:25:06 +00002330 if (IV) {
2331 // If the decl being referenced had an error, return an error for this
2332 // sub-expr without emitting another error, in order to avoid cascading
2333 // error cases.
2334 if (IV->isInvalidDecl())
2335 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002336
Steve Naroffa057ba92009-07-16 00:25:06 +00002337 // Check whether we can reference this field.
2338 if (DiagnoseUseOfDecl(IV, MemberLoc))
2339 return ExprError();
2340 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2341 IV->getAccessControl() != ObjCIvarDecl::Package) {
2342 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2343 if (ObjCMethodDecl *MD = getCurMethodDecl())
2344 ClassOfMethodDecl = MD->getClassInterface();
2345 else if (ObjCImpDecl && getCurFunctionDecl()) {
2346 // Case of a c-function declared inside an objc implementation.
2347 // FIXME: For a c-style function nested inside an objc implementation
2348 // class, there is no implementation context available, so we pass
2349 // down the context as argument to this routine. Ideally, this context
2350 // need be passed down in the AST node and somehow calculated from the
2351 // AST for a function decl.
2352 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Mike Stump11289f42009-09-09 15:08:12 +00002353 if (ObjCImplementationDecl *IMPD =
Steve Naroffa057ba92009-07-16 00:25:06 +00002354 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2355 ClassOfMethodDecl = IMPD->getClassInterface();
2356 else if (ObjCCategoryImplDecl* CatImplClass =
2357 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2358 ClassOfMethodDecl = CatImplClass->getClassInterface();
2359 }
Mike Stump11289f42009-09-09 15:08:12 +00002360
2361 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2362 if (ClassDeclared != IDecl ||
Steve Naroffa057ba92009-07-16 00:25:06 +00002363 ClassOfMethodDecl != ClassDeclared)
Mike Stump11289f42009-09-09 15:08:12 +00002364 Diag(MemberLoc, diag::error_private_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002365 << IV->getDeclName();
Mike Stump12b8ce12009-08-04 21:02:39 +00002366 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2367 // @protected
Mike Stump11289f42009-09-09 15:08:12 +00002368 Diag(MemberLoc, diag::error_protected_ivar_access)
Steve Naroffa057ba92009-07-16 00:25:06 +00002369 << IV->getDeclName();
Steve Naroffd1b64be2009-03-04 18:34:24 +00002370 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002371
2372 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2373 MemberLoc, BaseExpr,
2374 OpKind == tok::arrow));
Fariborz Jahaniana458c4f2009-03-03 01:21:12 +00002375 }
Steve Naroffa057ba92009-07-16 00:25:06 +00002376 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
Anders Carlssonf571c112009-08-26 18:25:21 +00002377 << IDecl->getDeclName() << MemberName
Steve Naroffa057ba92009-07-16 00:25:06 +00002378 << BaseExpr->getSourceRange());
Fariborz Jahanianb1378f92008-12-13 22:20:28 +00002379 }
Chris Lattnerb63a7452008-07-21 04:28:12 +00002380 }
Steve Naroff1329fa02009-07-15 18:40:39 +00002381 // Handle properties on 'id' and qualified "id".
Mike Stump11289f42009-09-09 15:08:12 +00002382 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
Steve Naroff1329fa02009-07-15 18:40:39 +00002383 BaseType->isObjCQualifiedIdType())) {
John McCall9dd450b2009-09-21 23:43:11 +00002384 const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
Anders Carlssonf571c112009-08-26 18:25:21 +00002385 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002386
Steve Naroff7cae42b2009-07-10 23:34:53 +00002387 // Check protocols on qualified interfaces.
Anders Carlssonf571c112009-08-26 18:25:21 +00002388 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002389 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2390 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2391 // Check the use of this declaration
2392 if (DiagnoseUseOfDecl(PD, MemberLoc))
2393 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002394
Steve Naroff7cae42b2009-07-10 23:34:53 +00002395 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2396 MemberLoc, BaseExpr));
2397 }
2398 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2399 // Check the use of this method.
2400 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2401 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002402
Steve Naroff7cae42b2009-07-10 23:34:53 +00002403 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Mike Stump11289f42009-09-09 15:08:12 +00002404 OMD->getResultType(),
2405 OMD, OpLoc, MemberLoc,
Steve Naroff7cae42b2009-07-10 23:34:53 +00002406 NULL, 0));
2407 }
2408 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002409
Steve Naroff7cae42b2009-07-10 23:34:53 +00002410 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002411 << MemberName << BaseType);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002412 }
Chris Lattnerdc420f42008-07-21 04:59:05 +00002413 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2414 // pointer to a (potentially qualified) interface type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00002415 const ObjCObjectPointerType *OPT;
Mike Stump11289f42009-09-09 15:08:12 +00002416 if (OpKind == tok::period &&
Steve Naroff7cae42b2009-07-10 23:34:53 +00002417 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2418 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2419 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Anders Carlssonf571c112009-08-26 18:25:21 +00002420 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Mike Stump11289f42009-09-09 15:08:12 +00002421
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002422 // Search for a declared property first.
Anders Carlssonf571c112009-08-26 18:25:21 +00002423 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002424 // Check whether we can reference this property.
2425 if (DiagnoseUseOfDecl(PD, MemberLoc))
2426 return ExprError();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002427 QualType ResTy = PD->getType();
Anders Carlssonf571c112009-08-26 18:25:21 +00002428 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002429 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianfe9e3942009-05-08 20:20:55 +00002430 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2431 ResTy = Getter->getResultType();
Fariborz Jahanianb2ab73d2009-05-08 19:36:34 +00002432 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner43df5562009-02-16 18:35:08 +00002433 MemberLoc, BaseExpr));
2434 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002435 // Check protocols on qualified interfaces.
Steve Naroffaccc4882009-07-20 17:56:53 +00002436 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2437 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00002438 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002439 // Check whether we can reference this property.
2440 if (DiagnoseUseOfDecl(PD, MemberLoc))
2441 return ExprError();
Chris Lattner43df5562009-02-16 18:35:08 +00002442
Steve Narofff6009ed2009-01-21 00:14:39 +00002443 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner43df5562009-02-16 18:35:08 +00002444 MemberLoc, BaseExpr));
2445 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002446 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2447 E = OPT->qual_end(); I != E; ++I)
Anders Carlssonf571c112009-08-26 18:25:21 +00002448 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002449 // Check whether we can reference this property.
2450 if (DiagnoseUseOfDecl(PD, MemberLoc))
2451 return ExprError();
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002452
Steve Naroff7cae42b2009-07-10 23:34:53 +00002453 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2454 MemberLoc, BaseExpr));
2455 }
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002456 // If that failed, look for an "implicit" property by seeing if the nullary
2457 // selector is implemented.
2458
2459 // FIXME: The logic for looking up nullary and unary selectors should be
2460 // shared with the code in ActOnInstanceMessage.
2461
Anders Carlssonf571c112009-08-26 18:25:21 +00002462 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002463 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002464
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002465 // If this reference is in an @implementation, check for 'private' methods.
2466 if (!Getter)
Steve Naroffbb69c942009-10-01 23:46:04 +00002467 Getter = IFace->lookupPrivateInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002468
Steve Naroff1df62692008-10-22 19:16:27 +00002469 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002470 if (!Getter)
2471 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbaref89086c2008-09-03 01:05:41 +00002472 if (Getter) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00002473 // Check if we can reference this property.
2474 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2475 return ExprError();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002476 }
2477 // If we found a getter then this may be a valid dot-reference, we
2478 // will look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00002479 Selector SetterSel =
2480 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Anders Carlssonf571c112009-08-26 18:25:21 +00002481 PP.getSelectorTable(), Member);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002482 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002483 if (!Setter) {
2484 // If this reference is in an @implementation, also check for 'private'
2485 // methods.
Steve Naroffbb69c942009-10-01 23:46:04 +00002486 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
Steve Naroff1d984fe2009-03-11 13:48:17 +00002487 }
2488 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00002489 if (!Setter)
2490 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002491
Steve Naroff1d984fe2009-03-11 13:48:17 +00002492 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2493 return ExprError();
2494
2495 if (Getter || Setter) {
2496 QualType PType;
2497
2498 if (Getter)
2499 PType = Getter->getResultType();
Fariborz Jahanian88cc2342009-08-18 20:50:23 +00002500 else
2501 // Get the expression type from Setter's incoming parameter.
2502 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff1d984fe2009-03-11 13:48:17 +00002503 // FIXME: we must check that the setter has property type.
Fariborz Jahanian9a846652009-08-20 17:02:02 +00002504 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
Steve Naroff1d984fe2009-03-11 13:48:17 +00002505 Setter, MemberLoc, BaseExpr));
2506 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002507 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
Anders Carlssonf571c112009-08-26 18:25:21 +00002508 << MemberName << BaseType);
Fariborz Jahanian21f54ee2007-11-12 22:29:28 +00002509 }
Mike Stump11289f42009-09-09 15:08:12 +00002510
Steve Naroffe87026a2009-07-24 17:54:45 +00002511 // Handle the following exceptional case (*Obj).isa.
Mike Stump11289f42009-09-09 15:08:12 +00002512 if (OpKind == tok::period &&
Steve Naroffe87026a2009-07-24 17:54:45 +00002513 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Anders Carlssonf571c112009-08-26 18:25:21 +00002514 MemberName.getAsIdentifierInfo()->isStr("isa"))
Steve Naroffe87026a2009-07-24 17:54:45 +00002515 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2516 Context.getObjCIdType()));
2517
Chris Lattnerb63a7452008-07-21 04:28:12 +00002518 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002519 if (BaseType->isExtVectorType()) {
Anders Carlssonf571c112009-08-26 18:25:21 +00002520 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Chris Lattnerb63a7452008-07-21 04:28:12 +00002521 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2522 if (ret.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002523 return ExprError();
Anders Carlssonf571c112009-08-26 18:25:21 +00002524 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
Steve Narofff6009ed2009-01-21 00:14:39 +00002525 MemberLoc));
Chris Lattnerb63a7452008-07-21 04:28:12 +00002526 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002527
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002528 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2529 << BaseType << BaseExpr->getSourceRange();
2530
2531 // If the user is trying to apply -> or . to a function or function
2532 // pointer, it's probably because they forgot parentheses to call
2533 // the function. Suggest the addition of those parentheses.
Mike Stump11289f42009-09-09 15:08:12 +00002534 if (BaseType == Context.OverloadTy ||
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002535 BaseType->isFunctionType() ||
Mike Stump11289f42009-09-09 15:08:12 +00002536 (BaseType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002537 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor0b08ba42009-03-27 06:00:30 +00002538 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2539 Diag(Loc, diag::note_member_reference_needs_call)
2540 << CodeModificationHint::CreateInsertion(Loc, "()");
2541 }
2542
2543 return ExprError();
Chris Lattnere168f762006-11-10 05:29:30 +00002544}
2545
Anders Carlssonf571c112009-08-26 18:25:21 +00002546Action::OwningExprResult
2547Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2548 tok::TokenKind OpKind, SourceLocation MemberLoc,
2549 IdentifierInfo &Member,
2550 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
Mike Stump11289f42009-09-09 15:08:12 +00002551 return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
Anders Carlssonf571c112009-08-26 18:25:21 +00002552 DeclarationName(&Member), ObjCImpDecl, SS);
2553}
2554
Anders Carlsson355933d2009-08-25 03:49:14 +00002555Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2556 FunctionDecl *FD,
2557 ParmVarDecl *Param) {
2558 if (Param->hasUnparsedDefaultArg()) {
2559 Diag (CallLoc,
2560 diag::err_use_of_default_argument_to_function_declared_later) <<
2561 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00002562 Diag(UnparsedDefaultArgLocs[Param],
Anders Carlsson355933d2009-08-25 03:49:14 +00002563 diag::note_default_argument_declared_here);
2564 } else {
2565 if (Param->hasUninstantiatedDefaultArg()) {
2566 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2567
2568 // Instantiate the expression.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002569 MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
Anders Carlsson657bad42009-09-05 05:14:19 +00002570
Mike Stump11289f42009-09-09 15:08:12 +00002571 InstantiatingTemplate Inst(*this, CallLoc, Param,
2572 ArgList.getInnermost().getFlatArgumentList(),
Douglas Gregor01afeef2009-08-28 20:31:08 +00002573 ArgList.getInnermost().flat_size());
Anders Carlsson355933d2009-08-25 03:49:14 +00002574
John McCall76d824f2009-08-25 22:02:44 +00002575 OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
Mike Stump11289f42009-09-09 15:08:12 +00002576 if (Result.isInvalid())
Anders Carlsson355933d2009-08-25 03:49:14 +00002577 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002578
2579 if (SetParamDefaultArgument(Param, move(Result),
Anders Carlsson355933d2009-08-25 03:49:14 +00002580 /*FIXME:EqualLoc*/
2581 UninstExpr->getSourceRange().getBegin()))
2582 return ExprError();
2583 }
Mike Stump11289f42009-09-09 15:08:12 +00002584
Anders Carlsson355933d2009-08-25 03:49:14 +00002585 Expr *DefaultExpr = Param->getDefaultArg();
Mike Stump11289f42009-09-09 15:08:12 +00002586
Anders Carlsson355933d2009-08-25 03:49:14 +00002587 // If the default expression creates temporaries, we need to
2588 // push them to the current stack of expression temporaries so they'll
2589 // be properly destroyed.
Mike Stump11289f42009-09-09 15:08:12 +00002590 if (CXXExprWithTemporaries *E
Anders Carlsson355933d2009-08-25 03:49:14 +00002591 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002592 assert(!E->shouldDestroyTemporaries() &&
Anders Carlsson355933d2009-08-25 03:49:14 +00002593 "Can't destroy temporaries in a default argument expr!");
2594 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2595 ExprTemporaries.push_back(E->getTemporary(I));
2596 }
2597 }
2598
2599 // We already type-checked the argument, so we know it works.
2600 return Owned(CXXDefaultArgExpr::Create(Context, Param));
2601}
2602
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002603/// ConvertArgumentsForCall - Converts the arguments specified in
2604/// Args/NumArgs to the parameter types of the function FDecl with
2605/// function prototype Proto. Call is the call expression itself, and
2606/// Fn is the function expression. For a C++ member function, this
2607/// routine does not attempt to convert the object argument. Returns
2608/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00002609bool
2610Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002611 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002612 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002613 Expr **Args, unsigned NumArgs,
2614 SourceLocation RParenLoc) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00002615 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002616 // assignment, to the types of the corresponding parameter, ...
2617 unsigned NumArgsInProto = Proto->getNumArgs();
2618 unsigned NumArgsToCheck = NumArgs;
Douglas Gregorb6b99612009-01-23 21:30:56 +00002619 bool Invalid = false;
2620
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002621 // If too few arguments are available (and we don't have default
2622 // arguments for the remaining parameters), don't make the call.
2623 if (NumArgs < NumArgsInProto) {
2624 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2625 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2626 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2627 // Use default arguments for missing arguments
2628 NumArgsToCheck = NumArgsInProto;
Ted Kremenek5a201952009-02-07 01:47:29 +00002629 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002630 }
2631
2632 // If too many are passed and not variadic, error on the extras and drop
2633 // them.
2634 if (NumArgs > NumArgsInProto) {
2635 if (!Proto->isVariadic()) {
2636 Diag(Args[NumArgsInProto]->getLocStart(),
2637 diag::err_typecheck_call_too_many_args)
2638 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2639 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2640 Args[NumArgs-1]->getLocEnd());
2641 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00002642 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregorb6b99612009-01-23 21:30:56 +00002643 Invalid = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002644 }
2645 NumArgsToCheck = NumArgsInProto;
2646 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002647
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002648 // Continue to check argument types (even if we have too few/many args).
2649 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2650 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002651
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002652 Expr *Arg;
Douglas Gregor58354032008-12-24 00:01:03 +00002653 if (i < NumArgs) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002654 Arg = Args[i];
Douglas Gregor58354032008-12-24 00:01:03 +00002655
Eli Friedman3164fb12009-03-22 22:00:50 +00002656 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2657 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00002658 PDiag(diag::err_call_incomplete_argument)
2659 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00002660 return true;
2661
Douglas Gregor58354032008-12-24 00:01:03 +00002662 // Pass the argument.
2663 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2664 return true;
Anders Carlsson84613c42009-06-12 16:51:40 +00002665 } else {
Anders Carlssonc80a1272009-08-25 02:29:20 +00002666 ParmVarDecl *Param = FDecl->getParamDecl(i);
Mike Stump11289f42009-09-09 15:08:12 +00002667
2668 OwningExprResult ArgExpr =
Anders Carlsson355933d2009-08-25 03:49:14 +00002669 BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2670 FDecl, Param);
2671 if (ArgExpr.isInvalid())
2672 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002673
Anders Carlsson355933d2009-08-25 03:49:14 +00002674 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00002675 }
Mike Stump11289f42009-09-09 15:08:12 +00002676
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002677 Call->setArg(i, Arg);
2678 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00002679
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002680 // If this is a variadic call, handle args passed through "...".
2681 if (Proto->isVariadic()) {
Anders Carlssona7d069d2009-01-16 16:48:51 +00002682 VariadicCallType CallType = VariadicFunction;
2683 if (Fn->getType()->isBlockPointerType())
2684 CallType = VariadicBlock; // Block
2685 else if (isa<MemberExpr>(Fn))
2686 CallType = VariadicMethod;
2687
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002688 // Promote the arguments (C99 6.5.2.2p7).
2689 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2690 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00002691 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002692 Call->setArg(i, Arg);
2693 }
2694 }
2695
Douglas Gregorb6b99612009-01-23 21:30:56 +00002696 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002697}
2698
Douglas Gregorcabea402009-09-22 15:41:20 +00002699/// \brief "Deconstruct" the function argument of a call expression to find
2700/// the underlying declaration (if any), the name of the called function,
2701/// whether argument-dependent lookup is available, whether it has explicit
2702/// template arguments, etc.
2703void Sema::DeconstructCallFunction(Expr *FnExpr,
2704 NamedDecl *&Function,
2705 DeclarationName &Name,
2706 NestedNameSpecifier *&Qualifier,
2707 SourceRange &QualifierRange,
2708 bool &ArgumentDependentLookup,
2709 bool &HasExplicitTemplateArguments,
2710 const TemplateArgument *&ExplicitTemplateArgs,
2711 unsigned &NumExplicitTemplateArgs) {
2712 // Set defaults for all of the output parameters.
2713 Function = 0;
2714 Name = DeclarationName();
2715 Qualifier = 0;
2716 QualifierRange = SourceRange();
2717 ArgumentDependentLookup = getLangOptions().CPlusPlus;
2718 HasExplicitTemplateArguments = false;
2719
2720 // If we're directly calling a function, get the appropriate declaration.
2721 // Also, in C++, keep track of whether we should perform argument-dependent
2722 // lookup and whether there were any explicitly-specified template arguments.
2723 while (true) {
2724 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2725 FnExpr = IcExpr->getSubExpr();
2726 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2727 // Parentheses around a function disable ADL
2728 // (C++0x [basic.lookup.argdep]p1).
2729 ArgumentDependentLookup = false;
2730 FnExpr = PExpr->getSubExpr();
2731 } else if (isa<UnaryOperator>(FnExpr) &&
2732 cast<UnaryOperator>(FnExpr)->getOpcode()
2733 == UnaryOperator::AddrOf) {
2734 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregorcabea402009-09-22 15:41:20 +00002735 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
2736 Function = dyn_cast<NamedDecl>(DRExpr->getDecl());
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002737 if ((Qualifier = DRExpr->getQualifier())) {
2738 ArgumentDependentLookup = false;
2739 QualifierRange = DRExpr->getQualifierRange();
2740 }
Douglas Gregorcabea402009-09-22 15:41:20 +00002741 break;
2742 } else if (UnresolvedFunctionNameExpr *DepName
2743 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2744 Name = DepName->getName();
2745 break;
2746 } else if (TemplateIdRefExpr *TemplateIdRef
2747 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2748 Function = TemplateIdRef->getTemplateName().getAsTemplateDecl();
2749 if (!Function)
2750 Function = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
2751 HasExplicitTemplateArguments = true;
2752 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2753 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2754
2755 // C++ [temp.arg.explicit]p6:
2756 // [Note: For simple function names, argument dependent lookup (3.4.2)
2757 // applies even when the function name is not visible within the
2758 // scope of the call. This is because the call still has the syntactic
2759 // form of a function call (3.4.1). But when a function template with
2760 // explicit template arguments is used, the call does not have the
2761 // correct syntactic form unless there is a function template with
2762 // that name visible at the point of the call. If no such name is
2763 // visible, the call is not syntactically well-formed and
2764 // argument-dependent lookup does not apply. If some such name is
2765 // visible, argument dependent lookup applies and additional function
2766 // templates may be found in other namespaces.
2767 //
2768 // The summary of this paragraph is that, if we get to this point and the
2769 // template-id was not a qualified name, then argument-dependent lookup
2770 // is still possible.
2771 if ((Qualifier = TemplateIdRef->getQualifier())) {
2772 ArgumentDependentLookup = false;
2773 QualifierRange = TemplateIdRef->getQualifierRange();
2774 }
2775 break;
2776 } else {
2777 // Any kind of name that does not refer to a declaration (or
2778 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2779 ArgumentDependentLookup = false;
2780 break;
2781 }
2782 }
2783}
2784
Steve Naroff83895f72007-09-16 03:34:24 +00002785/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00002786/// This provides the location of the left/right parens and a list of comma
2787/// locations.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002788Action::OwningExprResult
2789Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2790 MultiExprArg args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002791 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002792 unsigned NumArgs = args.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002793
2794 // Since this might be a postfix expression, get rid of ParenListExprs.
2795 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
Mike Stump11289f42009-09-09 15:08:12 +00002796
Anders Carlsson3cbc8592009-05-01 19:30:39 +00002797 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002798 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner38dbdb22007-07-21 03:03:59 +00002799 assert(Fn && "no function call expression");
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002800 FunctionDecl *FDecl = NULL;
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00002801 NamedDecl *NDecl = NULL;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002802 DeclarationName UnqualifiedName;
Mike Stump11289f42009-09-09 15:08:12 +00002803
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002804 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00002805 // If this is a pseudo-destructor expression, build the call immediately.
2806 if (isa<CXXPseudoDestructorExpr>(Fn)) {
2807 if (NumArgs > 0) {
2808 // Pseudo-destructor calls should not have any arguments.
2809 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2810 << CodeModificationHint::CreateRemoval(
2811 SourceRange(Args[0]->getLocStart(),
2812 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00002813
Douglas Gregorad8a3362009-09-04 17:36:40 +00002814 for (unsigned I = 0; I != NumArgs; ++I)
2815 Args[I]->Destroy(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002816
Douglas Gregorad8a3362009-09-04 17:36:40 +00002817 NumArgs = 0;
2818 }
Mike Stump11289f42009-09-09 15:08:12 +00002819
Douglas Gregorad8a3362009-09-04 17:36:40 +00002820 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2821 RParenLoc));
2822 }
Mike Stump11289f42009-09-09 15:08:12 +00002823
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002824 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00002825 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00002826 // FIXME: Will need to cache the results of name lookup (including ADL) in
2827 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002828 bool Dependent = false;
2829 if (Fn->isTypeDependent())
2830 Dependent = true;
2831 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2832 Dependent = true;
2833
2834 if (Dependent)
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002835 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002836 Context.DependentTy, RParenLoc));
2837
2838 // Determine whether this is a call to an object (C++ [over.call.object]).
2839 if (Fn->getType()->isRecordType())
2840 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2841 CommaLocs, RParenLoc));
2842
Douglas Gregore254f902009-02-04 00:32:51 +00002843 // Determine whether this is a call to a member function.
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002844 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2845 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2846 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2847 isa<CXXMethodDecl>(MemDecl) ||
2848 (isa<FunctionTemplateDecl>(MemDecl) &&
2849 isa<CXXMethodDecl>(
2850 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002851 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2852 CommaLocs, RParenLoc));
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002853 }
Anders Carlsson61914b52009-10-03 17:40:22 +00002854
2855 // Determine whether this is a call to a pointer-to-member function.
2856 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Fn->IgnoreParens())) {
2857 if (BO->getOpcode() == BinaryOperator::PtrMemD ||
2858 BO->getOpcode() == BinaryOperator::PtrMemI) {
2859 const FunctionProtoType *FPT = cast<FunctionProtoType>(BO->getType());
Anders Carlsson63dce022009-10-15 00:41:48 +00002860 QualType ResultTy = FPT->getResultType().getNonReferenceType();
Anders Carlsson61914b52009-10-03 17:40:22 +00002861
Anders Carlsson63dce022009-10-15 00:41:48 +00002862 ExprOwningPtr<CXXMemberCallExpr>
2863 TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
2864 NumArgs, ResultTy,
2865 RParenLoc));
Anders Carlsson61914b52009-10-03 17:40:22 +00002866
Anders Carlsson63dce022009-10-15 00:41:48 +00002867 if (CheckCallReturnType(FPT->getResultType(),
2868 BO->getRHS()->getSourceRange().getBegin(),
2869 TheCall.get(), 0))
2870 return ExprError();
2871
Anders Carlsson61914b52009-10-03 17:40:22 +00002872 if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
2873 RParenLoc))
2874 return ExprError();
2875
2876 return Owned(MaybeBindToTemporary(TheCall.release()).release());
2877 }
2878 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002879 }
2880
Douglas Gregore254f902009-02-04 00:32:51 +00002881 // If we're directly calling a function, get the appropriate declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002882 // Also, in C++, keep track of whether we should perform argument-dependent
Douglas Gregor89026b52009-06-30 23:57:56 +00002883 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregore254f902009-02-04 00:32:51 +00002884 bool ADL = true;
Douglas Gregor89026b52009-06-30 23:57:56 +00002885 bool HasExplicitTemplateArgs = 0;
2886 const TemplateArgument *ExplicitTemplateArgs = 0;
2887 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregorcabea402009-09-22 15:41:20 +00002888 NestedNameSpecifier *Qualifier = 0;
2889 SourceRange QualifierRange;
2890 DeconstructCallFunction(Fn, NDecl, UnqualifiedName, Qualifier, QualifierRange,
2891 ADL,HasExplicitTemplateArgs, ExplicitTemplateArgs,
2892 NumExplicitTemplateArgs);
Mike Stump4e1f26a2009-02-19 03:04:26 +00002893
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002894 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002895 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregora727cb92009-06-30 22:34:41 +00002896 if (NDecl) {
2897 FDecl = dyn_cast<FunctionDecl>(NDecl);
2898 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002899 FDecl = FunctionTemplate->getTemplatedDecl();
2900 else
Douglas Gregora727cb92009-06-30 22:34:41 +00002901 FDecl = dyn_cast<FunctionDecl>(NDecl);
2902 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregorb8a9a412009-02-04 15:01:18 +00002903 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002904
Mike Stump11289f42009-09-09 15:08:12 +00002905 if (Ovl || FunctionTemplate ||
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002906 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregorb9063fc2009-02-13 23:20:09 +00002907 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002908 if (FDecl && FDecl->getBuiltinID() && FDecl->isImplicit())
Douglas Gregore254f902009-02-04 00:32:51 +00002909 ADL = false;
2910
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002911 // We don't perform ADL in C.
2912 if (!getLangOptions().CPlusPlus)
2913 ADL = false;
2914
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002915 if (Ovl || FunctionTemplate || ADL) {
Mike Stump11289f42009-09-09 15:08:12 +00002916 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00002917 HasExplicitTemplateArgs,
2918 ExplicitTemplateArgs,
2919 NumExplicitTemplateArgs,
Mike Stump11289f42009-09-09 15:08:12 +00002920 LParenLoc, Args, NumArgs, CommaLocs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002921 RParenLoc, ADL);
Douglas Gregore254f902009-02-04 00:32:51 +00002922 if (!FDecl)
2923 return ExprError();
2924
Douglas Gregor091f0422009-10-23 22:18:25 +00002925 Fn = FixOverloadedFunctionReference(Fn, FDecl);
Douglas Gregore254f902009-02-04 00:32:51 +00002926 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002927 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002928
2929 // Promote the function operand.
2930 UsualUnaryConversions(Fn);
2931
Chris Lattner08464942007-12-28 05:29:59 +00002932 // Make the call expr early, before semantic checks. This guarantees cleanup
2933 // of arguments and function on error.
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002934 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2935 Args, NumArgs,
2936 Context.BoolTy,
2937 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002938
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002939 const FunctionType *FuncT;
2940 if (!Fn->getType()->isBlockPointerType()) {
2941 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2942 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002943 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002944 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002945 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2946 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00002947 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002948 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002949 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00002950 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002951 }
Chris Lattner08464942007-12-28 05:29:59 +00002952 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002953 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2954 << Fn->getType() << Fn->getSourceRange());
2955
Eli Friedman3164fb12009-03-22 22:00:50 +00002956 // Check for a valid return type
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002957 if (CheckCallReturnType(FuncT->getResultType(),
2958 Fn->getSourceRange().getBegin(), TheCall.get(),
2959 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00002960 return ExprError();
2961
Chris Lattner08464942007-12-28 05:29:59 +00002962 // We know the result type of the call, set it.
Douglas Gregor786ab212008-10-29 02:00:59 +00002963 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002964
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002965 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00002966 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002967 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002968 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00002969 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002970 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002971
Douglas Gregord8e97de2009-04-02 15:37:10 +00002972 if (FDecl) {
2973 // Check if we have too few/too many template arguments, based
2974 // on our knowledge of the function definition.
2975 const FunctionDecl *Def = 0;
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002976 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002977 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00002978 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002979 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2980 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2981 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2982 }
2983 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00002984 }
2985
Steve Naroff0b661582007-08-28 23:30:39 +00002986 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00002987 for (unsigned i = 0; i != NumArgs; i++) {
2988 Expr *Arg = Args[i];
2989 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00002990 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2991 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00002992 PDiag(diag::err_call_incomplete_argument)
2993 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00002994 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00002995 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00002996 }
Steve Naroffae4143e2007-04-26 20:39:23 +00002997 }
Chris Lattner08464942007-12-28 05:29:59 +00002998
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002999 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3000 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003001 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3002 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003003
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003004 // Check for sentinels
3005 if (NDecl)
3006 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003007
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003008 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003009 if (FDecl) {
3010 if (CheckFunctionCall(FDecl, TheCall.get()))
3011 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003012
Douglas Gregor15fc9562009-09-12 00:22:50 +00003013 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003014 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3015 } else if (NDecl) {
3016 if (CheckBlockCall(NDecl, TheCall.get()))
3017 return ExprError();
3018 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003019
Anders Carlssonf8984012009-08-16 03:06:32 +00003020 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00003021}
3022
Sebastian Redlb5d49352009-01-19 22:31:54 +00003023Action::OwningExprResult
3024Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3025 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003026 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003027 //FIXME: Preserve type source info.
3028 QualType literalType = GetTypeFromParser(Ty);
Steve Naroff57eb2c52007-07-19 21:32:11 +00003029 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003030 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb5d49352009-01-19 22:31:54 +00003031 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003032
Eli Friedman37a186d2008-05-20 05:22:08 +00003033 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003034 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003035 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3036 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003037 } else if (!literalType->isDependentType() &&
3038 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003039 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003040 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003041 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003042 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003043
Sebastian Redlb5d49352009-01-19 22:31:54 +00003044 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003045 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003046 return ExprError();
Steve Naroffd32419d2008-01-14 18:19:28 +00003047
Chris Lattner79413952008-12-04 23:50:19 +00003048 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003049 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003050 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003051 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003052 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00003053 InitExpr.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003054 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003055 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003056}
3057
Sebastian Redlb5d49352009-01-19 22:31:54 +00003058Action::OwningExprResult
3059Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003060 SourceLocation RBraceLoc) {
3061 unsigned NumInit = initlist.size();
3062 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003063
Steve Naroff30d242c2007-09-15 18:49:24 +00003064 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003065 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003066
Mike Stump4e1f26a2009-02-19 03:04:26 +00003067 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00003068 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003069 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003070 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003071}
3072
Anders Carlsson094c4592009-10-18 18:12:03 +00003073static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3074 QualType SrcTy, QualType DestTy) {
3075 if (Context.getCanonicalType(SrcTy).getUnqualifiedType() ==
3076 Context.getCanonicalType(DestTy).getUnqualifiedType())
3077 return CastExpr::CK_NoOp;
3078
3079 if (SrcTy->hasPointerRepresentation()) {
3080 if (DestTy->hasPointerRepresentation())
3081 return CastExpr::CK_BitCast;
3082 if (DestTy->isIntegerType())
3083 return CastExpr::CK_PointerToIntegral;
3084 }
3085
3086 if (SrcTy->isIntegerType()) {
3087 if (DestTy->isIntegerType())
3088 return CastExpr::CK_IntegralCast;
3089 if (DestTy->hasPointerRepresentation())
3090 return CastExpr::CK_IntegralToPointer;
3091 if (DestTy->isRealFloatingType())
3092 return CastExpr::CK_IntegralToFloating;
3093 }
3094
3095 if (SrcTy->isRealFloatingType()) {
3096 if (DestTy->isRealFloatingType())
3097 return CastExpr::CK_FloatingCast;
3098 if (DestTy->isIntegerType())
3099 return CastExpr::CK_FloatingToIntegral;
3100 }
3101
3102 // FIXME: Assert here.
3103 // assert(false && "Unhandled cast combination!");
3104 return CastExpr::CK_Unknown;
3105}
3106
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003107/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003108bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003109 CastExpr::CastKind& Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003110 CXXMethodDecl *& ConversionDecl,
3111 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003112 if (getLangOptions().CPlusPlus)
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003113 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3114 ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003115
Eli Friedmanda8d4de2009-08-15 19:02:19 +00003116 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003117
3118 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3119 // type needs to be scalar.
3120 if (castType->isVoidType()) {
3121 // Cast to void allows any expr type.
Anders Carlssonef918ac2009-10-16 02:35:04 +00003122 Kind = CastExpr::CK_ToVoid;
3123 return false;
3124 }
3125
3126 if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003127 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3128 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3129 (castType->isStructureType() || castType->isUnionType())) {
3130 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003131 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003132 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3133 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003134 Kind = CastExpr::CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003135 return false;
3136 }
3137
3138 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003139 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003140 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003141 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003142 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003143 Field != FieldEnd; ++Field) {
3144 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3145 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3146 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3147 << castExpr->getSourceRange();
3148 break;
3149 }
3150 }
3151 if (Field == FieldEnd)
3152 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3153 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003154 Kind = CastExpr::CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003155 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003156 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00003157
3158 // Reject any other conversions to non-scalar types.
3159 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3160 << castType << castExpr->getSourceRange();
3161 }
3162
3163 if (!castExpr->getType()->isScalarType() &&
3164 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003165 return Diag(castExpr->getLocStart(),
3166 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003167 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003168 }
3169
Anders Carlsson43d70f82009-10-16 05:23:41 +00003170 if (castType->isExtVectorType())
3171 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3172
Anders Carlsson525b76b2009-10-16 02:48:28 +00003173 if (castType->isVectorType())
3174 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3175 if (castExpr->getType()->isVectorType())
3176 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3177
3178 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffb47acdb2009-04-08 23:52:26 +00003179 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003180
Anders Carlsson43d70f82009-10-16 05:23:41 +00003181 if (isa<ObjCSelectorExpr>(castExpr))
3182 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3183
Anders Carlsson525b76b2009-10-16 02:48:28 +00003184 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003185 QualType castExprType = castExpr->getType();
3186 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3187 return Diag(castExpr->getLocStart(),
3188 diag::err_cast_pointer_from_non_pointer_int)
3189 << castExprType << castExpr->getSourceRange();
3190 } else if (!castExpr->getType()->isArithmeticType()) {
3191 if (!castType->isIntegralType() && castType->isArithmeticType())
3192 return Diag(castExpr->getLocStart(),
3193 diag::err_cast_pointer_to_non_pointer_int)
3194 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003195 }
Anders Carlsson094c4592009-10-18 18:12:03 +00003196
3197 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003198 return false;
3199}
3200
Anders Carlsson525b76b2009-10-16 02:48:28 +00003201bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3202 CastExpr::CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003203 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003204
Anders Carlssonde71adf2007-11-27 05:51:55 +00003205 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003206 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003207 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003208 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003209 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003210 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003211 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003212 } else
3213 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003214 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003215 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003216
Anders Carlsson525b76b2009-10-16 02:48:28 +00003217 Kind = CastExpr::CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003218 return false;
3219}
3220
Anders Carlsson43d70f82009-10-16 05:23:41 +00003221bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3222 CastExpr::CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00003223 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson43d70f82009-10-16 05:23:41 +00003224
3225 QualType SrcTy = CastExpr->getType();
3226
Nate Begemanc8961a42009-06-27 22:05:55 +00003227 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3228 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003229 if (SrcTy->isVectorType()) {
3230 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3231 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3232 << DestTy << SrcTy << R;
Anders Carlsson43d70f82009-10-16 05:23:41 +00003233 Kind = CastExpr::CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00003234 return false;
3235 }
3236
Nate Begemanbd956c42009-06-28 02:36:38 +00003237 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00003238 // conversion will take place first from scalar to elt type, and then
3239 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00003240 if (SrcTy->isPointerType())
3241 return Diag(R.getBegin(),
3242 diag::err_invalid_conversion_between_vector_and_scalar)
3243 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003244
3245 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3246 ImpCastExprToType(CastExpr, DestElemTy,
3247 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson43d70f82009-10-16 05:23:41 +00003248
3249 Kind = CastExpr::CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00003250 return false;
3251}
3252
Sebastian Redlb5d49352009-01-19 22:31:54 +00003253Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00003254Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003255 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssonf10e4142009-08-07 22:21:05 +00003256 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump11289f42009-09-09 15:08:12 +00003257
Sebastian Redlb5d49352009-01-19 22:31:54 +00003258 assert((Ty != 0) && (Op.get() != 0) &&
3259 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00003260
Nate Begeman5ec4b312009-08-10 23:49:36 +00003261 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003262 //FIXME: Preserve type source info.
3263 QualType castType = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003264
Nate Begeman5ec4b312009-08-10 23:49:36 +00003265 // If the Expr being casted is a ParenListExpr, handle it specially.
3266 if (isa<ParenListExpr>(castExpr))
3267 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlssone9766d52009-09-09 21:33:21 +00003268 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003269 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlssone9766d52009-09-09 21:33:21 +00003270 Kind, Method))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003271 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00003272
3273 if (Method) {
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003274 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlssone9766d52009-09-09 21:33:21 +00003275 Method, move(Op));
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003276
Anders Carlssone9766d52009-09-09 21:33:21 +00003277 if (CastArg.isInvalid())
3278 return ExprError();
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003279
Anders Carlssone9766d52009-09-09 21:33:21 +00003280 castExpr = CastArg.takeAs<Expr>();
3281 } else {
3282 Op.release();
Fariborz Jahanian3df87672009-08-29 19:15:16 +00003283 }
Mike Stump11289f42009-09-09 15:08:12 +00003284
Sebastian Redl9f831db2009-07-25 15:41:38 +00003285 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump11289f42009-09-09 15:08:12 +00003286 Kind, castExpr, castType,
Anders Carlssonf10e4142009-08-07 22:21:05 +00003287 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003288}
3289
Nate Begeman5ec4b312009-08-10 23:49:36 +00003290/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3291/// of comma binary operators.
3292Action::OwningExprResult
3293Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3294 Expr *expr = EA.takeAs<Expr>();
3295 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3296 if (!E)
3297 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00003298
Nate Begeman5ec4b312009-08-10 23:49:36 +00003299 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00003300
Nate Begeman5ec4b312009-08-10 23:49:36 +00003301 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3302 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3303 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00003304
Nate Begeman5ec4b312009-08-10 23:49:36 +00003305 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3306}
3307
3308Action::OwningExprResult
3309Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3310 SourceLocation RParenLoc, ExprArg Op,
3311 QualType Ty) {
3312 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump11289f42009-09-09 15:08:12 +00003313
3314 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman5ec4b312009-08-10 23:49:36 +00003315 // then handle it as such.
3316 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3317 if (PE->getNumExprs() == 0) {
3318 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3319 return ExprError();
3320 }
3321
3322 llvm::SmallVector<Expr *, 8> initExprs;
3323 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3324 initExprs.push_back(PE->getExpr(i));
3325
3326 // FIXME: This means that pretty-printing the final AST will produce curly
3327 // braces instead of the original commas.
3328 Op.release();
Mike Stump11289f42009-09-09 15:08:12 +00003329 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00003330 initExprs.size(), RParenLoc);
3331 E->setType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003332 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003333 Owned(E));
3334 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003335 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00003336 // sequence of BinOp comma operators.
3337 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3338 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3339 }
3340}
3341
3342Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3343 SourceLocation R,
3344 MultiExprArg Val) {
3345 unsigned nexprs = Val.size();
3346 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3347 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3348 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3349 return Owned(expr);
3350}
3351
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003352/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3353/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00003354/// C99 6.5.15
3355QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3356 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003357 // C++ is sufficiently different to merit its own checker.
3358 if (getLangOptions().CPlusPlus)
3359 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3360
Chris Lattner432cff52009-02-18 04:28:32 +00003361 UsualUnaryConversions(Cond);
3362 UsualUnaryConversions(LHS);
3363 UsualUnaryConversions(RHS);
3364 QualType CondTy = Cond->getType();
3365 QualType LHSTy = LHS->getType();
3366 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00003367
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003368 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003369 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3370 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3371 << CondTy;
3372 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003373 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003374
Chris Lattnere2949f42008-01-06 22:42:25 +00003375 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00003376 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3377 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00003378
Chris Lattnere2949f42008-01-06 22:42:25 +00003379 // If both operands have arithmetic type, do the usual arithmetic conversions
3380 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00003381 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3382 UsualArithmeticConversions(LHS, RHS);
3383 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00003384 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003385
Chris Lattnere2949f42008-01-06 22:42:25 +00003386 // If both operands are the same structure or union type, the result is that
3387 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003388 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3389 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00003390 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00003391 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00003392 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00003393 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00003394 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003395 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003396
Chris Lattnere2949f42008-01-06 22:42:25 +00003397 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00003398 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00003399 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3400 if (!LHSTy->isVoidType())
3401 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3402 << RHS->getSourceRange();
3403 if (!RHSTy->isVoidType())
3404 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3405 << LHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003406 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3407 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00003408 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00003409 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00003410 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3411 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00003412 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00003413 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003414 // promote the null to a pointer.
3415 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00003416 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003417 }
Steve Naroff6b712a72009-07-14 18:25:06 +00003418 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00003419 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003420 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00003421 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003422 }
David Chisnall9f57c292009-08-17 16:35:33 +00003423 // Handle things like Class and struct objc_class*. Here we case the result
3424 // to the pseudo-builtin, because that will be implicitly cast back to the
3425 // redefinition type if an attempt is made to access its fields.
3426 if (LHSTy->isObjCClassType() &&
3427 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003428 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003429 return LHSTy;
3430 }
3431 if (RHSTy->isObjCClassType() &&
3432 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003433 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003434 return RHSTy;
3435 }
3436 // And the same for struct objc_object* / id
3437 if (LHSTy->isObjCIdType() &&
3438 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003439 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003440 return LHSTy;
3441 }
3442 if (RHSTy->isObjCIdType() &&
3443 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003444 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003445 return RHSTy;
3446 }
Steve Naroff05efa972009-07-01 14:36:47 +00003447 // Handle block pointer types.
3448 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3449 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3450 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3451 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003452 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3453 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003454 return destType;
3455 }
3456 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3457 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3458 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00003459 }
Steve Naroff05efa972009-07-01 14:36:47 +00003460 // We have 2 block pointer types.
3461 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3462 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00003463 return LHSTy;
3464 }
Steve Naroff05efa972009-07-01 14:36:47 +00003465 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003466 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3467 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003468
Steve Naroff05efa972009-07-01 14:36:47 +00003469 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3470 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00003471 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3472 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3473 // In this situation, we assume void* type. No especially good
3474 // reason, but this is what gcc does, and we do have to pick
3475 // to get a consistent AST.
3476 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003477 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3478 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00003479 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003480 }
Steve Naroff05efa972009-07-01 14:36:47 +00003481 // The block pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00003482 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3483 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00003484 return LHSTy;
3485 }
Steve Naroff05efa972009-07-01 14:36:47 +00003486 // Check constraints for Objective-C object pointers types.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003487 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003488
Steve Naroff05efa972009-07-01 14:36:47 +00003489 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3490 // Two identical object pointer types are always compatible.
3491 return LHSTy;
3492 }
John McCall9dd450b2009-09-21 23:43:11 +00003493 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3494 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
Steve Naroff05efa972009-07-01 14:36:47 +00003495 QualType compositeType = LHSTy;
Mike Stump11289f42009-09-09 15:08:12 +00003496
Steve Naroff05efa972009-07-01 14:36:47 +00003497 // If both operands are interfaces and either operand can be
3498 // assigned to the other, use that type as the composite
3499 // type. This allows
3500 // xxx ? (A*) a : (B*) b
3501 // where B is a subclass of A.
3502 //
3503 // Additionally, as for assignment, if either type is 'id'
3504 // allow silent coercion. Finally, if the types are
3505 // incompatible then make sure to use 'id' as the composite
3506 // type so the result is acceptable for sending messages to.
3507
3508 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3509 // It could return the composite type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003510 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahaniana83c0162009-08-22 22:27:17 +00003511 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003512 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahaniana83c0162009-08-22 22:27:17 +00003513 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump11289f42009-09-09 15:08:12 +00003514 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00003515 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff8e6aee52009-07-23 01:01:38 +00003516 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump11289f42009-09-09 15:08:12 +00003517 // Need to handle "id<xx>" explicitly.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003518 // GCC allows qualified id and any Objective-C type to devolve to
3519 // id. Currently localizing to here until clear this should be
3520 // part of ObjCQualifiedIdTypesAreCompatible.
3521 compositeType = Context.getObjCIdType();
3522 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff05efa972009-07-01 14:36:47 +00003523 compositeType = Context.getObjCIdType();
3524 } else {
3525 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3526 << LHSTy << RHSTy
3527 << LHS->getSourceRange() << RHS->getSourceRange();
3528 QualType incompatTy = Context.getObjCIdType();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003529 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3530 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003531 return incompatTy;
3532 }
3533 // The object pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00003534 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
3535 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003536 return compositeType;
3537 }
Steve Naroff85d97152009-07-29 15:09:39 +00003538 // Check Objective-C object pointer types and 'void *'
3539 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003540 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003541 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003542 QualType destPointee
3543 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff85d97152009-07-29 15:09:39 +00003544 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003545 // Add qualifiers if necessary.
3546 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3547 // Promote to void*.
3548 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff85d97152009-07-29 15:09:39 +00003549 return destType;
3550 }
3551 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
John McCall9dd450b2009-09-21 23:43:11 +00003552 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003553 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003554 QualType destPointee
3555 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff85d97152009-07-29 15:09:39 +00003556 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003557 // Add qualifiers if necessary.
3558 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
3559 // Promote to void*.
3560 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff85d97152009-07-29 15:09:39 +00003561 return destType;
3562 }
Steve Naroff05efa972009-07-01 14:36:47 +00003563 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3564 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3565 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003566 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3567 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00003568
3569 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3570 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3571 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00003572 QualType destPointee
3573 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00003574 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003575 // Add qualifiers if necessary.
3576 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3577 // Promote to void*.
3578 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003579 return destType;
3580 }
3581 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003582 QualType destPointee
3583 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00003584 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003585 // Add qualifiers if necessary.
3586 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3587 // Promote to void*.
3588 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003589 return destType;
3590 }
3591
3592 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3593 // Two identical pointer types are always compatible.
3594 return LHSTy;
3595 }
3596 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3597 rhptee.getUnqualifiedType())) {
3598 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3599 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3600 // In this situation, we assume void* type. No especially good
3601 // reason, but this is what gcc does, and we do have to pick
3602 // to get a consistent AST.
3603 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003604 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3605 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003606 return incompatTy;
3607 }
3608 // The pointer types are compatible.
3609 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3610 // differently qualified versions of compatible types, the result type is
3611 // a pointer to an appropriately qualified version of the *composite*
3612 // type.
3613 // FIXME: Need to calculate the composite type.
3614 // FIXME: Need to add qualifiers
Eli Friedman06ed2a52009-10-20 08:27:19 +00003615 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3616 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003617 return LHSTy;
3618 }
Mike Stump11289f42009-09-09 15:08:12 +00003619
Steve Naroff05efa972009-07-01 14:36:47 +00003620 // GCC compatibility: soften pointer/integer mismatch.
3621 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3622 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3623 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003624 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00003625 return RHSTy;
3626 }
3627 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3628 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3629 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003630 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00003631 return LHSTy;
3632 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00003633
Chris Lattnere2949f42008-01-06 22:42:25 +00003634 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00003635 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3636 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003637 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00003638}
3639
Steve Naroff83895f72007-09-16 03:34:24 +00003640/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00003641/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003642Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3643 SourceLocation ColonLoc,
3644 ExprArg Cond, ExprArg LHS,
3645 ExprArg RHS) {
3646 Expr *CondExpr = (Expr *) Cond.get();
3647 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00003648
3649 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3650 // was the condition.
3651 bool isLHSNull = LHSExpr == 0;
3652 if (isLHSNull)
3653 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00003654
3655 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00003656 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00003657 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003658 return ExprError();
3659
3660 Cond.release();
3661 LHS.release();
3662 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00003663 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00003664 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00003665 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00003666}
3667
Steve Naroff3f597292007-05-11 22:18:03 +00003668// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00003669// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00003670// routine is it effectively iqnores the qualifiers on the top level pointee.
3671// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3672// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003673Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00003674Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00003675 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003676
David Chisnall9f57c292009-08-17 16:35:33 +00003677 if ((lhsType->isObjCClassType() &&
3678 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3679 (rhsType->isObjCClassType() &&
3680 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3681 return Compatible;
3682 }
3683
Steve Naroff1f4d7272007-05-11 04:00:31 +00003684 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003685 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3686 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003687
Steve Naroff1f4d7272007-05-11 04:00:31 +00003688 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00003689 lhptee = Context.getCanonicalType(lhptee);
3690 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00003691
Chris Lattner9bad62c2008-01-04 18:04:52 +00003692 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003693
3694 // C99 6.5.16.1p1: This following citation is common to constraints
3695 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3696 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00003697 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00003698 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00003699 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00003700
Mike Stump4e1f26a2009-02-19 03:04:26 +00003701 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3702 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00003703 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00003704 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003705 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00003706 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003707
Chris Lattner0a788432008-01-03 22:56:36 +00003708 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003709 assert(rhptee->isFunctionType());
3710 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00003711 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003712
Chris Lattner0a788432008-01-03 22:56:36 +00003713 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003714 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00003715 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00003716
3717 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003718 assert(lhptee->isFunctionType());
3719 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00003720 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003721 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00003722 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00003723 lhptee = lhptee.getUnqualifiedType();
3724 rhptee = rhptee.getUnqualifiedType();
3725 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3726 // Check if the pointee types are compatible ignoring the sign.
3727 // We explicitly check for char so that we catch "char" vs
3728 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00003729 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00003730 lhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00003731 else if (lhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00003732 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00003733
3734 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00003735 rhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00003736 else if (rhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00003737 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00003738
Eli Friedman80160bd2009-03-22 23:59:44 +00003739 if (lhptee == rhptee) {
3740 // Types are compatible ignoring the sign. Qualifier incompatibility
3741 // takes priority over sign incompatibility because the sign
3742 // warning can be disabled.
3743 if (ConvTy != Compatible)
3744 return ConvTy;
3745 return IncompatiblePointerSign;
3746 }
3747 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00003748 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00003749 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00003750 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00003751}
3752
Steve Naroff081c7422008-09-04 15:10:53 +00003753/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3754/// block pointer types are compatible or whether a block and normal pointer
3755/// are compatible. It is more restrict than comparing two function pointer
3756// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003757Sema::AssignConvertType
3758Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00003759 QualType rhsType) {
3760 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003761
Steve Naroff081c7422008-09-04 15:10:53 +00003762 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003763 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3764 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003765
Steve Naroff081c7422008-09-04 15:10:53 +00003766 // make sure we operate on the canonical type
3767 lhptee = Context.getCanonicalType(lhptee);
3768 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003769
Steve Naroff081c7422008-09-04 15:10:53 +00003770 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003771
Steve Naroff081c7422008-09-04 15:10:53 +00003772 // For blocks we enforce that qualifiers are identical.
3773 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3774 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003775
Eli Friedmana6638ca2009-06-08 05:08:54 +00003776 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00003777 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00003778 return ConvTy;
3779}
3780
Mike Stump4e1f26a2009-02-19 03:04:26 +00003781/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3782/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00003783/// pointers. Here are some objectionable examples that GCC considers warnings:
3784///
3785/// int a, *pint;
3786/// short *pshort;
3787/// struct foo *pfoo;
3788///
3789/// pint = pshort; // warning: assignment from incompatible pointer type
3790/// a = pint; // warning: assignment makes integer from pointer without a cast
3791/// pint = a; // warning: assignment makes pointer from integer without a cast
3792/// pint = pfoo; // warning: assignment from incompatible pointer type
3793///
3794/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00003795/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00003796///
Chris Lattner9bad62c2008-01-04 18:04:52 +00003797Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00003798Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00003799 // Get canonical types. We're not formatting these types, just comparing
3800 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00003801 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3802 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00003803
3804 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00003805 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00003806
David Chisnall9f57c292009-08-17 16:35:33 +00003807 if ((lhsType->isObjCClassType() &&
3808 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3809 (rhsType->isObjCClassType() &&
3810 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3811 return Compatible;
3812 }
3813
Douglas Gregor6b754842008-10-28 00:22:11 +00003814 // If the left-hand side is a reference type, then we are in a
3815 // (rare!) case where we've allowed the use of references in C,
3816 // e.g., as a parameter type in a built-in function. In this case,
3817 // just make sure that the type referenced is compatible with the
3818 // right-hand side type. The caller is responsible for adjusting
3819 // lhsType so that the resulting expression does not have reference
3820 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003821 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00003822 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00003823 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00003824 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00003825 }
Nate Begemanbd956c42009-06-28 02:36:38 +00003826 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3827 // to the same ExtVector type.
3828 if (lhsType->isExtVectorType()) {
3829 if (rhsType->isExtVectorType())
3830 return lhsType == rhsType ? Compatible : Incompatible;
3831 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3832 return Compatible;
3833 }
Mike Stump11289f42009-09-09 15:08:12 +00003834
Nate Begeman191a6b12008-07-14 18:02:46 +00003835 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00003836 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00003837 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00003838 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00003839 if (getLangOptions().LaxVectorConversions &&
3840 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00003841 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00003842 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00003843 }
3844 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003845 }
Eli Friedman3360d892008-05-30 18:07:22 +00003846
Chris Lattner881a2122008-01-04 23:32:24 +00003847 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Steve Naroff98cf3e92007-06-06 18:38:38 +00003848 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00003849
Chris Lattnerec646832008-04-07 06:49:41 +00003850 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00003851 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00003852 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00003853
Chris Lattnerec646832008-04-07 06:49:41 +00003854 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00003855 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003856
Steve Naroffaccc4882009-07-20 17:56:53 +00003857 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003858 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00003859 if (lhsType->isVoidPointerType()) // an exception to the rule.
3860 return Compatible;
3861 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003862 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003863 if (rhsType->getAs<BlockPointerType>()) {
3864 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00003865 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00003866
3867 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003868 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00003869 return Compatible;
3870 }
Steve Naroff081c7422008-09-04 15:10:53 +00003871 return Incompatible;
3872 }
3873
3874 if (isa<BlockPointerType>(lhsType)) {
3875 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00003876 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003877
Steve Naroff32d072c2008-09-29 18:10:17 +00003878 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003879 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00003880 return Compatible;
3881
Steve Naroff081c7422008-09-04 15:10:53 +00003882 if (rhsType->isBlockPointerType())
3883 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003884
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003885 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00003886 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00003887 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00003888 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00003889 return Incompatible;
3890 }
3891
Steve Naroff7cae42b2009-07-10 23:34:53 +00003892 if (isa<ObjCObjectPointerType>(lhsType)) {
3893 if (rhsType->isIntegerType())
3894 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00003895
Steve Naroffaccc4882009-07-20 17:56:53 +00003896 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003897 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00003898 if (rhsType->isVoidPointerType()) // an exception to the rule.
3899 return Compatible;
3900 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003901 }
3902 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003903 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3904 return Compatible;
Steve Naroffaccc4882009-07-20 17:56:53 +00003905 if (Context.typesAreCompatible(lhsType, rhsType))
3906 return Compatible;
Steve Naroff8e6aee52009-07-23 01:01:38 +00003907 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3908 return IncompatibleObjCQualifiedId;
Steve Naroffaccc4882009-07-20 17:56:53 +00003909 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003910 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003911 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003912 if (RHSPT->getPointeeType()->isVoidType())
3913 return Compatible;
3914 }
3915 // Treat block pointers as objects.
3916 if (rhsType->isBlockPointerType())
3917 return Compatible;
3918 return Incompatible;
3919 }
Chris Lattnerec646832008-04-07 06:49:41 +00003920 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00003921 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00003922 if (lhsType == Context.BoolTy)
3923 return Compatible;
3924
3925 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00003926 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00003927
Mike Stump4e1f26a2009-02-19 03:04:26 +00003928 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00003929 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003930
3931 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003932 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00003933 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00003934 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00003935 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00003936 if (isa<ObjCObjectPointerType>(rhsType)) {
3937 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3938 if (lhsType == Context.BoolTy)
3939 return Compatible;
3940
3941 if (lhsType->isIntegerType())
3942 return PointerToInt;
3943
Steve Naroffaccc4882009-07-20 17:56:53 +00003944 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003945 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00003946 if (lhsType->isVoidPointerType()) // an exception to the rule.
3947 return Compatible;
3948 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003949 }
3950 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003951 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00003952 return Compatible;
3953 return Incompatible;
3954 }
Eli Friedman3360d892008-05-30 18:07:22 +00003955
Chris Lattnera52c2f22008-01-04 23:18:45 +00003956 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00003957 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00003958 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00003959 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00003960 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00003961}
3962
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003963/// \brief Constructs a transparent union from an expression that is
3964/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00003965static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003966 QualType UnionType, FieldDecl *Field) {
3967 // Build an initializer list that designates the appropriate member
3968 // of the transparent union.
3969 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3970 &E, 1,
3971 SourceLocation());
3972 Initializer->setType(UnionType);
3973 Initializer->setInitializedFieldInUnion(Field);
3974
3975 // Build a compound literal constructing a value of the transparent
3976 // union type from this initializer list.
3977 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3978 false);
3979}
3980
3981Sema::AssignConvertType
3982Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3983 QualType FromType = rExpr->getType();
3984
Mike Stump11289f42009-09-09 15:08:12 +00003985 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003986 // transparent_union GCC extension.
3987 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003988 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003989 return Incompatible;
3990
3991 // The field to initialize within the transparent union.
3992 RecordDecl *UD = UT->getDecl();
3993 FieldDecl *InitField = 0;
3994 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003995 for (RecordDecl::field_iterator it = UD->field_begin(),
3996 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003997 it != itend; ++it) {
3998 if (it->getType()->isPointerType()) {
3999 // If the transparent union contains a pointer type, we allow:
4000 // 1) void pointer
4001 // 2) null pointer constant
4002 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004003 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004004 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004005 InitField = *it;
4006 break;
4007 }
Mike Stump11289f42009-09-09 15:08:12 +00004008
Douglas Gregor56751b52009-09-25 04:25:58 +00004009 if (rExpr->isNullPointerConstant(Context,
4010 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004011 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004012 InitField = *it;
4013 break;
4014 }
4015 }
4016
4017 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4018 == Compatible) {
4019 InitField = *it;
4020 break;
4021 }
4022 }
4023
4024 if (!InitField)
4025 return Incompatible;
4026
4027 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4028 return Compatible;
4029}
4030
Chris Lattner9bad62c2008-01-04 18:04:52 +00004031Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004032Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00004033 if (getLangOptions().CPlusPlus) {
4034 if (!lhsType->isRecordType()) {
4035 // C++ 5.17p3: If the left operand is not of class type, the
4036 // expression is implicitly converted (C++ 4) to the
4037 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00004038 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4039 "assigning"))
Douglas Gregor9a657932008-10-21 23:43:52 +00004040 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00004041 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00004042 }
4043
4044 // FIXME: Currently, we fall through and treat C++ classes like C
4045 // structures.
4046 }
4047
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004048 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4049 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00004050 if ((lhsType->isPointerType() ||
4051 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00004052 lhsType->isBlockPointerType())
Douglas Gregor56751b52009-09-25 04:25:58 +00004053 && rExpr->isNullPointerConstant(Context,
4054 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004055 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004056 return Compatible;
4057 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004058
Chris Lattnere6dcd502007-10-16 02:55:40 +00004059 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004060 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff30d242c2007-09-15 18:49:24 +00004061 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004062 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00004063 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00004064 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00004065 if (!lhsType->isReferenceType())
4066 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004067
Chris Lattner9bad62c2008-01-04 18:04:52 +00004068 Sema::AssignConvertType result =
4069 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004070
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004071 // C99 6.5.16.1p2: The value of the right operand is converted to the
4072 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00004073 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4074 // so that we can use references in built-in functions even in C.
4075 // The getNonReferenceType() call makes sure that the resulting expression
4076 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004077 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004078 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4079 CastExpr::CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004080 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004081}
4082
Chris Lattner326f7572008-11-18 01:30:42 +00004083QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004084 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004085 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004086 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004087 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004088}
4089
Mike Stump4e1f26a2009-02-19 03:04:26 +00004090inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff7a5af782007-07-13 16:58:59 +00004091 Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004092 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004093 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004094 QualType lhsType =
4095 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4096 QualType rhsType =
4097 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004098
Nate Begeman191a6b12008-07-14 18:02:46 +00004099 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004100 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004101 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004102
Nate Begeman191a6b12008-07-14 18:02:46 +00004103 // Handle the case of a vector & extvector type of the same size and element
4104 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004105 if (getLangOptions().LaxVectorConversions) {
4106 // FIXME: Should we warn here?
John McCall9dd450b2009-09-21 23:43:11 +00004107 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4108 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begeman191a6b12008-07-14 18:02:46 +00004109 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004110 LV->getNumElements() == RV->getNumElements()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004111 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004112 }
4113 }
4114 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004115
Nate Begemanbd956c42009-06-28 02:36:38 +00004116 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4117 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4118 bool swapped = false;
4119 if (rhsType->isExtVectorType()) {
4120 swapped = true;
4121 std::swap(rex, lex);
4122 std::swap(rhsType, lhsType);
4123 }
Mike Stump11289f42009-09-09 15:08:12 +00004124
Nate Begeman886448d2009-06-28 19:12:57 +00004125 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00004126 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00004127 QualType EltTy = LV->getElementType();
4128 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4129 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004130 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004131 if (swapped) std::swap(rex, lex);
4132 return lhsType;
4133 }
4134 }
4135 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4136 rhsType->isRealFloatingType()) {
4137 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004138 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004139 if (swapped) std::swap(rex, lex);
4140 return lhsType;
4141 }
Nate Begeman330aaa72007-12-30 02:59:45 +00004142 }
4143 }
Mike Stump11289f42009-09-09 15:08:12 +00004144
Nate Begeman886448d2009-06-28 19:12:57 +00004145 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00004146 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004147 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004148 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00004149 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00004150}
4151
Steve Naroff218bc2b2007-05-04 21:54:46 +00004152inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004153 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00004154 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004155 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004156
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004157 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004158
Steve Naroffdbd9e892007-07-17 00:58:39 +00004159 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004160 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004161 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004162}
4163
Steve Naroff218bc2b2007-05-04 21:54:46 +00004164inline QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004165 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00004166 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4167 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4168 return CheckVectorOperands(Loc, lex, rex);
4169 return InvalidOperands(Loc, lex, rex);
4170 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004171
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004172 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004173
Steve Naroffdbd9e892007-07-17 00:58:39 +00004174 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004175 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004176 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004177}
4178
4179inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00004180 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004181 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4182 QualType compType = CheckVectorOperands(Loc, lex, rex);
4183 if (CompLHSTy) *CompLHSTy = compType;
4184 return compType;
4185 }
Steve Naroff7a5af782007-07-13 16:58:59 +00004186
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004187 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00004188
Steve Naroffe4718892007-04-27 18:30:00 +00004189 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004190 if (lex->getType()->isArithmeticType() &&
4191 rex->getType()->isArithmeticType()) {
4192 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004193 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004194 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00004195
Eli Friedman8e122982008-05-18 18:08:51 +00004196 // Put any potential pointer into PExp
4197 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00004198 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00004199 std::swap(PExp, IExp);
4200
Steve Naroff6b712a72009-07-14 18:25:06 +00004201 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004202
Eli Friedman8e122982008-05-18 18:08:51 +00004203 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004204 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004205
Chris Lattner12bdebb2009-04-24 23:50:08 +00004206 // Check for arithmetic on pointers to incomplete types.
4207 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004208 if (getLangOptions().CPlusPlus) {
4209 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00004210 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00004211 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00004212 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004213
4214 // GNU extension: arithmetic on pointer to void
4215 Diag(Loc, diag::ext_gnu_void_ptr)
4216 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00004217 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004218 if (getLangOptions().CPlusPlus) {
4219 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4220 << lex->getType() << lex->getSourceRange();
4221 return QualType();
4222 }
4223
4224 // GNU extension: arithmetic on pointer to function
4225 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4226 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00004227 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004228 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00004229 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00004230 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004231 PExp->getType()->isObjCObjectPointerType()) &&
4232 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00004233 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4234 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004235 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004236 return QualType();
4237 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00004238 // Diagnose bad cases where we step over interface counts.
4239 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4240 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4241 << PointeeTy << PExp->getSourceRange();
4242 return QualType();
4243 }
Mike Stump11289f42009-09-09 15:08:12 +00004244
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004245 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00004246 QualType LHSTy = Context.isPromotableBitField(lex);
4247 if (LHSTy.isNull()) {
4248 LHSTy = lex->getType();
4249 if (LHSTy->isPromotableIntegerType())
4250 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004251 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004252 *CompLHSTy = LHSTy;
4253 }
Eli Friedman8e122982008-05-18 18:08:51 +00004254 return PExp->getType();
4255 }
4256 }
4257
Chris Lattner326f7572008-11-18 01:30:42 +00004258 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004259}
4260
Chris Lattner2a3569b2008-04-07 05:30:13 +00004261// C99 6.5.6
4262QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004263 SourceLocation Loc, QualType* CompLHSTy) {
4264 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4265 QualType compType = CheckVectorOperands(Loc, lex, rex);
4266 if (CompLHSTy) *CompLHSTy = compType;
4267 return compType;
4268 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004269
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004270 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004271
Chris Lattner4d62f422007-12-09 21:53:25 +00004272 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004273
Chris Lattner4d62f422007-12-09 21:53:25 +00004274 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00004275 if (lex->getType()->isArithmeticType()
4276 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004277 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004278 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004279 }
Mike Stump11289f42009-09-09 15:08:12 +00004280
Chris Lattner4d62f422007-12-09 21:53:25 +00004281 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00004282 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00004283 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004284
Douglas Gregorac1fb652009-03-24 19:52:54 +00004285 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00004286
Douglas Gregorac1fb652009-03-24 19:52:54 +00004287 bool ComplainAboutVoid = false;
4288 Expr *ComplainAboutFunc = 0;
4289 if (lpointee->isVoidType()) {
4290 if (getLangOptions().CPlusPlus) {
4291 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4292 << lex->getSourceRange() << rex->getSourceRange();
4293 return QualType();
4294 }
4295
4296 // GNU C extension: arithmetic on pointer to void
4297 ComplainAboutVoid = true;
4298 } else if (lpointee->isFunctionType()) {
4299 if (getLangOptions().CPlusPlus) {
4300 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004301 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004302 return QualType();
4303 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004304
4305 // GNU C extension: arithmetic on pointer to function
4306 ComplainAboutFunc = lex;
4307 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00004308 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004309 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00004310 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004311 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004312 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004313
Chris Lattner12bdebb2009-04-24 23:50:08 +00004314 // Diagnose bad cases where we step over interface counts.
4315 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4316 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4317 << lpointee << lex->getSourceRange();
4318 return QualType();
4319 }
Mike Stump11289f42009-09-09 15:08:12 +00004320
Chris Lattner4d62f422007-12-09 21:53:25 +00004321 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00004322 if (rex->getType()->isIntegerType()) {
4323 if (ComplainAboutVoid)
4324 Diag(Loc, diag::ext_gnu_void_ptr)
4325 << lex->getSourceRange() << rex->getSourceRange();
4326 if (ComplainAboutFunc)
4327 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004328 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004329 << ComplainAboutFunc->getSourceRange();
4330
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004331 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004332 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00004333 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004334
Chris Lattner4d62f422007-12-09 21:53:25 +00004335 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004336 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00004337 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004338
Douglas Gregorac1fb652009-03-24 19:52:54 +00004339 // RHS must be a completely-type object type.
4340 // Handle the GNU void* extension.
4341 if (rpointee->isVoidType()) {
4342 if (getLangOptions().CPlusPlus) {
4343 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4344 << lex->getSourceRange() << rex->getSourceRange();
4345 return QualType();
4346 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004347
Douglas Gregorac1fb652009-03-24 19:52:54 +00004348 ComplainAboutVoid = true;
4349 } else if (rpointee->isFunctionType()) {
4350 if (getLangOptions().CPlusPlus) {
4351 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004352 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004353 return QualType();
4354 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004355
4356 // GNU extension: arithmetic on pointer to function
4357 if (!ComplainAboutFunc)
4358 ComplainAboutFunc = rex;
4359 } else if (!rpointee->isDependentType() &&
4360 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004361 PDiag(diag::err_typecheck_sub_ptr_object)
4362 << rex->getSourceRange()
4363 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004364 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004365
Eli Friedman168fe152009-05-16 13:54:38 +00004366 if (getLangOptions().CPlusPlus) {
4367 // Pointee types must be the same: C++ [expr.add]
4368 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4369 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4370 << lex->getType() << rex->getType()
4371 << lex->getSourceRange() << rex->getSourceRange();
4372 return QualType();
4373 }
4374 } else {
4375 // Pointee types must be compatible C99 6.5.6p3
4376 if (!Context.typesAreCompatible(
4377 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4378 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4379 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4380 << lex->getType() << rex->getType()
4381 << lex->getSourceRange() << rex->getSourceRange();
4382 return QualType();
4383 }
Chris Lattner4d62f422007-12-09 21:53:25 +00004384 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004385
Douglas Gregorac1fb652009-03-24 19:52:54 +00004386 if (ComplainAboutVoid)
4387 Diag(Loc, diag::ext_gnu_void_ptr)
4388 << lex->getSourceRange() << rex->getSourceRange();
4389 if (ComplainAboutFunc)
4390 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004391 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004392 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004393
4394 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004395 return Context.getPointerDiffType();
4396 }
4397 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004398
Chris Lattner326f7572008-11-18 01:30:42 +00004399 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004400}
4401
Chris Lattner2a3569b2008-04-07 05:30:13 +00004402// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00004403QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00004404 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00004405 // C99 6.5.7p2: Each of the operands shall have integer type.
4406 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00004407 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004408
Nate Begemane46ee9a2009-10-25 02:26:48 +00004409 // Vector shifts promote their scalar inputs to vector type.
4410 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4411 return CheckVectorOperands(Loc, lex, rex);
4412
Chris Lattner5c11c412007-12-12 05:47:28 +00004413 // Shifts don't perform usual arithmetic conversions, they just do integer
4414 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00004415 QualType LHSTy = Context.isPromotableBitField(lex);
4416 if (LHSTy.isNull()) {
4417 LHSTy = lex->getType();
4418 if (LHSTy->isPromotableIntegerType())
4419 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004420 }
Chris Lattner3c133402007-12-13 07:28:16 +00004421 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004422 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004423
Chris Lattner5c11c412007-12-12 05:47:28 +00004424 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004425
Ryan Flynnf53fab82009-08-07 16:20:20 +00004426 // Sanity-check shift operands
4427 llvm::APSInt Right;
4428 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00004429 if (!rex->isValueDependent() &&
4430 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00004431 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00004432 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4433 else {
4434 llvm::APInt LeftBits(Right.getBitWidth(),
4435 Context.getTypeSize(lex->getType()));
4436 if (Right.uge(LeftBits))
4437 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4438 }
4439 }
4440
Chris Lattner5c11c412007-12-12 05:47:28 +00004441 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004442 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00004443}
4444
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004445// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00004446QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004447 unsigned OpaqueOpc, bool isRelational) {
4448 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4449
Nate Begeman191a6b12008-07-14 18:02:46 +00004450 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004451 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004452
Chris Lattnerb620c342007-08-26 01:18:55 +00004453 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff47fea352007-08-10 18:26:40 +00004454 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4455 UsualArithmeticConversions(lex, rex);
4456 else {
4457 UsualUnaryConversions(lex);
4458 UsualUnaryConversions(rex);
4459 }
Steve Naroff31090012007-07-16 21:54:35 +00004460 QualType lType = lex->getType();
4461 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004462
Mike Stumpf70bcf72009-05-07 18:43:07 +00004463 if (!lType->isFloatingType()
4464 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00004465 // For non-floating point types, check for self-comparisons of the form
4466 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4467 // often indicate logic errors in the program.
Mike Stump11289f42009-09-09 15:08:12 +00004468 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenekde9e9682009-03-20 19:57:37 +00004469 // from macro expansions, and are usually quite deliberate.
Chris Lattner222b8bd2009-03-08 19:39:53 +00004470 Expr *LHSStripped = lex->IgnoreParens();
4471 Expr *RHSStripped = rex->IgnoreParens();
4472 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4473 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek9ffbe412009-03-20 18:35:45 +00004474 if (DRL->getDecl() == DRR->getDecl() &&
4475 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004476 Diag(Loc, diag::warn_selfcomparison);
Mike Stump11289f42009-09-09 15:08:12 +00004477
Chris Lattner222b8bd2009-03-08 19:39:53 +00004478 if (isa<CastExpr>(LHSStripped))
4479 LHSStripped = LHSStripped->IgnoreParenCasts();
4480 if (isa<CastExpr>(RHSStripped))
4481 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004482
Chris Lattner222b8bd2009-03-08 19:39:53 +00004483 // Warn about comparisons against a string constant (unless the other
4484 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004485 Expr *literalString = 0;
4486 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00004487 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004488 !RHSStripped->isNullPointerConstant(Context,
4489 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004490 literalString = lex;
4491 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00004492 } else if ((isa<StringLiteral>(RHSStripped) ||
4493 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004494 !LHSStripped->isNullPointerConstant(Context,
4495 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004496 literalString = rex;
4497 literalStringStripped = RHSStripped;
4498 }
4499
4500 if (literalString) {
4501 std::string resultComparison;
4502 switch (Opc) {
4503 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4504 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4505 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4506 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4507 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4508 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4509 default: assert(false && "Invalid comparison operator");
4510 }
4511 Diag(Loc, diag::warn_stringcompare)
4512 << isa<ObjCEncodeExpr>(literalStringStripped)
4513 << literalString->getSourceRange()
Douglas Gregor170512f2009-04-01 23:51:29 +00004514 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4515 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4516 "strcmp(")
4517 << CodeModificationHint::CreateInsertion(
4518 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004519 resultComparison);
4520 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00004521 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004522
Douglas Gregorca63811b2008-11-19 03:25:36 +00004523 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner222b8bd2009-03-08 19:39:53 +00004524 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00004525
Chris Lattnerb620c342007-08-26 01:18:55 +00004526 if (isRelational) {
4527 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00004528 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00004529 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00004530 // Check for comparisons of floating point operands using != and ==.
Ted Kremeneke2763b02007-10-29 17:13:39 +00004531 if (lType->isFloatingType()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00004532 assert(rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00004533 CheckFloatComparison(Loc,lex,rex);
Ted Kremenekd4ecc6d2007-10-29 16:40:01 +00004534 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004535
Chris Lattnerb620c342007-08-26 01:18:55 +00004536 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00004537 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00004538 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004539
Douglas Gregor56751b52009-09-25 04:25:58 +00004540 bool LHSIsNull = lex->isNullPointerConstant(Context,
4541 Expr::NPC_ValueDependentIsNull);
4542 bool RHSIsNull = rex->isNullPointerConstant(Context,
4543 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004544
Chris Lattnerb620c342007-08-26 01:18:55 +00004545 // All of the following pointer related warnings are GCC extensions, except
4546 // when handling null pointer constants. One day, we can consider making them
4547 // errors (when -pedantic-errors is enabled).
Steve Naroff808eb8f2007-08-27 04:08:11 +00004548 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00004549 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004550 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00004551 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004552 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004553
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004554 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00004555 if (LCanPointeeTy == RCanPointeeTy)
4556 return ResultTy;
4557
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004558 // C++ [expr.rel]p2:
4559 // [...] Pointer conversions (4.10) and qualification
4560 // conversions (4.4) are performed on pointer operands (or on
4561 // a pointer operand and a null pointer constant) to bring
4562 // them to their composite pointer type. [...]
4563 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004564 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004565 // comparisons of pointers.
Douglas Gregorb8420462009-05-05 04:50:50 +00004566 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004567 if (T.isNull()) {
4568 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4569 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4570 return QualType();
4571 }
4572
Eli Friedman06ed2a52009-10-20 08:27:19 +00004573 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4574 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004575 return ResultTy;
4576 }
Eli Friedman16c209612009-08-23 00:27:47 +00004577 // C99 6.5.9p2 and C99 6.5.8p2
4578 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4579 RCanPointeeTy.getUnqualifiedType())) {
4580 // Valid unless a relational comparison of function pointers
4581 if (isRelational && LCanPointeeTy->isFunctionType()) {
4582 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4583 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4584 }
4585 } else if (!isRelational &&
4586 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4587 // Valid unless comparison between non-null pointer and function pointer
4588 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4589 && !LHSIsNull && !RHSIsNull) {
4590 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4591 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4592 }
4593 } else {
4594 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00004595 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004596 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00004597 }
Eli Friedman16c209612009-08-23 00:27:47 +00004598 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004599 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004600 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00004601 }
Mike Stump11289f42009-09-09 15:08:12 +00004602
Sebastian Redl576fd422009-05-10 18:38:11 +00004603 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00004604 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004605 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00004606 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004607 (lType->isPointerType() ||
4608 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00004609 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00004610 return ResultTy;
4611 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004612 if (LHSIsNull &&
4613 (rType->isPointerType() ||
4614 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00004615 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00004616 return ResultTy;
4617 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004618
4619 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00004620 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004621 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4622 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004623 // In addition, pointers to members can be compared, or a pointer to
4624 // member and a null pointer constant. Pointer to member conversions
4625 // (4.11) and qualification conversions (4.4) are performed to bring
4626 // them to a common type. If one operand is a null pointer constant,
4627 // the common type is the type of the other operand. Otherwise, the
4628 // common type is a pointer to member type similar (4.4) to the type
4629 // of one of the operands, with a cv-qualification signature (4.4)
4630 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004631 // types.
4632 QualType T = FindCompositePointerType(lex, rex);
4633 if (T.isNull()) {
4634 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4635 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4636 return QualType();
4637 }
Mike Stump11289f42009-09-09 15:08:12 +00004638
Eli Friedman06ed2a52009-10-20 08:27:19 +00004639 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4640 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004641 return ResultTy;
4642 }
Mike Stump11289f42009-09-09 15:08:12 +00004643
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004644 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00004645 if (lType->isNullPtrType() && rType->isNullPtrType())
4646 return ResultTy;
4647 }
Mike Stump11289f42009-09-09 15:08:12 +00004648
Steve Naroff081c7422008-09-04 15:10:53 +00004649 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00004650 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004651 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4652 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004653
Steve Naroff081c7422008-09-04 15:10:53 +00004654 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00004655 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004656 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004657 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00004658 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004659 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004660 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00004661 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00004662 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00004663 if (!isRelational
4664 && ((lType->isBlockPointerType() && rType->isPointerType())
4665 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00004666 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004667 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00004668 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004669 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00004670 ->getPointeeType()->isVoidType())))
4671 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4672 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00004673 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004674 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004675 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00004676 }
Steve Naroff081c7422008-09-04 15:10:53 +00004677
Steve Naroff7cae42b2009-07-10 23:34:53 +00004678 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00004679 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004680 const PointerType *LPT = lType->getAs<PointerType>();
4681 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004682 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00004683 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004684 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00004685 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004686
Steve Naroff753567f2008-11-17 19:49:16 +00004687 if (!LPtrToVoid && !RPtrToVoid &&
4688 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004689 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004690 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00004691 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004692 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004693 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00004694 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004695 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00004696 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004697 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4698 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004699 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004700 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00004701 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00004702 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004703 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00004704 unsigned DiagID = 0;
4705 if (RHSIsNull) {
4706 if (isRelational)
4707 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4708 } else if (isRelational)
4709 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4710 else
4711 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00004712
Chris Lattnerd99bd522009-08-23 00:03:44 +00004713 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00004714 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00004715 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00004716 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004717 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004718 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00004719 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004720 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00004721 unsigned DiagID = 0;
4722 if (LHSIsNull) {
4723 if (isRelational)
4724 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4725 } else if (isRelational)
4726 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4727 else
4728 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00004729
Chris Lattnerd99bd522009-08-23 00:03:44 +00004730 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00004731 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00004732 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00004733 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004734 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004735 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00004736 }
Steve Naroff4b191572008-09-04 16:56:14 +00004737 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00004738 if (!isRelational && RHSIsNull
4739 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004740 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004741 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00004742 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00004743 if (!isRelational && LHSIsNull
4744 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004745 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004746 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00004747 }
Chris Lattner326f7572008-11-18 01:30:42 +00004748 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004749}
4750
Nate Begeman191a6b12008-07-14 18:02:46 +00004751/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00004752/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00004753/// like a scalar comparison, a vector comparison produces a vector of integer
4754/// types.
4755QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00004756 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00004757 bool isRelational) {
4758 // Check to make sure we're operating on vectors of the same type and width,
4759 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00004760 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00004761 if (vType.isNull())
4762 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004763
Nate Begeman191a6b12008-07-14 18:02:46 +00004764 QualType lType = lex->getType();
4765 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004766
Nate Begeman191a6b12008-07-14 18:02:46 +00004767 // For non-floating point types, check for self-comparisons of the form
4768 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4769 // often indicate logic errors in the program.
4770 if (!lType->isFloatingType()) {
4771 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4772 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4773 if (DRL->getDecl() == DRR->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004774 Diag(Loc, diag::warn_selfcomparison);
Nate Begeman191a6b12008-07-14 18:02:46 +00004775 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004776
Nate Begeman191a6b12008-07-14 18:02:46 +00004777 // Check for comparisons of floating point operands using != and ==.
4778 if (!isRelational && lType->isFloatingType()) {
4779 assert (rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00004780 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00004781 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004782
Nate Begeman191a6b12008-07-14 18:02:46 +00004783 // Return the type for the comparison, which is the same as vector type for
4784 // integer vectors, or an integer type of identical size and number of
4785 // elements for floating point vectors.
4786 if (lType->isIntegerType())
4787 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004788
John McCall9dd450b2009-09-21 23:43:11 +00004789 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00004790 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004791 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00004792 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00004793 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004794 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4795
Mike Stump4e1f26a2009-02-19 03:04:26 +00004796 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004797 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00004798 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4799}
4800
Steve Naroff218bc2b2007-05-04 21:54:46 +00004801inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004802 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00004803 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004804 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004805
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004806 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004807
Steve Naroffdbd9e892007-07-17 00:58:39 +00004808 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004809 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004810 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004811}
4812
Steve Naroff218bc2b2007-05-04 21:54:46 +00004813inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump11289f42009-09-09 15:08:12 +00004814 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Steve Naroff31090012007-07-16 21:54:35 +00004815 UsualUnaryConversions(lex);
4816 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004817
Anders Carlsson35a99d92009-10-16 01:44:21 +00004818 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
4819 return InvalidOperands(Loc, lex, rex);
4820
4821 if (Context.getLangOptions().CPlusPlus) {
4822 // C++ [expr.log.and]p2
4823 // C++ [expr.log.or]p2
4824 return Context.BoolTy;
4825 }
4826
4827 return Context.IntTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00004828}
4829
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004830/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4831/// is a read-only property; return true if so. A readonly property expression
4832/// depends on various declarations and thus must be treated specially.
4833///
Mike Stump11289f42009-09-09 15:08:12 +00004834static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004835 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4836 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4837 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4838 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004839 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00004840 BaseType->getAsObjCInterfacePointerType())
4841 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4842 if (S.isPropertyReadonly(PDecl, IFace))
4843 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004844 }
4845 }
4846 return false;
4847}
4848
Chris Lattner30bd3272008-11-18 01:22:49 +00004849/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4850/// emit an error and return true. If so, return false.
4851static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004852 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00004853 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004854 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004855 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4856 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00004857 if (IsLV == Expr::MLV_Valid)
4858 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004859
Chris Lattner30bd3272008-11-18 01:22:49 +00004860 unsigned Diag = 0;
4861 bool NeedType = false;
4862 switch (IsLV) { // C99 6.5.16p2
4863 default: assert(0 && "Unknown result from isModifiableLvalue!");
4864 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004865 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00004866 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4867 NeedType = true;
4868 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004869 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00004870 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4871 NeedType = true;
4872 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00004873 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00004874 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4875 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00004876 case Expr::MLV_InvalidExpression:
Chris Lattner30bd3272008-11-18 01:22:49 +00004877 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4878 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00004879 case Expr::MLV_IncompleteType:
4880 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00004881 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00004882 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4883 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00004884 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00004885 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4886 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00004887 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00004888 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4889 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00004890 case Expr::MLV_ReadonlyProperty:
4891 Diag = diag::error_readonly_property_assignment;
4892 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00004893 case Expr::MLV_NoSetterProperty:
4894 Diag = diag::error_nosetter_property_assignment;
4895 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00004896 }
Steve Naroffad373bd2007-07-31 12:34:36 +00004897
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004898 SourceRange Assign;
4899 if (Loc != OrigLoc)
4900 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00004901 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004902 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00004903 else
Mike Stump11289f42009-09-09 15:08:12 +00004904 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00004905 return true;
4906}
4907
4908
4909
4910// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00004911QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4912 SourceLocation Loc,
4913 QualType CompoundType) {
4914 // Verify that LHS is a modifiable lvalue, and emit error if not.
4915 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00004916 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00004917
4918 QualType LHSType = LHS->getType();
4919 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004920
Chris Lattner9bad62c2008-01-04 18:04:52 +00004921 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00004922 if (CompoundType.isNull()) {
Chris Lattnerea714382008-08-21 18:04:13 +00004923 // Simple assignment "x = y".
Chris Lattner326f7572008-11-18 01:30:42 +00004924 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004925 // Special case of NSObject attributes on c-style pointer types.
4926 if (ConvTy == IncompatiblePointer &&
4927 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00004928 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004929 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00004930 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004931 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004932
Chris Lattnerea714382008-08-21 18:04:13 +00004933 // If the RHS is a unary plus or minus, check to see if they = and + are
4934 // right next to each other. If so, the user may have typo'd "x =+ 4"
4935 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00004936 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00004937 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4938 RHSCheck = ICE->getSubExpr();
4939 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4940 if ((UO->getOpcode() == UnaryOperator::Plus ||
4941 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00004942 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00004943 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00004944 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4945 // And there is a space or other character before the subexpr of the
4946 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00004947 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4948 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00004949 Diag(Loc, diag::warn_not_compound_assign)
4950 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4951 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00004952 }
Chris Lattnerea714382008-08-21 18:04:13 +00004953 }
4954 } else {
4955 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00004956 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00004957 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004958
Chris Lattner326f7572008-11-18 01:30:42 +00004959 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4960 RHS, "assigning"))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004961 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004962
Steve Naroff98cf3e92007-06-06 18:38:38 +00004963 // C99 6.5.16p3: The type of an assignment expression is the type of the
4964 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00004965 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00004966 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4967 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00004968 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00004969 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00004970 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00004971}
4972
Chris Lattner326f7572008-11-18 01:30:42 +00004973// C99 6.5.17
4974QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattnerf6e1e302008-07-25 20:54:07 +00004975 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner326f7572008-11-18 01:30:42 +00004976 DefaultFunctionArrayConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00004977
4978 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4979 // incomplete in C++).
4980
Chris Lattner326f7572008-11-18 01:30:42 +00004981 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00004982}
4983
Steve Naroff7a5af782007-07-13 16:58:59 +00004984/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4985/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00004986QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4987 bool isInc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004988 if (Op->isTypeDependent())
4989 return Context.DependentTy;
4990
Chris Lattner6b0cf142008-11-21 07:05:48 +00004991 QualType ResType = Op->getType();
4992 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00004993
Sebastian Redle10c2c32008-12-20 09:35:34 +00004994 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4995 // Decrement of bool is not allowed.
4996 if (!isInc) {
4997 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4998 return QualType();
4999 }
5000 // Increment of bool sets it to true, but is deprecated.
5001 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5002 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005003 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00005004 } else if (ResType->isAnyPointerType()) {
5005 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005006
Chris Lattner6b0cf142008-11-21 07:05:48 +00005007 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00005008 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005009 if (getLangOptions().CPlusPlus) {
5010 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5011 << Op->getSourceRange();
5012 return QualType();
5013 }
5014
5015 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005016 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005017 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005018 if (getLangOptions().CPlusPlus) {
5019 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5020 << Op->getType() << Op->getSourceRange();
5021 return QualType();
5022 }
5023
5024 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005025 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005026 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00005027 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005028 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005029 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00005030 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00005031 // Diagnose bad cases where we step over interface counts.
5032 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5033 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5034 << PointeeTy << Op->getSourceRange();
5035 return QualType();
5036 }
Chris Lattner6b0cf142008-11-21 07:05:48 +00005037 } else if (ResType->isComplexType()) {
5038 // C99 does not support ++/-- on complex types, we allow as an extension.
5039 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005040 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005041 } else {
5042 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005043 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005044 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00005045 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005046 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00005047 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005048 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00005049 return QualType();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005050 return ResType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005051}
5052
Anders Carlsson806700f2008-02-01 07:15:58 +00005053/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00005054/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005055/// where the declaration is needed for type checking. We only need to
5056/// handle cases when the expression references a function designator
5057/// or is an lvalue. Here are some examples:
5058/// - &(x) => x
5059/// - &*****f => f for f a function designator.
5060/// - &s.xx => s
5061/// - &s.zz[1].yy -> s, if zz is an array
5062/// - *(x + 1) -> x, if x is an array
5063/// - &"123"[2] -> 0
5064/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005065static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005066 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00005067 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005068 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00005069 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005070 // If this is an arrow operator, the address is an offset from
5071 // the base's value, so the object the base refers to is
5072 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005073 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00005074 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00005075 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005076 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00005077 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00005078 // FIXME: This code shouldn't be necessary! We should catch the implicit
5079 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00005080 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5081 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5082 if (ICE->getSubExpr()->getType()->isArrayType())
5083 return getPrimaryDecl(ICE->getSubExpr());
5084 }
5085 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00005086 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005087 case Stmt::UnaryOperatorClass: {
5088 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005089
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005090 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005091 case UnaryOperator::Real:
5092 case UnaryOperator::Imag:
5093 case UnaryOperator::Extension:
5094 return getPrimaryDecl(UO->getSubExpr());
5095 default:
5096 return 0;
5097 }
5098 }
Steve Naroff47500512007-04-19 23:00:49 +00005099 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005100 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00005101 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005102 // If the result of an implicit cast is an l-value, we care about
5103 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005104 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00005105 default:
5106 return 0;
5107 }
5108}
5109
5110/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00005111/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00005112/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005113/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005114/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005115/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00005116/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00005117QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005118 // Make sure to ignore parentheses in subsequent checks
5119 op = op->IgnoreParens();
5120
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00005121 if (op->isTypeDependent())
5122 return Context.DependentTy;
5123
Steve Naroff826e91a2008-01-13 17:10:08 +00005124 if (getLangOptions().C99) {
5125 // Implement C99-only parts of addressof rules.
5126 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5127 if (uOp->getOpcode() == UnaryOperator::Deref)
5128 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5129 // (assuming the deref expression is valid).
5130 return uOp->getSubExpr()->getType();
5131 }
5132 // Technically, there should be a check for array subscript
5133 // expressions here, but the result of one is always an lvalue anyway.
5134 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005135 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00005136 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00005137
Eli Friedmance7f9002009-05-16 23:27:50 +00005138 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5139 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005140 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00005141 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00005142 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00005143 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5144 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005145 return QualType();
5146 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00005147 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005148 // The operand cannot be a bit-field
5149 Diag(OpLoc, diag::err_typecheck_address_of)
5150 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00005151 return QualType();
Nate Begemana6b47a42009-02-15 22:45:20 +00005152 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5153 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman3a1e6922009-04-20 08:23:18 +00005154 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00005155 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00005156 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005157 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00005158 } else if (isa<ObjCPropertyRefExpr>(op)) {
5159 // cannot take address of a property expression.
5160 Diag(OpLoc, diag::err_typecheck_address_of)
5161 << "property expression" << op->getSourceRange();
5162 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00005163 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5164 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00005165 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5166 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005167 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00005168 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00005169 // with the register storage-class specifier.
5170 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00005171 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005172 Diag(OpLoc, diag::err_typecheck_address_of)
5173 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005174 return QualType();
5175 }
Douglas Gregor9b146582009-07-08 20:55:45 +00005176 } else if (isa<OverloadedFunctionDecl>(dcl) ||
5177 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005178 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00005179 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00005180 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005181 // Could be a pointer to member, though, if there is an explicit
5182 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005183 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005184 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00005185 if (Ctx && Ctx->isRecord()) {
5186 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005187 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00005188 diag::err_cannot_form_pointer_to_member_of_reference_type)
5189 << FD->getDeclName() << FD->getType();
5190 return QualType();
5191 }
Mike Stump11289f42009-09-09 15:08:12 +00005192
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005193 return Context.getMemberPointerType(op->getType(),
5194 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00005195 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005196 }
Anders Carlsson5b535762009-05-16 21:43:42 +00005197 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00005198 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005199 // As above.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005200 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5201 MD->isInstance())
Anders Carlsson5b535762009-05-16 21:43:42 +00005202 return Context.getMemberPointerType(op->getType(),
5203 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5204 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00005205 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00005206 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005207
Eli Friedmance7f9002009-05-16 23:27:50 +00005208 if (lval == Expr::LV_IncompleteVoidType) {
5209 // Taking the address of a void variable is technically illegal, but we
5210 // allow it in cases which are otherwise valid.
5211 // Example: "extern void x; void* y = &x;".
5212 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5213 }
5214
Steve Naroff47500512007-04-19 23:00:49 +00005215 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00005216 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00005217}
5218
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005219QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005220 if (Op->isTypeDependent())
5221 return Context.DependentTy;
5222
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005223 UsualUnaryConversions(Op);
5224 QualType Ty = Op->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005225
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005226 // Note that per both C89 and C99, this is always legal, even if ptype is an
5227 // incomplete type or void. It would be possible to warn about dereferencing
5228 // a void pointer, but it's completely well-defined, and such a warning is
5229 // unlikely to catch any mistakes.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005230 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff826e91a2008-01-13 17:10:08 +00005231 return PT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005232
John McCall9dd450b2009-09-21 23:43:11 +00005233 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +00005234 return OPT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005235
Chris Lattner29e812b2008-11-20 06:06:08 +00005236 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005237 << Ty << Op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005238 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +00005239}
Steve Naroff218bc2b2007-05-04 21:54:46 +00005240
5241static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5242 tok::TokenKind Kind) {
5243 BinaryOperator::Opcode Opc;
5244 switch (Kind) {
5245 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00005246 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5247 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005248 case tok::star: Opc = BinaryOperator::Mul; break;
5249 case tok::slash: Opc = BinaryOperator::Div; break;
5250 case tok::percent: Opc = BinaryOperator::Rem; break;
5251 case tok::plus: Opc = BinaryOperator::Add; break;
5252 case tok::minus: Opc = BinaryOperator::Sub; break;
5253 case tok::lessless: Opc = BinaryOperator::Shl; break;
5254 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5255 case tok::lessequal: Opc = BinaryOperator::LE; break;
5256 case tok::less: Opc = BinaryOperator::LT; break;
5257 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5258 case tok::greater: Opc = BinaryOperator::GT; break;
5259 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5260 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5261 case tok::amp: Opc = BinaryOperator::And; break;
5262 case tok::caret: Opc = BinaryOperator::Xor; break;
5263 case tok::pipe: Opc = BinaryOperator::Or; break;
5264 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5265 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5266 case tok::equal: Opc = BinaryOperator::Assign; break;
5267 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5268 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5269 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5270 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5271 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5272 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5273 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5274 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5275 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5276 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5277 case tok::comma: Opc = BinaryOperator::Comma; break;
5278 }
5279 return Opc;
5280}
5281
Steve Naroff35d85152007-05-07 00:24:15 +00005282static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5283 tok::TokenKind Kind) {
5284 UnaryOperator::Opcode Opc;
5285 switch (Kind) {
5286 default: assert(0 && "Unknown unary op!");
5287 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5288 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5289 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5290 case tok::star: Opc = UnaryOperator::Deref; break;
5291 case tok::plus: Opc = UnaryOperator::Plus; break;
5292 case tok::minus: Opc = UnaryOperator::Minus; break;
5293 case tok::tilde: Opc = UnaryOperator::Not; break;
5294 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005295 case tok::kw___real: Opc = UnaryOperator::Real; break;
5296 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00005297 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005298 }
5299 return Opc;
5300}
5301
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005302/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5303/// operator @p Opc at location @c TokLoc. This routine only supports
5304/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005305Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5306 unsigned Op,
5307 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005308 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005309 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005310 // The following two variables are used for compound assignment operators
5311 QualType CompLHSTy; // Type of LHS after promotions for computation
5312 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005313
5314 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005315 case BinaryOperator::Assign:
5316 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5317 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00005318 case BinaryOperator::PtrMemD:
5319 case BinaryOperator::PtrMemI:
5320 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5321 Opc == BinaryOperator::PtrMemI);
5322 break;
5323 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005324 case BinaryOperator::Div:
5325 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5326 break;
5327 case BinaryOperator::Rem:
5328 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5329 break;
5330 case BinaryOperator::Add:
5331 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5332 break;
5333 case BinaryOperator::Sub:
5334 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5335 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00005336 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005337 case BinaryOperator::Shr:
5338 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5339 break;
5340 case BinaryOperator::LE:
5341 case BinaryOperator::LT:
5342 case BinaryOperator::GE:
5343 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005344 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005345 break;
5346 case BinaryOperator::EQ:
5347 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005348 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005349 break;
5350 case BinaryOperator::And:
5351 case BinaryOperator::Xor:
5352 case BinaryOperator::Or:
5353 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5354 break;
5355 case BinaryOperator::LAnd:
5356 case BinaryOperator::LOr:
5357 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5358 break;
5359 case BinaryOperator::MulAssign:
5360 case BinaryOperator::DivAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005361 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5362 CompLHSTy = CompResultTy;
5363 if (!CompResultTy.isNull())
5364 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005365 break;
5366 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005367 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5368 CompLHSTy = CompResultTy;
5369 if (!CompResultTy.isNull())
5370 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005371 break;
5372 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005373 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5374 if (!CompResultTy.isNull())
5375 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005376 break;
5377 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005378 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5379 if (!CompResultTy.isNull())
5380 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005381 break;
5382 case BinaryOperator::ShlAssign:
5383 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005384 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5385 CompLHSTy = CompResultTy;
5386 if (!CompResultTy.isNull())
5387 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005388 break;
5389 case BinaryOperator::AndAssign:
5390 case BinaryOperator::XorAssign:
5391 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005392 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5393 CompLHSTy = CompResultTy;
5394 if (!CompResultTy.isNull())
5395 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005396 break;
5397 case BinaryOperator::Comma:
5398 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5399 break;
5400 }
5401 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005402 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005403 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00005404 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5405 else
5406 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005407 CompLHSTy, CompResultTy,
5408 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005409}
5410
Steve Naroff218bc2b2007-05-04 21:54:46 +00005411// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005412Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5413 tok::TokenKind Kind,
5414 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00005415 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00005416 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00005417
Steve Naroff83895f72007-09-16 03:34:24 +00005418 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5419 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00005420
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005421 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00005422 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005423 rhs->getType()->isOverloadableType())) {
5424 // Find all of the overloaded operators visible from this
5425 // point. We perform both an operator-name lookup from the local
5426 // scope and an argument-dependent lookup based on the types of
5427 // the arguments.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005428 FunctionSet Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005429 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5430 if (OverOp != OO_None) {
5431 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5432 Functions);
5433 Expr *Args[2] = { lhs, rhs };
Mike Stump11289f42009-09-09 15:08:12 +00005434 DeclarationName OpName
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005435 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00005436 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregora11693b2008-11-12 17:17:38 +00005437 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005438
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005439 // Build the (potentially-overloaded, potentially-dependent)
5440 // binary operation.
5441 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00005442 }
5443
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005444 // Build a built-in binary operation.
5445 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005446}
5447
Douglas Gregor084d8552009-03-13 23:49:33 +00005448Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005449 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00005450 ExprArg InputArg) {
5451 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00005452
Mike Stump87c57ac2009-05-16 07:39:55 +00005453 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00005454 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00005455 QualType resultType;
5456 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005457 case UnaryOperator::OffsetOf:
5458 assert(false && "Invalid unary operator");
5459 break;
5460
Steve Naroff35d85152007-05-07 00:24:15 +00005461 case UnaryOperator::PreInc:
5462 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00005463 case UnaryOperator::PostInc:
5464 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00005465 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00005466 Opc == UnaryOperator::PreInc ||
5467 Opc == UnaryOperator::PostInc);
Steve Naroff35d85152007-05-07 00:24:15 +00005468 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005469 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00005470 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00005471 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005472 case UnaryOperator::Deref:
Steve Naroffb7235642007-12-18 04:06:57 +00005473 DefaultFunctionArrayConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00005474 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00005475 break;
5476 case UnaryOperator::Plus:
5477 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00005478 UsualUnaryConversions(Input);
5479 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005480 if (resultType->isDependentType())
5481 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005482 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5483 break;
5484 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5485 resultType->isEnumeralType())
5486 break;
5487 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5488 Opc == UnaryOperator::Plus &&
5489 resultType->isPointerType())
5490 break;
5491
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005492 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5493 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00005494 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00005495 UsualUnaryConversions(Input);
5496 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005497 if (resultType->isDependentType())
5498 break;
Chris Lattner0d707612008-07-25 23:52:49 +00005499 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5500 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5501 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00005502 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005503 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00005504 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005505 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5506 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00005507 break;
5508 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00005509 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroff31090012007-07-16 21:54:35 +00005510 DefaultFunctionArrayConversion(Input);
5511 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005512 if (resultType->isDependentType())
5513 break;
Steve Naroff35d85152007-05-07 00:24:15 +00005514 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005515 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5516 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00005517 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005518 // In C++, it's bool. C++ 5.3.1p8
5519 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00005520 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00005521 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00005522 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00005523 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00005524 break;
Chris Lattner86554282007-06-08 22:32:33 +00005525 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00005526 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00005527 break;
Steve Naroff35d85152007-05-07 00:24:15 +00005528 }
5529 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005530 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00005531
5532 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00005533 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00005534}
Chris Lattnereefa10e2007-05-28 06:56:27 +00005535
Douglas Gregor084d8552009-03-13 23:49:33 +00005536// Unary Operators. 'Tok' is the token for the operator.
5537Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5538 tok::TokenKind Op, ExprArg input) {
5539 Expr *Input = (Expr*)input.get();
5540 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5541
5542 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5543 // Find all of the overloaded operators visible from this
5544 // point. We perform both an operator-name lookup from the local
5545 // scope and an argument-dependent lookup based on the types of
5546 // the arguments.
5547 FunctionSet Functions;
5548 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5549 if (OverOp != OO_None) {
5550 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5551 Functions);
Mike Stump11289f42009-09-09 15:08:12 +00005552 DeclarationName OpName
Douglas Gregor084d8552009-03-13 23:49:33 +00005553 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00005554 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregor084d8552009-03-13 23:49:33 +00005555 }
5556
5557 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5558 }
5559
5560 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5561}
5562
Steve Naroff66356bd2007-09-16 14:56:35 +00005563/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005564Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5565 SourceLocation LabLoc,
5566 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00005567 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00005568 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00005569
Daniel Dunbar88402ce2008-08-04 16:51:22 +00005570 // If we haven't seen this label yet, create a forward reference. It
5571 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00005572 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00005573 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005574
Chris Lattnereefa10e2007-05-28 06:56:27 +00005575 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005576 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5577 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00005578}
5579
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005580Sema::OwningExprResult
5581Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5582 SourceLocation RPLoc) { // "({..})"
5583 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00005584 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5585 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5586
Eli Friedman52cc0162009-01-24 23:09:00 +00005587 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattnera69b0762009-04-25 19:11:05 +00005588 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005589 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00005590
Chris Lattner366727f2007-07-24 16:58:17 +00005591 // FIXME: there are a variety of strange constraints to enforce here, for
5592 // example, it is not possible to goto into a stmt expression apparently.
5593 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005594
Chris Lattner366727f2007-07-24 16:58:17 +00005595 // If there are sub stmts in the compound stmt, take the type of the last one
5596 // as the type of the stmtexpr.
5597 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005598
Chris Lattner944d3062008-07-26 19:51:01 +00005599 if (!Compound->body_empty()) {
5600 Stmt *LastStmt = Compound->body_back();
5601 // If LastStmt is a label, skip down through into the body.
5602 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5603 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005604
Chris Lattner944d3062008-07-26 19:51:01 +00005605 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00005606 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00005607 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005608
Eli Friedmanba961a92009-03-23 00:24:07 +00005609 // FIXME: Check that expression type is complete/non-abstract; statement
5610 // expressions are not lvalues.
5611
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005612 substmt.release();
5613 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00005614}
Steve Naroff78864672007-08-01 22:05:33 +00005615
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005616Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5617 SourceLocation BuiltinLoc,
5618 SourceLocation TypeLoc,
5619 TypeTy *argty,
5620 OffsetOfComponent *CompPtr,
5621 unsigned NumComponents,
5622 SourceLocation RPLoc) {
5623 // FIXME: This function leaks all expressions in the offset components on
5624 // error.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005625 // FIXME: Preserve type source info.
5626 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattnerf17bd422007-08-30 17:45:32 +00005627 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005628
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005629 bool Dependent = ArgTy->isDependentType();
5630
Chris Lattnerf17bd422007-08-30 17:45:32 +00005631 // We must have at least one component that refers to the type, and the first
5632 // one is known to be a field designator. Verify that the ArgTy represents
5633 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005634 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005635 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005636
Eli Friedmanba961a92009-03-23 00:24:07 +00005637 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5638 // with an incomplete type would be illegal.
Douglas Gregor26897462009-03-11 16:48:53 +00005639
Eli Friedman988a16b2009-02-27 06:44:11 +00005640 // Otherwise, create a null pointer as the base, and iteratively process
5641 // the offsetof designators.
5642 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5643 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005644 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman988a16b2009-02-27 06:44:11 +00005645 ArgTy, SourceLocation());
Eli Friedman16c88df2009-01-26 01:33:06 +00005646
Chris Lattner78502cf2007-08-31 21:49:13 +00005647 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5648 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00005649 // FIXME: This diagnostic isn't actually visible because the location is in
5650 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00005651 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00005652 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5653 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005654
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005655 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00005656 bool DidWarnAboutNonPOD = false;
Mike Stump11289f42009-09-09 15:08:12 +00005657
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005658 // FIXME: Dependent case loses a lot of information here. And probably
5659 // leaks like a sieve.
5660 for (unsigned i = 0; i != NumComponents; ++i) {
5661 const OffsetOfComponent &OC = CompPtr[i];
5662 if (OC.isBrackets) {
5663 // Offset of an array sub-field. TODO: Should we allow vector elements?
5664 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5665 if (!AT) {
5666 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005667 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5668 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005669 }
5670
5671 // FIXME: C++: Verify that operator[] isn't overloaded.
5672
Eli Friedman988a16b2009-02-27 06:44:11 +00005673 // Promote the array so it looks more like a normal array subscript
5674 // expression.
5675 DefaultFunctionArrayConversion(Res);
5676
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005677 // C99 6.5.2.1p1
5678 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005679 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005680 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005681 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00005682 diag::err_typecheck_subscript_not_integer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005683 << Idx->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005684
5685 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5686 OC.LocEnd);
5687 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00005688 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005689
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005690 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005691 if (!RC) {
5692 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005693 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5694 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005695 }
Chris Lattner98dbf0a2007-08-30 17:59:59 +00005696
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005697 // Get the decl corresponding to this.
5698 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00005699 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00005700 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlsson8b98d022009-05-02 17:45:47 +00005701 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5702 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5703 << Res->getType());
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00005704 DidWarnAboutNonPOD = true;
5705 }
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00005706 }
Mike Stump11289f42009-09-09 15:08:12 +00005707
John McCall9f3059a2009-10-09 21:13:30 +00005708 LookupResult R;
5709 LookupQualifiedName(R, RD, OC.U.IdentInfo, LookupMemberName);
5710
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005711 FieldDecl *MemberDecl
John McCall9f3059a2009-10-09 21:13:30 +00005712 = dyn_cast_or_null<FieldDecl>(R.getAsSingleDecl(Context));
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005713 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005714 if (!MemberDecl)
Douglas Gregore40876a2009-10-13 21:16:44 +00005715 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
5716 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump4e1f26a2009-02-19 03:04:26 +00005717
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005718 // FIXME: C++: Verify that MemberDecl isn't a static field.
5719 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00005720 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00005721 Res = BuildAnonymousStructUnionMemberReference(
5722 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00005723 } else {
5724 // MemberDecl->getType() doesn't get the right qualifiers, but it
5725 // doesn't matter here.
5726 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5727 MemberDecl->getType().getNonReferenceType());
5728 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005729 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00005730 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005731
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005732 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5733 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00005734}
5735
5736
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005737Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5738 TypeTy *arg1,TypeTy *arg2,
5739 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005740 // FIXME: Preserve type source info.
5741 QualType argT1 = GetTypeFromParser(arg1);
5742 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005743
Steve Naroff78864672007-08-01 22:05:33 +00005744 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005745
Douglas Gregorf907cbf2009-05-19 22:28:02 +00005746 if (getLangOptions().CPlusPlus) {
5747 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5748 << SourceRange(BuiltinLoc, RPLoc);
5749 return ExprError();
5750 }
5751
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005752 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5753 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00005754}
5755
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005756Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5757 ExprArg cond,
5758 ExprArg expr1, ExprArg expr2,
5759 SourceLocation RPLoc) {
5760 Expr *CondExpr = static_cast<Expr*>(cond.get());
5761 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5762 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005763
Steve Naroff9efdabc2007-08-03 21:21:27 +00005764 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5765
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005766 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00005767 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00005768 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005769 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00005770 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005771 } else {
5772 // The conditional expression is required to be a constant expression.
5773 llvm::APSInt condEval(32);
5774 SourceLocation ExpLoc;
5775 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005776 return ExprError(Diag(ExpLoc,
5777 diag::err_typecheck_choose_expr_requires_constant)
5778 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00005779
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005780 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5781 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00005782 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
5783 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005784 }
5785
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005786 cond.release(); expr1.release(); expr2.release();
5787 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00005788 resType, RPLoc,
5789 resType->isDependentType(),
5790 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00005791}
5792
Steve Naroffc540d662008-09-03 18:15:37 +00005793//===----------------------------------------------------------------------===//
5794// Clang Extensions.
5795//===----------------------------------------------------------------------===//
5796
5797/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005798void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00005799 // Analyze block parameters.
5800 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005801
Steve Naroffc540d662008-09-03 18:15:37 +00005802 // Add BSI to CurBlock.
5803 BSI->PrevBlockInfo = CurBlock;
5804 CurBlock = BSI;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005805
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00005806 BSI->ReturnType = QualType();
Steve Naroffc540d662008-09-03 18:15:37 +00005807 BSI->TheScope = BlockScope;
Mike Stumpa6703322009-02-19 22:01:56 +00005808 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarb9a68612009-07-29 01:59:17 +00005809 BSI->hasPrototype = false;
Chris Lattner45542ea2009-04-19 05:28:12 +00005810 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5811 CurFunctionNeedsScopeChecking = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005812
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005813 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00005814 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005815}
5816
Mike Stump82f071f2009-02-04 22:31:32 +00005817void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00005818 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump82f071f2009-02-04 22:31:32 +00005819
5820 if (ParamInfo.getNumTypeObjects() == 0
5821 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor758a8692009-06-17 21:51:59 +00005822 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump82f071f2009-02-04 22:31:32 +00005823 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5824
Mike Stumpd456c482009-04-28 01:10:27 +00005825 if (T->isArrayType()) {
5826 Diag(ParamInfo.getSourceRange().getBegin(),
5827 diag::err_block_returns_array);
5828 return;
5829 }
5830
Mike Stump82f071f2009-02-04 22:31:32 +00005831 // The parameter list is optional, if there was none, assume ().
5832 if (!T->isFunctionType())
5833 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5834
5835 CurBlock->hasPrototype = true;
5836 CurBlock->isVariadic = false;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00005837 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005838 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00005839 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00005840 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00005841 // FIXME: remove the attribute.
5842 }
John McCall9dd450b2009-09-21 23:43:11 +00005843 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00005844
Chris Lattner6de05082009-04-11 19:27:54 +00005845 // Do not allow returning a objc interface by-value.
5846 if (RetTy->isObjCInterfaceType()) {
5847 Diag(ParamInfo.getSourceRange().getBegin(),
5848 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5849 return;
5850 }
Mike Stump82f071f2009-02-04 22:31:32 +00005851 return;
5852 }
5853
Steve Naroffc540d662008-09-03 18:15:37 +00005854 // Analyze arguments to block.
5855 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5856 "Not a function declarator!");
5857 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005858
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005859 CurBlock->hasPrototype = FTI.hasPrototype;
5860 CurBlock->isVariadic = true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005861
Steve Naroffc540d662008-09-03 18:15:37 +00005862 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5863 // no arguments, not a function that takes a single void argument.
5864 if (FTI.hasPrototype &&
5865 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner83f095c2009-03-28 19:18:32 +00005866 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5867 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00005868 // empty arg list, don't push any params.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005869 CurBlock->isVariadic = false;
Steve Naroffc540d662008-09-03 18:15:37 +00005870 } else if (FTI.hasPrototype) {
5871 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner83f095c2009-03-28 19:18:32 +00005872 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005873 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroffc540d662008-09-03 18:15:37 +00005874 }
Jay Foad7d0479f2009-05-21 09:52:38 +00005875 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner6de05082009-04-11 19:27:54 +00005876 CurBlock->Params.size());
Fariborz Jahanian960910a2009-05-19 17:08:59 +00005877 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor758a8692009-06-17 21:51:59 +00005878 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005879 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5880 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5881 // If this has an identifier, add it to the scope stack.
5882 if ((*AI)->getIdentifier())
5883 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner6de05082009-04-11 19:27:54 +00005884
Fariborz Jahanian6607b212009-05-14 20:53:39 +00005885 // Check for a valid sentinel attribute on this block.
Mike Stump11289f42009-09-09 15:08:12 +00005886 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005887 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00005888 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00005889 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00005890 // FIXME: remove the attribute.
5891 }
Mike Stump11289f42009-09-09 15:08:12 +00005892
Chris Lattner6de05082009-04-11 19:27:54 +00005893 // Analyze the return type.
5894 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall9dd450b2009-09-21 23:43:11 +00005895 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00005896
Chris Lattner6de05082009-04-11 19:27:54 +00005897 // Do not allow returning a objc interface by-value.
5898 if (RetTy->isObjCInterfaceType()) {
5899 Diag(ParamInfo.getSourceRange().getBegin(),
5900 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5901 } else if (!RetTy->isDependentType())
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00005902 CurBlock->ReturnType = RetTy;
Steve Naroffc540d662008-09-03 18:15:37 +00005903}
5904
5905/// ActOnBlockError - If there is an error parsing a block, this callback
5906/// is invoked to pop the information about the block from the action impl.
5907void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5908 // Ensure that CurBlock is deleted.
5909 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005910
Chris Lattner45542ea2009-04-19 05:28:12 +00005911 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5912
Steve Naroffc540d662008-09-03 18:15:37 +00005913 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00005914 PopDeclContext();
Steve Naroffc540d662008-09-03 18:15:37 +00005915 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroffc540d662008-09-03 18:15:37 +00005916 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00005917}
5918
5919/// ActOnBlockStmtExpr - This is called when the body of a block statement
5920/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005921Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5922 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00005923 // If blocks are disabled, emit an error.
5924 if (!LangOpts.Blocks)
5925 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00005926
Steve Naroffc540d662008-09-03 18:15:37 +00005927 // Ensure that CurBlock is deleted.
5928 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroffc540d662008-09-03 18:15:37 +00005929
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005930 PopDeclContext();
5931
Steve Naroffc540d662008-09-03 18:15:37 +00005932 // Pop off CurBlock, handle nested blocks.
5933 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005934
Steve Naroffc540d662008-09-03 18:15:37 +00005935 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00005936 if (!BSI->ReturnType.isNull())
5937 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005938
Steve Naroffc540d662008-09-03 18:15:37 +00005939 llvm::SmallVector<QualType, 8> ArgTypes;
5940 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5941 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005942
Mike Stump3bf1ab42009-07-28 22:04:01 +00005943 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00005944 QualType BlockTy;
5945 if (!BSI->hasPrototype)
Mike Stump3bf1ab42009-07-28 22:04:01 +00005946 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5947 NoReturn);
Steve Naroffc540d662008-09-03 18:15:37 +00005948 else
Jay Foad7d0479f2009-05-21 09:52:38 +00005949 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump3bf1ab42009-07-28 22:04:01 +00005950 BSI->isVariadic, 0, false, false, 0, 0,
5951 NoReturn);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005952
Eli Friedmanba961a92009-03-23 00:24:07 +00005953 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005954 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroffc540d662008-09-03 18:15:37 +00005955 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005956
Chris Lattner45542ea2009-04-19 05:28:12 +00005957 // If needed, diagnose invalid gotos and switches in the block.
5958 if (CurFunctionNeedsScopeChecking)
5959 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5960 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump11289f42009-09-09 15:08:12 +00005961
Anders Carlssonb781bcd2009-05-01 19:49:17 +00005962 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump3bf1ab42009-07-28 22:04:01 +00005963 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005964 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5965 BSI->hasBlockDeclRefExprs));
Steve Naroffc540d662008-09-03 18:15:37 +00005966}
5967
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005968Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5969 ExprArg expr, TypeTy *type,
5970 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005971 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00005972 Expr *E = static_cast<Expr*>(expr.get());
5973 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00005974
Anders Carlsson7e13ab82007-10-15 20:28:48 +00005975 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00005976
5977 // Get the va_list type
5978 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00005979 if (VaListType->isArrayType()) {
5980 // Deal with implicit array decay; for example, on x86-64,
5981 // va_list is an array, but it's supposed to decay to
5982 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00005983 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00005984 // Make sure the input expression also decays appropriately.
5985 UsualUnaryConversions(E);
5986 } else {
5987 // Otherwise, the va_list argument must be an l-value because
5988 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00005989 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00005990 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00005991 return ExprError();
5992 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00005993
Douglas Gregorad3150c2009-05-19 23:10:31 +00005994 if (!E->isTypeDependent() &&
5995 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005996 return ExprError(Diag(E->getLocStart(),
5997 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00005998 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00005999 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006000
Eli Friedmanba961a92009-03-23 00:24:07 +00006001 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006002 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006003
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006004 expr.release();
6005 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6006 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006007}
6008
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006009Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00006010 // The type of __null will be int or long, depending on the size of
6011 // pointers on the target.
6012 QualType Ty;
6013 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6014 Ty = Context.IntTy;
6015 else
6016 Ty = Context.LongTy;
6017
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006018 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00006019}
6020
Chris Lattner9bad62c2008-01-04 18:04:52 +00006021bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6022 SourceLocation Loc,
6023 QualType DstType, QualType SrcType,
6024 Expr *SrcExpr, const char *Flavor) {
6025 // Decode the result (notice that AST's are still created for extensions).
6026 bool isInvalid = false;
6027 unsigned DiagKind;
6028 switch (ConvTy) {
6029 default: assert(0 && "Unknown conversion type");
6030 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006031 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00006032 DiagKind = diag::ext_typecheck_convert_pointer_int;
6033 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006034 case IntToPointer:
6035 DiagKind = diag::ext_typecheck_convert_int_pointer;
6036 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006037 case IncompatiblePointer:
6038 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6039 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00006040 case IncompatiblePointerSign:
6041 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6042 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006043 case FunctionVoidPointer:
6044 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6045 break;
6046 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00006047 // If the qualifiers lost were because we were applying the
6048 // (deprecated) C++ conversion from a string literal to a char*
6049 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6050 // Ideally, this check would be performed in
6051 // CheckPointerTypesForAssignment. However, that would require a
6052 // bit of refactoring (so that the second argument is an
6053 // expression, rather than a type), which should be done as part
6054 // of a larger effort to fix CheckPointerTypesForAssignment for
6055 // C++ semantics.
6056 if (getLangOptions().CPlusPlus &&
6057 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6058 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006059 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6060 break;
Steve Naroff081c7422008-09-04 15:10:53 +00006061 case IntToBlockPointer:
6062 DiagKind = diag::err_int_to_block_pointer;
6063 break;
6064 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00006065 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00006066 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00006067 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00006068 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00006069 // it can give a more specific diagnostic.
6070 DiagKind = diag::warn_incompatible_qualified_id;
6071 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006072 case IncompatibleVectors:
6073 DiagKind = diag::warn_incompatible_vectors;
6074 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006075 case Incompatible:
6076 DiagKind = diag::err_typecheck_convert_incompatible;
6077 isInvalid = true;
6078 break;
6079 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006080
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006081 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
6082 << SrcExpr->getSourceRange();
Chris Lattner9bad62c2008-01-04 18:04:52 +00006083 return isInvalid;
6084}
Anders Carlssone54e8a12008-11-30 19:50:32 +00006085
Chris Lattnerc71d08b2009-04-25 21:59:05 +00006086bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006087 llvm::APSInt ICEResult;
6088 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6089 if (Result)
6090 *Result = ICEResult;
6091 return false;
6092 }
6093
Anders Carlssone54e8a12008-11-30 19:50:32 +00006094 Expr::EvalResult EvalResult;
6095
Mike Stump4e1f26a2009-02-19 03:04:26 +00006096 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00006097 EvalResult.HasSideEffects) {
6098 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6099
6100 if (EvalResult.Diag) {
6101 // We only show the note if it's not the usual "invalid subexpression"
6102 // or if it's actually in a subexpression.
6103 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6104 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6105 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6106 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006107
Anders Carlssone54e8a12008-11-30 19:50:32 +00006108 return true;
6109 }
6110
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006111 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6112 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00006113
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006114 if (EvalResult.Diag &&
6115 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6116 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006117
Anders Carlssone54e8a12008-11-30 19:50:32 +00006118 if (Result)
6119 *Result = EvalResult.Val.getInt();
6120 return false;
6121}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006122
Mike Stump11289f42009-09-09 15:08:12 +00006123Sema::ExpressionEvaluationContext
6124Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006125 // Introduce a new set of potentially referenced declarations to the stack.
6126 if (NewContext == PotentiallyPotentiallyEvaluated)
6127 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
Mike Stump11289f42009-09-09 15:08:12 +00006128
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006129 std::swap(ExprEvalContext, NewContext);
6130 return NewContext;
6131}
6132
Mike Stump11289f42009-09-09 15:08:12 +00006133void
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006134Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6135 ExpressionEvaluationContext NewContext) {
6136 ExprEvalContext = NewContext;
6137
6138 if (OldContext == PotentiallyPotentiallyEvaluated) {
6139 // Mark any remaining declarations in the current position of the stack
6140 // as "referenced". If they were not meant to be referenced, semantic
6141 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6142 PotentiallyReferencedDecls RemainingDecls;
6143 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6144 PotentiallyReferencedDeclStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00006145
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006146 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6147 IEnd = RemainingDecls.end();
6148 I != IEnd; ++I)
6149 MarkDeclarationReferenced(I->first, I->second);
6150 }
6151}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006152
6153/// \brief Note that the given declaration was referenced in the source code.
6154///
6155/// This routine should be invoke whenever a given declaration is referenced
6156/// in the source code, and where that reference occurred. If this declaration
6157/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6158/// C99 6.9p3), then the declaration will be marked as used.
6159///
6160/// \param Loc the location where the declaration was referenced.
6161///
6162/// \param D the declaration that has been referenced by the source code.
6163void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6164 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00006165
Douglas Gregor77b50e12009-06-22 23:06:13 +00006166 if (D->isUsed())
6167 return;
Mike Stump11289f42009-09-09 15:08:12 +00006168
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00006169 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6170 // template or not. The reason for this is that unevaluated expressions
6171 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6172 // -Wunused-parameters)
6173 if (isa<ParmVarDecl>(D) ||
6174 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006175 D->setUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00006176
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006177 // Do not mark anything as "used" within a dependent context; wait for
6178 // an instantiation.
6179 if (CurContext->isDependentContext())
6180 return;
Mike Stump11289f42009-09-09 15:08:12 +00006181
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006182 switch (ExprEvalContext) {
6183 case Unevaluated:
6184 // We are in an expression that is not potentially evaluated; do nothing.
6185 return;
Mike Stump11289f42009-09-09 15:08:12 +00006186
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006187 case PotentiallyEvaluated:
6188 // We are in a potentially-evaluated expression, so this declaration is
6189 // "used"; handle this below.
6190 break;
Mike Stump11289f42009-09-09 15:08:12 +00006191
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006192 case PotentiallyPotentiallyEvaluated:
6193 // We are in an expression that may be potentially evaluated; queue this
6194 // declaration reference until we know whether the expression is
6195 // potentially evaluated.
6196 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6197 return;
6198 }
Mike Stump11289f42009-09-09 15:08:12 +00006199
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006200 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00006201 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006202 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00006203 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6204 if (!Constructor->isUsed())
6205 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00006206 } else if (Constructor->isImplicit() &&
Mike Stump12b8ce12009-08-04 21:02:39 +00006207 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006208 if (!Constructor->isUsed())
6209 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6210 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006211 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6212 if (Destructor->isImplicit() && !Destructor->isUsed())
6213 DefineImplicitDestructor(Loc, Destructor);
Mike Stump11289f42009-09-09 15:08:12 +00006214
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006215 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6216 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6217 MethodDecl->getOverloadedOperator() == OO_Equal) {
6218 if (!MethodDecl->isUsed())
6219 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6220 }
6221 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00006222 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00006223 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00006224 // class templates.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006225 if (!Function->getBody() &&
6226 Function->getTemplateSpecializationKind()
6227 == TSK_ImplicitInstantiation) {
6228 bool AlreadyInstantiated = false;
6229 if (FunctionTemplateSpecializationInfo *SpecInfo
6230 = Function->getTemplateSpecializationInfo()) {
6231 if (SpecInfo->getPointOfInstantiation().isInvalid())
6232 SpecInfo->setPointOfInstantiation(Loc);
6233 else
6234 AlreadyInstantiated = true;
6235 } else if (MemberSpecializationInfo *MSInfo
6236 = Function->getMemberSpecializationInfo()) {
6237 if (MSInfo->getPointOfInstantiation().isInvalid())
6238 MSInfo->setPointOfInstantiation(Loc);
6239 else
6240 AlreadyInstantiated = true;
6241 }
6242
6243 if (!AlreadyInstantiated)
6244 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6245 }
6246
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006247 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006248 Function->setUsed(true);
6249 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00006250 }
Mike Stump11289f42009-09-09 15:08:12 +00006251
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006252 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006253 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00006254 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00006255 Var->getInstantiatedFromStaticDataMember()) {
6256 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6257 assert(MSInfo && "Missing member specialization information?");
6258 if (MSInfo->getPointOfInstantiation().isInvalid() &&
6259 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6260 MSInfo->setPointOfInstantiation(Loc);
6261 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6262 }
6263 }
Mike Stump11289f42009-09-09 15:08:12 +00006264
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006265 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006266
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006267 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006268 return;
Sam Weinigbae69142009-09-11 03:29:30 +00006269 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006270}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00006271
6272bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
6273 CallExpr *CE, FunctionDecl *FD) {
6274 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
6275 return false;
6276
6277 PartialDiagnostic Note =
6278 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
6279 << FD->getDeclName() : PDiag();
6280 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
6281
6282 if (RequireCompleteType(Loc, ReturnType,
6283 FD ?
6284 PDiag(diag::err_call_function_incomplete_return)
6285 << CE->getSourceRange() << FD->getDeclName() :
6286 PDiag(diag::err_call_incomplete_return)
6287 << CE->getSourceRange(),
6288 std::make_pair(NoteLoc, Note)))
6289 return true;
6290
6291 return false;
6292}
6293
John McCalld5707ab2009-10-12 21:59:07 +00006294// Diagnose the common s/=/==/ typo. Note that adding parentheses
6295// will prevent this condition from triggering, which is what we want.
6296void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
6297 SourceLocation Loc;
6298
6299 if (isa<BinaryOperator>(E)) {
6300 BinaryOperator *Op = cast<BinaryOperator>(E);
6301 if (Op->getOpcode() != BinaryOperator::Assign)
6302 return;
6303
6304 Loc = Op->getOperatorLoc();
6305 } else if (isa<CXXOperatorCallExpr>(E)) {
6306 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
6307 if (Op->getOperator() != OO_Equal)
6308 return;
6309
6310 Loc = Op->getOperatorLoc();
6311 } else {
6312 // Not an assignment.
6313 return;
6314 }
6315
John McCalld5707ab2009-10-12 21:59:07 +00006316 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00006317 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCalld5707ab2009-10-12 21:59:07 +00006318
6319 Diag(Loc, diag::warn_condition_is_assignment)
6320 << E->getSourceRange()
6321 << CodeModificationHint::CreateInsertion(Open, "(")
6322 << CodeModificationHint::CreateInsertion(Close, ")");
6323}
6324
6325bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
6326 DiagnoseAssignmentAsCondition(E);
6327
6328 if (!E->isTypeDependent()) {
6329 DefaultFunctionArrayConversion(E);
6330
6331 QualType T = E->getType();
6332
6333 if (getLangOptions().CPlusPlus) {
6334 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
6335 return true;
6336 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
6337 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
6338 << T << E->getSourceRange();
6339 return true;
6340 }
6341 }
6342
6343 return false;
6344}