blob: 490c73896ed13a81d1db21a63039fb39e3c32ae9 [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
2925 // Update Fn to refer to the actual function selected.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002926 // FIXME: Use FixOverloadedFunctionReference?
2927 Expr *NewFn = DeclRefExpr::Create(Context, Qualifier, QualifierRange, FDecl,
2928 Fn->getLocStart(), FDecl->getType(), false,
2929 false);
Douglas Gregore254f902009-02-04 00:32:51 +00002930 Fn->Destroy(Context);
2931 Fn = NewFn;
2932 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002933 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002934
2935 // Promote the function operand.
2936 UsualUnaryConversions(Fn);
2937
Chris Lattner08464942007-12-28 05:29:59 +00002938 // Make the call expr early, before semantic checks. This guarantees cleanup
2939 // of arguments and function on error.
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002940 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2941 Args, NumArgs,
2942 Context.BoolTy,
2943 RParenLoc));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002944
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002945 const FunctionType *FuncT;
2946 if (!Fn->getType()->isBlockPointerType()) {
2947 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2948 // have type pointer to function".
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002949 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002950 if (PT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002951 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2952 << Fn->getType() << Fn->getSourceRange());
John McCall9dd450b2009-09-21 23:43:11 +00002953 FuncT = PT->getPointeeType()->getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002954 } else { // This is a block call.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002955 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
John McCall9dd450b2009-09-21 23:43:11 +00002956 getAs<FunctionType>();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002957 }
Chris Lattner08464942007-12-28 05:29:59 +00002958 if (FuncT == 0)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002959 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2960 << Fn->getType() << Fn->getSourceRange());
2961
Eli Friedman3164fb12009-03-22 22:00:50 +00002962 // Check for a valid return type
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002963 if (CheckCallReturnType(FuncT->getResultType(),
2964 Fn->getSourceRange().getBegin(), TheCall.get(),
2965 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00002966 return ExprError();
2967
Chris Lattner08464942007-12-28 05:29:59 +00002968 // We know the result type of the call, set it.
Douglas Gregor786ab212008-10-29 02:00:59 +00002969 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002970
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002971 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00002972 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002973 RParenLoc))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002974 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00002975 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002976 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002977
Douglas Gregord8e97de2009-04-02 15:37:10 +00002978 if (FDecl) {
2979 // Check if we have too few/too many template arguments, based
2980 // on our knowledge of the function definition.
2981 const FunctionDecl *Def = 0;
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002982 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002983 const FunctionProtoType *Proto =
John McCall9dd450b2009-09-21 23:43:11 +00002984 Def->getType()->getAs<FunctionProtoType>();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00002985 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2986 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2987 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2988 }
2989 }
Douglas Gregord8e97de2009-04-02 15:37:10 +00002990 }
2991
Steve Naroff0b661582007-08-28 23:30:39 +00002992 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00002993 for (unsigned i = 0; i != NumArgs; i++) {
2994 Expr *Arg = Args[i];
2995 DefaultArgumentPromotion(Arg);
Eli Friedman3164fb12009-03-22 22:00:50 +00002996 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2997 Arg->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00002998 PDiag(diag::err_call_incomplete_argument)
2999 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003000 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003001 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003002 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003003 }
Chris Lattner08464942007-12-28 05:29:59 +00003004
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003005 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3006 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003007 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3008 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003009
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003010 // Check for sentinels
3011 if (NDecl)
3012 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003013
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003014 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003015 if (FDecl) {
3016 if (CheckFunctionCall(FDecl, TheCall.get()))
3017 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003018
Douglas Gregor15fc9562009-09-12 00:22:50 +00003019 if (unsigned BuiltinID = FDecl->getBuiltinID())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003020 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3021 } else if (NDecl) {
3022 if (CheckBlockCall(NDecl, TheCall.get()))
3023 return ExprError();
3024 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003025
Anders Carlssonf8984012009-08-16 03:06:32 +00003026 return MaybeBindToTemporary(TheCall.take());
Chris Lattnere168f762006-11-10 05:29:30 +00003027}
3028
Sebastian Redlb5d49352009-01-19 22:31:54 +00003029Action::OwningExprResult
3030Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3031 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003032 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003033 //FIXME: Preserve type source info.
3034 QualType literalType = GetTypeFromParser(Ty);
Steve Naroff57eb2c52007-07-19 21:32:11 +00003035 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003036 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redlb5d49352009-01-19 22:31:54 +00003037 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003038
Eli Friedman37a186d2008-05-20 05:22:08 +00003039 if (literalType->isArrayType()) {
Chris Lattner7adf0762008-08-04 07:31:14 +00003040 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003041 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3042 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003043 } else if (!literalType->isDependentType() &&
3044 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003045 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003046 << SourceRange(LParenLoc,
Anders Carlssond624e162009-08-26 23:45:07 +00003047 literalExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003048 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003049
Sebastian Redlb5d49352009-01-19 22:31:54 +00003050 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003051 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003052 return ExprError();
Steve Naroffd32419d2008-01-14 18:19:28 +00003053
Chris Lattner79413952008-12-04 23:50:19 +00003054 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003055 if (isFileScope) { // 6.5.2.5p3
Steve Naroff98f72032008-01-10 22:15:12 +00003056 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003057 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003058 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00003059 InitExpr.release();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003060 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Narofff6009ed2009-01-21 00:14:39 +00003061 literalExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003062}
3063
Sebastian Redlb5d49352009-01-19 22:31:54 +00003064Action::OwningExprResult
3065Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003066 SourceLocation RBraceLoc) {
3067 unsigned NumInit = initlist.size();
3068 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson4692db02007-08-31 04:56:16 +00003069
Steve Naroff30d242c2007-09-15 18:49:24 +00003070 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003071 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003072
Mike Stump4e1f26a2009-02-19 03:04:26 +00003073 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregor347f7ea2009-01-28 21:54:33 +00003074 RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003075 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003076 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003077}
3078
Anders Carlsson094c4592009-10-18 18:12:03 +00003079static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3080 QualType SrcTy, QualType DestTy) {
3081 if (Context.getCanonicalType(SrcTy).getUnqualifiedType() ==
3082 Context.getCanonicalType(DestTy).getUnqualifiedType())
3083 return CastExpr::CK_NoOp;
3084
3085 if (SrcTy->hasPointerRepresentation()) {
3086 if (DestTy->hasPointerRepresentation())
3087 return CastExpr::CK_BitCast;
3088 if (DestTy->isIntegerType())
3089 return CastExpr::CK_PointerToIntegral;
3090 }
3091
3092 if (SrcTy->isIntegerType()) {
3093 if (DestTy->isIntegerType())
3094 return CastExpr::CK_IntegralCast;
3095 if (DestTy->hasPointerRepresentation())
3096 return CastExpr::CK_IntegralToPointer;
3097 if (DestTy->isRealFloatingType())
3098 return CastExpr::CK_IntegralToFloating;
3099 }
3100
3101 if (SrcTy->isRealFloatingType()) {
3102 if (DestTy->isRealFloatingType())
3103 return CastExpr::CK_FloatingCast;
3104 if (DestTy->isIntegerType())
3105 return CastExpr::CK_FloatingToIntegral;
3106 }
3107
3108 // FIXME: Assert here.
3109 // assert(false && "Unhandled cast combination!");
3110 return CastExpr::CK_Unknown;
3111}
3112
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003113/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redl955a0672009-07-29 13:50:23 +00003114bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Mike Stump11289f42009-09-09 15:08:12 +00003115 CastExpr::CastKind& Kind,
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003116 CXXMethodDecl *& ConversionDecl,
3117 bool FunctionalStyle) {
Sebastian Redl9f831db2009-07-25 15:41:38 +00003118 if (getLangOptions().CPlusPlus)
Fariborz Jahanian1cec0c42009-08-26 18:55:36 +00003119 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3120 ConversionDecl);
Sebastian Redl9f831db2009-07-25 15:41:38 +00003121
Eli Friedmanda8d4de2009-08-15 19:02:19 +00003122 DefaultFunctionArrayConversion(castExpr);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003123
3124 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3125 // type needs to be scalar.
3126 if (castType->isVoidType()) {
3127 // Cast to void allows any expr type.
Anders Carlssonef918ac2009-10-16 02:35:04 +00003128 Kind = CastExpr::CK_ToVoid;
3129 return false;
3130 }
3131
3132 if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003133 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3134 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3135 (castType->isStructureType() || castType->isUnionType())) {
3136 // GCC struct/union extension: allow cast to self.
Eli Friedmanba961a92009-03-23 00:24:07 +00003137 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003138 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3139 << castType << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003140 Kind = CastExpr::CK_NoOp;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003141 return false;
3142 }
3143
3144 if (castType->isUnionType()) {
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003145 // GCC cast to union extension
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003146 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003147 RecordDecl::field_iterator Field, FieldEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003148 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon39a3ebf2009-01-15 04:51:39 +00003149 Field != FieldEnd; ++Field) {
3150 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3151 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3152 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3153 << castExpr->getSourceRange();
3154 break;
3155 }
3156 }
3157 if (Field == FieldEnd)
3158 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3159 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonec143772009-08-07 23:22:37 +00003160 Kind = CastExpr::CK_ToUnion;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003161 return false;
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003162 }
Anders Carlsson525b76b2009-10-16 02:48:28 +00003163
3164 // Reject any other conversions to non-scalar types.
3165 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3166 << castType << castExpr->getSourceRange();
3167 }
3168
3169 if (!castExpr->getType()->isScalarType() &&
3170 !castExpr->getType()->isVectorType()) {
Chris Lattner3b054132008-11-19 05:08:23 +00003171 return Diag(castExpr->getLocStart(),
3172 diag::err_typecheck_expect_scalar_operand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003173 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlsson525b76b2009-10-16 02:48:28 +00003174 }
3175
Anders Carlsson43d70f82009-10-16 05:23:41 +00003176 if (castType->isExtVectorType())
3177 return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3178
Anders Carlsson525b76b2009-10-16 02:48:28 +00003179 if (castType->isVectorType())
3180 return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3181 if (castExpr->getType()->isVectorType())
3182 return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3183
3184 if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr))
Steve Naroffb47acdb2009-04-08 23:52:26 +00003185 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Anders Carlsson525b76b2009-10-16 02:48:28 +00003186
Anders Carlsson43d70f82009-10-16 05:23:41 +00003187 if (isa<ObjCSelectorExpr>(castExpr))
3188 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3189
Anders Carlsson525b76b2009-10-16 02:48:28 +00003190 if (!castType->isArithmeticType()) {
Eli Friedmanf4e3ad62009-05-01 02:23:58 +00003191 QualType castExprType = castExpr->getType();
3192 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3193 return Diag(castExpr->getLocStart(),
3194 diag::err_cast_pointer_from_non_pointer_int)
3195 << castExprType << castExpr->getSourceRange();
3196 } else if (!castExpr->getType()->isArithmeticType()) {
3197 if (!castType->isIntegralType() && castType->isArithmeticType())
3198 return Diag(castExpr->getLocStart(),
3199 diag::err_cast_pointer_to_non_pointer_int)
3200 << castType << castExpr->getSourceRange();
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003201 }
Anders Carlsson094c4592009-10-18 18:12:03 +00003202
3203 Kind = getScalarCastKind(Context, castExpr->getType(), castType);
Argyrios Kyrtzidis2ade3902008-08-16 20:27:34 +00003204 return false;
3205}
3206
Anders Carlsson525b76b2009-10-16 02:48:28 +00003207bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3208 CastExpr::CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00003209 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00003210
Anders Carlssonde71adf2007-11-27 05:51:55 +00003211 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00003212 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00003213 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00003214 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00003215 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00003216 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003217 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003218 } else
3219 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003220 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00003221 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003222
Anders Carlsson525b76b2009-10-16 02:48:28 +00003223 Kind = CastExpr::CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00003224 return false;
3225}
3226
Anders Carlsson43d70f82009-10-16 05:23:41 +00003227bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3228 CastExpr::CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00003229 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Anders Carlsson43d70f82009-10-16 05:23:41 +00003230
3231 QualType SrcTy = CastExpr->getType();
3232
Nate Begemanc8961a42009-06-27 22:05:55 +00003233 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3234 // an ExtVectorType.
Nate Begemanc69b7402009-06-26 00:50:28 +00003235 if (SrcTy->isVectorType()) {
3236 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3237 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3238 << DestTy << SrcTy << R;
Anders Carlsson43d70f82009-10-16 05:23:41 +00003239 Kind = CastExpr::CK_BitCast;
Nate Begemanc69b7402009-06-26 00:50:28 +00003240 return false;
3241 }
3242
Nate Begemanbd956c42009-06-28 02:36:38 +00003243 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00003244 // conversion will take place first from scalar to elt type, and then
3245 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00003246 if (SrcTy->isPointerType())
3247 return Diag(R.getBegin(),
3248 diag::err_invalid_conversion_between_vector_and_scalar)
3249 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00003250
3251 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3252 ImpCastExprToType(CastExpr, DestElemTy,
3253 getScalarCastKind(Context, SrcTy, DestElemTy));
Anders Carlsson43d70f82009-10-16 05:23:41 +00003254
3255 Kind = CastExpr::CK_VectorSplat;
Nate Begemanc69b7402009-06-26 00:50:28 +00003256 return false;
3257}
3258
Sebastian Redlb5d49352009-01-19 22:31:54 +00003259Action::OwningExprResult
Nate Begeman5ec4b312009-08-10 23:49:36 +00003260Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003261 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlssonf10e4142009-08-07 22:21:05 +00003262 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Mike Stump11289f42009-09-09 15:08:12 +00003263
Sebastian Redlb5d49352009-01-19 22:31:54 +00003264 assert((Ty != 0) && (Op.get() != 0) &&
3265 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00003266
Nate Begeman5ec4b312009-08-10 23:49:36 +00003267 Expr *castExpr = (Expr *)Op.get();
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00003268 //FIXME: Preserve type source info.
3269 QualType castType = GetTypeFromParser(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003270
Nate Begeman5ec4b312009-08-10 23:49:36 +00003271 // If the Expr being casted is a ParenListExpr, handle it specially.
3272 if (isa<ParenListExpr>(castExpr))
3273 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Anders Carlssone9766d52009-09-09 21:33:21 +00003274 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00003275 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
Anders Carlssone9766d52009-09-09 21:33:21 +00003276 Kind, Method))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003277 return ExprError();
Anders Carlssone9766d52009-09-09 21:33:21 +00003278
3279 if (Method) {
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003280 OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
Anders Carlssone9766d52009-09-09 21:33:21 +00003281 Method, move(Op));
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003282
Anders Carlssone9766d52009-09-09 21:33:21 +00003283 if (CastArg.isInvalid())
3284 return ExprError();
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003285
Anders Carlssone9766d52009-09-09 21:33:21 +00003286 castExpr = CastArg.takeAs<Expr>();
3287 } else {
3288 Op.release();
Fariborz Jahanian3df87672009-08-29 19:15:16 +00003289 }
Mike Stump11289f42009-09-09 15:08:12 +00003290
Sebastian Redl9f831db2009-07-25 15:41:38 +00003291 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Mike Stump11289f42009-09-09 15:08:12 +00003292 Kind, castExpr, castType,
Anders Carlssonf10e4142009-08-07 22:21:05 +00003293 LParenLoc, RParenLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003294}
3295
Nate Begeman5ec4b312009-08-10 23:49:36 +00003296/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3297/// of comma binary operators.
3298Action::OwningExprResult
3299Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3300 Expr *expr = EA.takeAs<Expr>();
3301 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3302 if (!E)
3303 return Owned(expr);
Mike Stump11289f42009-09-09 15:08:12 +00003304
Nate Begeman5ec4b312009-08-10 23:49:36 +00003305 OwningExprResult Result(*this, E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00003306
Nate Begeman5ec4b312009-08-10 23:49:36 +00003307 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3308 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3309 Owned(E->getExpr(i)));
Mike Stump11289f42009-09-09 15:08:12 +00003310
Nate Begeman5ec4b312009-08-10 23:49:36 +00003311 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3312}
3313
3314Action::OwningExprResult
3315Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3316 SourceLocation RParenLoc, ExprArg Op,
3317 QualType Ty) {
3318 ParenListExpr *PE = (ParenListExpr *)Op.get();
Mike Stump11289f42009-09-09 15:08:12 +00003319
3320 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
Nate Begeman5ec4b312009-08-10 23:49:36 +00003321 // then handle it as such.
3322 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3323 if (PE->getNumExprs() == 0) {
3324 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3325 return ExprError();
3326 }
3327
3328 llvm::SmallVector<Expr *, 8> initExprs;
3329 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3330 initExprs.push_back(PE->getExpr(i));
3331
3332 // FIXME: This means that pretty-printing the final AST will produce curly
3333 // braces instead of the original commas.
3334 Op.release();
Mike Stump11289f42009-09-09 15:08:12 +00003335 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
Nate Begeman5ec4b312009-08-10 23:49:36 +00003336 initExprs.size(), RParenLoc);
3337 E->setType(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00003338 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
Nate Begeman5ec4b312009-08-10 23:49:36 +00003339 Owned(E));
3340 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003341 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
Nate Begeman5ec4b312009-08-10 23:49:36 +00003342 // sequence of BinOp comma operators.
3343 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3344 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3345 }
3346}
3347
3348Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3349 SourceLocation R,
3350 MultiExprArg Val) {
3351 unsigned nexprs = Val.size();
3352 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3353 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3354 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3355 return Owned(expr);
3356}
3357
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003358/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3359/// In that case, lhs = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00003360/// C99 6.5.15
3361QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3362 SourceLocation QuestionLoc) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003363 // C++ is sufficiently different to merit its own checker.
3364 if (getLangOptions().CPlusPlus)
3365 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3366
Chris Lattner432cff52009-02-18 04:28:32 +00003367 UsualUnaryConversions(Cond);
3368 UsualUnaryConversions(LHS);
3369 UsualUnaryConversions(RHS);
3370 QualType CondTy = Cond->getType();
3371 QualType LHSTy = LHS->getType();
3372 QualType RHSTy = RHS->getType();
Steve Naroff31090012007-07-16 21:54:35 +00003373
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003374 // first, check the condition.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003375 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3376 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3377 << CondTy;
3378 return QualType();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003379 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003380
Chris Lattnere2949f42008-01-06 22:42:25 +00003381 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00003382 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3383 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor4619e432008-12-05 23:32:09 +00003384
Chris Lattnere2949f42008-01-06 22:42:25 +00003385 // If both operands have arithmetic type, do the usual arithmetic conversions
3386 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00003387 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3388 UsualArithmeticConversions(LHS, RHS);
3389 return LHS->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00003390 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003391
Chris Lattnere2949f42008-01-06 22:42:25 +00003392 // If both operands are the same structure or union type, the result is that
3393 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003394 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3395 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00003396 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00003397 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00003398 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00003399 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00003400 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003401 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003402
Chris Lattnere2949f42008-01-06 22:42:25 +00003403 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00003404 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00003405 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3406 if (!LHSTy->isVoidType())
3407 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3408 << RHS->getSourceRange();
3409 if (!RHSTy->isVoidType())
3410 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3411 << LHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003412 ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
3413 ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
Eli Friedman3e1852f2008-06-04 19:47:51 +00003414 return Context.VoidTy;
Steve Naroffbf1516c2008-05-12 21:44:38 +00003415 }
Steve Naroff039ad3c2008-01-08 01:11:38 +00003416 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3417 // the type of the other operand."
Steve Naroff6b712a72009-07-14 18:25:06 +00003418 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00003419 RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003420 // promote the null to a pointer.
3421 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00003422 return LHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003423 }
Steve Naroff6b712a72009-07-14 18:25:06 +00003424 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00003425 LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003426 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
Chris Lattner432cff52009-02-18 04:28:32 +00003427 return RHSTy;
Steve Naroff039ad3c2008-01-08 01:11:38 +00003428 }
David Chisnall9f57c292009-08-17 16:35:33 +00003429 // Handle things like Class and struct objc_class*. Here we case the result
3430 // to the pseudo-builtin, because that will be implicitly cast back to the
3431 // redefinition type if an attempt is made to access its fields.
3432 if (LHSTy->isObjCClassType() &&
3433 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003434 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003435 return LHSTy;
3436 }
3437 if (RHSTy->isObjCClassType() &&
3438 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003439 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003440 return RHSTy;
3441 }
3442 // And the same for struct objc_object* / id
3443 if (LHSTy->isObjCIdType() &&
3444 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003445 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003446 return LHSTy;
3447 }
3448 if (RHSTy->isObjCIdType() &&
3449 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00003450 ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
David Chisnall9f57c292009-08-17 16:35:33 +00003451 return RHSTy;
3452 }
Steve Naroff05efa972009-07-01 14:36:47 +00003453 // Handle block pointer types.
3454 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3455 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3456 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3457 QualType destType = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003458 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
3459 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003460 return destType;
3461 }
3462 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3463 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3464 return QualType();
Mike Stump1b821b42009-05-07 03:14:14 +00003465 }
Steve Naroff05efa972009-07-01 14:36:47 +00003466 // We have 2 block pointer types.
3467 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3468 // Two identical block pointer types are always compatible.
Mike Stump1b821b42009-05-07 03:14:14 +00003469 return LHSTy;
3470 }
Steve Naroff05efa972009-07-01 14:36:47 +00003471 // The block pointer types aren't identical, continue checking.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003472 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3473 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003474
Steve Naroff05efa972009-07-01 14:36:47 +00003475 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3476 rhptee.getUnqualifiedType())) {
Mike Stump1b821b42009-05-07 03:14:14 +00003477 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3478 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3479 // In this situation, we assume void* type. No especially good
3480 // reason, but this is what gcc does, and we do have to pick
3481 // to get a consistent AST.
3482 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003483 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3484 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Mike Stump1b821b42009-05-07 03:14:14 +00003485 return incompatTy;
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003486 }
Steve Naroff05efa972009-07-01 14:36:47 +00003487 // The block pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00003488 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3489 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroffea4c7802009-04-08 17:05:15 +00003490 return LHSTy;
3491 }
Steve Naroff05efa972009-07-01 14:36:47 +00003492 // Check constraints for Objective-C object pointers types.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003493 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003494
Steve Naroff05efa972009-07-01 14:36:47 +00003495 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3496 // Two identical object pointer types are always compatible.
3497 return LHSTy;
3498 }
John McCall9dd450b2009-09-21 23:43:11 +00003499 const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3500 const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
Steve Naroff05efa972009-07-01 14:36:47 +00003501 QualType compositeType = LHSTy;
Mike Stump11289f42009-09-09 15:08:12 +00003502
Steve Naroff05efa972009-07-01 14:36:47 +00003503 // If both operands are interfaces and either operand can be
3504 // assigned to the other, use that type as the composite
3505 // type. This allows
3506 // xxx ? (A*) a : (B*) b
3507 // where B is a subclass of A.
3508 //
3509 // Additionally, as for assignment, if either type is 'id'
3510 // allow silent coercion. Finally, if the types are
3511 // incompatible then make sure to use 'id' as the composite
3512 // type so the result is acceptable for sending messages to.
3513
3514 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3515 // It could return the composite type.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003516 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Fariborz Jahaniana83c0162009-08-22 22:27:17 +00003517 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003518 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Fariborz Jahaniana83c0162009-08-22 22:27:17 +00003519 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
Mike Stump11289f42009-09-09 15:08:12 +00003520 } else if ((LHSTy->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00003521 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff8e6aee52009-07-23 01:01:38 +00003522 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Mike Stump11289f42009-09-09 15:08:12 +00003523 // Need to handle "id<xx>" explicitly.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003524 // GCC allows qualified id and any Objective-C type to devolve to
3525 // id. Currently localizing to here until clear this should be
3526 // part of ObjCQualifiedIdTypesAreCompatible.
3527 compositeType = Context.getObjCIdType();
3528 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff05efa972009-07-01 14:36:47 +00003529 compositeType = Context.getObjCIdType();
3530 } else {
3531 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3532 << LHSTy << RHSTy
3533 << LHS->getSourceRange() << RHS->getSourceRange();
3534 QualType incompatTy = Context.getObjCIdType();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003535 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3536 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003537 return incompatTy;
3538 }
3539 // The object pointer types are compatible.
Eli Friedman06ed2a52009-10-20 08:27:19 +00003540 ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
3541 ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003542 return compositeType;
3543 }
Steve Naroff85d97152009-07-29 15:09:39 +00003544 // Check Objective-C object pointer types and 'void *'
3545 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003546 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003547 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003548 QualType destPointee
3549 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff85d97152009-07-29 15:09:39 +00003550 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003551 // Add qualifiers if necessary.
3552 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3553 // Promote to void*.
3554 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff85d97152009-07-29 15:09:39 +00003555 return destType;
3556 }
3557 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
John McCall9dd450b2009-09-21 23:43:11 +00003558 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003559 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003560 QualType destPointee
3561 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff85d97152009-07-29 15:09:39 +00003562 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003563 // Add qualifiers if necessary.
3564 ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
3565 // Promote to void*.
3566 ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
Steve Naroff85d97152009-07-29 15:09:39 +00003567 return destType;
3568 }
Steve Naroff05efa972009-07-01 14:36:47 +00003569 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3570 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3571 // get the "pointed to" types
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003572 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3573 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff05efa972009-07-01 14:36:47 +00003574
3575 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3576 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3577 // Figure out necessary qualifiers (C99 6.5.15p6)
John McCall8ccfcb52009-09-24 19:53:00 +00003578 QualType destPointee
3579 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00003580 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003581 // Add qualifiers if necessary.
3582 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3583 // Promote to void*.
3584 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003585 return destType;
3586 }
3587 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
John McCall8ccfcb52009-09-24 19:53:00 +00003588 QualType destPointee
3589 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
Steve Naroff05efa972009-07-01 14:36:47 +00003590 QualType destType = Context.getPointerType(destPointee);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003591 // Add qualifiers if necessary.
3592 ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
3593 // Promote to void*.
3594 ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003595 return destType;
3596 }
3597
3598 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3599 // Two identical pointer types are always compatible.
3600 return LHSTy;
3601 }
3602 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3603 rhptee.getUnqualifiedType())) {
3604 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3605 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3606 // In this situation, we assume void* type. No especially good
3607 // reason, but this is what gcc does, and we do have to pick
3608 // to get a consistent AST.
3609 QualType incompatTy = Context.getPointerType(Context.VoidTy);
Eli Friedman06ed2a52009-10-20 08:27:19 +00003610 ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
3611 ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003612 return incompatTy;
3613 }
3614 // The pointer types are compatible.
3615 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3616 // differently qualified versions of compatible types, the result type is
3617 // a pointer to an appropriately qualified version of the *composite*
3618 // type.
3619 // FIXME: Need to calculate the composite type.
3620 // FIXME: Need to add qualifiers
Eli Friedman06ed2a52009-10-20 08:27:19 +00003621 ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
3622 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
Steve Naroff05efa972009-07-01 14:36:47 +00003623 return LHSTy;
3624 }
Mike Stump11289f42009-09-09 15:08:12 +00003625
Steve Naroff05efa972009-07-01 14:36:47 +00003626 // GCC compatibility: soften pointer/integer mismatch.
3627 if (RHSTy->isPointerType() && LHSTy->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(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00003631 return RHSTy;
3632 }
3633 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3634 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3635 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003636 ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
Steve Naroff05efa972009-07-01 14:36:47 +00003637 return LHSTy;
3638 }
Daniel Dunbar484603b2008-09-11 23:12:46 +00003639
Chris Lattnere2949f42008-01-06 22:42:25 +00003640 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00003641 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3642 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00003643 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00003644}
3645
Steve Naroff83895f72007-09-16 03:34:24 +00003646/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00003647/// in the case of a the GNU conditional expr extension.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003648Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3649 SourceLocation ColonLoc,
3650 ExprArg Cond, ExprArg LHS,
3651 ExprArg RHS) {
3652 Expr *CondExpr = (Expr *) Cond.get();
3653 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner2ab40a62007-11-26 01:40:58 +00003654
3655 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3656 // was the condition.
3657 bool isLHSNull = LHSExpr == 0;
3658 if (isLHSNull)
3659 LHSExpr = CondExpr;
Sebastian Redlb5d49352009-01-19 22:31:54 +00003660
3661 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattnerdaaa9f22007-07-16 21:39:03 +00003662 RHSExpr, QuestionLoc);
Steve Narofff8a28c52007-05-15 20:29:32 +00003663 if (result.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003664 return ExprError();
3665
3666 Cond.release();
3667 LHS.release();
3668 RHS.release();
Douglas Gregor7e112b02009-08-26 14:37:04 +00003669 return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
Steve Narofff6009ed2009-01-21 00:14:39 +00003670 isLHSNull ? 0 : LHSExpr,
Douglas Gregor7e112b02009-08-26 14:37:04 +00003671 ColonLoc, RHSExpr, result));
Chris Lattnere168f762006-11-10 05:29:30 +00003672}
3673
Steve Naroff3f597292007-05-11 22:18:03 +00003674// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00003675// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00003676// routine is it effectively iqnores the qualifiers on the top level pointee.
3677// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3678// FIXME: add a couple examples in this comment.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003679Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00003680Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
Steve Naroff3f597292007-05-11 22:18:03 +00003681 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003682
David Chisnall9f57c292009-08-17 16:35:33 +00003683 if ((lhsType->isObjCClassType() &&
3684 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3685 (rhsType->isObjCClassType() &&
3686 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3687 return Compatible;
3688 }
3689
Steve Naroff1f4d7272007-05-11 04:00:31 +00003690 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003691 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3692 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003693
Steve Naroff1f4d7272007-05-11 04:00:31 +00003694 // make sure we operate on the canonical type
Chris Lattner574dee62008-07-26 22:17:49 +00003695 lhptee = Context.getCanonicalType(lhptee);
3696 rhptee = Context.getCanonicalType(rhptee);
Steve Naroff1f4d7272007-05-11 04:00:31 +00003697
Chris Lattner9bad62c2008-01-04 18:04:52 +00003698 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003699
3700 // C99 6.5.16.1p1: This following citation is common to constraints
3701 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3702 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianece85822009-02-17 18:27:45 +00003703 // FIXME: Handle ExtQualType
Douglas Gregor9a657932008-10-21 23:43:52 +00003704 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner9bad62c2008-01-04 18:04:52 +00003705 ConvTy = CompatiblePointerDiscardsQualifiers;
Steve Naroff3f597292007-05-11 22:18:03 +00003706
Mike Stump4e1f26a2009-02-19 03:04:26 +00003707 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3708 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00003709 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00003710 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003711 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00003712 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003713
Chris Lattner0a788432008-01-03 22:56:36 +00003714 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003715 assert(rhptee->isFunctionType());
3716 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00003717 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003718
Chris Lattner0a788432008-01-03 22:56:36 +00003719 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003720 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00003721 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00003722
3723 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00003724 assert(lhptee->isFunctionType());
3725 return FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00003726 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003727 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00003728 // unqualified versions of compatible types, ...
Eli Friedman80160bd2009-03-22 23:59:44 +00003729 lhptee = lhptee.getUnqualifiedType();
3730 rhptee = rhptee.getUnqualifiedType();
3731 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3732 // Check if the pointee types are compatible ignoring the sign.
3733 // We explicitly check for char so that we catch "char" vs
3734 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00003735 if (lhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00003736 lhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00003737 else if (lhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00003738 lhptee = Context.getCorrespondingUnsignedType(lhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00003739
3740 if (rhptee->isCharType())
Eli Friedman80160bd2009-03-22 23:59:44 +00003741 rhptee = Context.UnsignedCharTy;
Chris Lattnerec3a1562009-10-17 20:33:28 +00003742 else if (rhptee->isSignedIntegerType())
Eli Friedman80160bd2009-03-22 23:59:44 +00003743 rhptee = Context.getCorrespondingUnsignedType(rhptee);
Chris Lattnerec3a1562009-10-17 20:33:28 +00003744
Eli Friedman80160bd2009-03-22 23:59:44 +00003745 if (lhptee == rhptee) {
3746 // Types are compatible ignoring the sign. Qualifier incompatibility
3747 // takes priority over sign incompatibility because the sign
3748 // warning can be disabled.
3749 if (ConvTy != Compatible)
3750 return ConvTy;
3751 return IncompatiblePointerSign;
3752 }
3753 // General pointer incompatibility takes priority over qualifiers.
Mike Stump11289f42009-09-09 15:08:12 +00003754 return IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00003755 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00003756 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00003757}
3758
Steve Naroff081c7422008-09-04 15:10:53 +00003759/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3760/// block pointer types are compatible or whether a block and normal pointer
3761/// are compatible. It is more restrict than comparing two function pointer
3762// types.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003763Sema::AssignConvertType
3764Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff081c7422008-09-04 15:10:53 +00003765 QualType rhsType) {
3766 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003767
Steve Naroff081c7422008-09-04 15:10:53 +00003768 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003769 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3770 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00003771
Steve Naroff081c7422008-09-04 15:10:53 +00003772 // make sure we operate on the canonical type
3773 lhptee = Context.getCanonicalType(lhptee);
3774 rhptee = Context.getCanonicalType(rhptee);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003775
Steve Naroff081c7422008-09-04 15:10:53 +00003776 AssignConvertType ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003777
Steve Naroff081c7422008-09-04 15:10:53 +00003778 // For blocks we enforce that qualifiers are identical.
3779 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3780 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003781
Eli Friedmana6638ca2009-06-08 05:08:54 +00003782 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump4e1f26a2009-02-19 03:04:26 +00003783 return IncompatibleBlockPointer;
Steve Naroff081c7422008-09-04 15:10:53 +00003784 return ConvTy;
3785}
3786
Mike Stump4e1f26a2009-02-19 03:04:26 +00003787/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3788/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00003789/// pointers. Here are some objectionable examples that GCC considers warnings:
3790///
3791/// int a, *pint;
3792/// short *pshort;
3793/// struct foo *pfoo;
3794///
3795/// pint = pshort; // warning: assignment from incompatible pointer type
3796/// a = pint; // warning: assignment makes integer from pointer without a cast
3797/// pint = a; // warning: assignment makes pointer from integer without a cast
3798/// pint = pfoo; // warning: assignment from incompatible pointer type
3799///
3800/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00003801/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00003802///
Chris Lattner9bad62c2008-01-04 18:04:52 +00003803Sema::AssignConvertType
Steve Naroff98cf3e92007-06-06 18:38:38 +00003804Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattnera52c2f22008-01-04 23:18:45 +00003805 // Get canonical types. We're not formatting these types, just comparing
3806 // them.
Chris Lattner574dee62008-07-26 22:17:49 +00003807 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3808 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00003809
3810 if (lhsType == rhsType)
Chris Lattnerf5c973d2008-01-07 17:51:46 +00003811 return Compatible; // Common case: fast path an exact match.
Steve Naroff44fd8ff2007-07-24 21:46:40 +00003812
David Chisnall9f57c292009-08-17 16:35:33 +00003813 if ((lhsType->isObjCClassType() &&
3814 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3815 (rhsType->isObjCClassType() &&
3816 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3817 return Compatible;
3818 }
3819
Douglas Gregor6b754842008-10-28 00:22:11 +00003820 // If the left-hand side is a reference type, then we are in a
3821 // (rare!) case where we've allowed the use of references in C,
3822 // e.g., as a parameter type in a built-in function. In this case,
3823 // just make sure that the type referenced is compatible with the
3824 // right-hand side type. The caller is responsible for adjusting
3825 // lhsType so that the resulting expression does not have reference
3826 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003827 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor6b754842008-10-28 00:22:11 +00003828 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlsson24ebce62007-10-12 23:56:29 +00003829 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00003830 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00003831 }
Nate Begemanbd956c42009-06-28 02:36:38 +00003832 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3833 // to the same ExtVector type.
3834 if (lhsType->isExtVectorType()) {
3835 if (rhsType->isExtVectorType())
3836 return lhsType == rhsType ? Compatible : Incompatible;
3837 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3838 return Compatible;
3839 }
Mike Stump11289f42009-09-09 15:08:12 +00003840
Nate Begeman191a6b12008-07-14 18:02:46 +00003841 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00003842 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump4e1f26a2009-02-19 03:04:26 +00003843 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begeman191a6b12008-07-14 18:02:46 +00003844 // no bits are changed but the result type is different.
Chris Lattner881a2122008-01-04 23:32:24 +00003845 if (getLangOptions().LaxVectorConversions &&
3846 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00003847 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlssondb5a9b62009-01-30 23:17:46 +00003848 return IncompatibleVectors;
Chris Lattner881a2122008-01-04 23:32:24 +00003849 }
3850 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003851 }
Eli Friedman3360d892008-05-30 18:07:22 +00003852
Chris Lattner881a2122008-01-04 23:32:24 +00003853 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Steve Naroff98cf3e92007-06-06 18:38:38 +00003854 return Compatible;
Eli Friedman3360d892008-05-30 18:07:22 +00003855
Chris Lattnerec646832008-04-07 06:49:41 +00003856 if (isa<PointerType>(lhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00003857 if (rhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00003858 return IntToPointer;
Eli Friedman3360d892008-05-30 18:07:22 +00003859
Chris Lattnerec646832008-04-07 06:49:41 +00003860 if (isa<PointerType>(rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00003861 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003862
Steve Naroffaccc4882009-07-20 17:56:53 +00003863 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003864 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00003865 if (lhsType->isVoidPointerType()) // an exception to the rule.
3866 return Compatible;
3867 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003868 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003869 if (rhsType->getAs<BlockPointerType>()) {
3870 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00003871 return Compatible;
Steve Naroff32d072c2008-09-29 18:10:17 +00003872
3873 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003874 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00003875 return Compatible;
3876 }
Steve Naroff081c7422008-09-04 15:10:53 +00003877 return Incompatible;
3878 }
3879
3880 if (isa<BlockPointerType>(lhsType)) {
3881 if (rhsType->isIntegerType())
Eli Friedman8163b7a2009-02-25 04:20:42 +00003882 return IntToBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00003883
Steve Naroff32d072c2008-09-29 18:10:17 +00003884 // Treat block pointers as objects.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003885 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroff32d072c2008-09-29 18:10:17 +00003886 return Compatible;
3887
Steve Naroff081c7422008-09-04 15:10:53 +00003888 if (rhsType->isBlockPointerType())
3889 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003890
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003891 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff081c7422008-09-04 15:10:53 +00003892 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00003893 return Compatible;
Steve Naroff081c7422008-09-04 15:10:53 +00003894 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00003895 return Incompatible;
3896 }
3897
Steve Naroff7cae42b2009-07-10 23:34:53 +00003898 if (isa<ObjCObjectPointerType>(lhsType)) {
3899 if (rhsType->isIntegerType())
3900 return IntToPointer;
Mike Stump11289f42009-09-09 15:08:12 +00003901
Steve Naroffaccc4882009-07-20 17:56:53 +00003902 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003903 if (isa<PointerType>(rhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00003904 if (rhsType->isVoidPointerType()) // an exception to the rule.
3905 return Compatible;
3906 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003907 }
3908 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff1329fa02009-07-15 18:40:39 +00003909 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3910 return Compatible;
Steve Naroffaccc4882009-07-20 17:56:53 +00003911 if (Context.typesAreCompatible(lhsType, rhsType))
3912 return Compatible;
Steve Naroff8e6aee52009-07-23 01:01:38 +00003913 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3914 return IncompatibleObjCQualifiedId;
Steve Naroffaccc4882009-07-20 17:56:53 +00003915 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003916 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003917 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003918 if (RHSPT->getPointeeType()->isVoidType())
3919 return Compatible;
3920 }
3921 // Treat block pointers as objects.
3922 if (rhsType->isBlockPointerType())
3923 return Compatible;
3924 return Incompatible;
3925 }
Chris Lattnerec646832008-04-07 06:49:41 +00003926 if (isa<PointerType>(rhsType)) {
Steve Naroff98cf3e92007-06-06 18:38:38 +00003927 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman3360d892008-05-30 18:07:22 +00003928 if (lhsType == Context.BoolTy)
3929 return Compatible;
3930
3931 if (lhsType->isIntegerType())
Chris Lattner940cfeb2008-01-04 18:22:42 +00003932 return PointerToInt;
Steve Naroff98cf3e92007-06-06 18:38:38 +00003933
Mike Stump4e1f26a2009-02-19 03:04:26 +00003934 if (isa<PointerType>(lhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00003935 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump4e1f26a2009-02-19 03:04:26 +00003936
3937 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003938 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregore7dd1452008-11-27 00:44:28 +00003939 return Compatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00003940 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00003941 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00003942 if (isa<ObjCObjectPointerType>(rhsType)) {
3943 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3944 if (lhsType == Context.BoolTy)
3945 return Compatible;
3946
3947 if (lhsType->isIntegerType())
3948 return PointerToInt;
3949
Steve Naroffaccc4882009-07-20 17:56:53 +00003950 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff7cae42b2009-07-10 23:34:53 +00003951 if (isa<PointerType>(lhsType)) {
Steve Naroffaccc4882009-07-20 17:56:53 +00003952 if (lhsType->isVoidPointerType()) // an exception to the rule.
3953 return Compatible;
3954 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00003955 }
3956 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003957 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00003958 return Compatible;
3959 return Incompatible;
3960 }
Eli Friedman3360d892008-05-30 18:07:22 +00003961
Chris Lattnera52c2f22008-01-04 23:18:45 +00003962 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattnerec646832008-04-07 06:49:41 +00003963 if (Context.typesAreCompatible(lhsType, rhsType))
Steve Naroff98cf3e92007-06-06 18:38:38 +00003964 return Compatible;
Bill Wendling216423b2007-05-30 06:30:29 +00003965 }
Steve Naroff98cf3e92007-06-06 18:38:38 +00003966 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00003967}
3968
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003969/// \brief Constructs a transparent union from an expression that is
3970/// used to initialize the transparent union.
Mike Stump11289f42009-09-09 15:08:12 +00003971static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003972 QualType UnionType, FieldDecl *Field) {
3973 // Build an initializer list that designates the appropriate member
3974 // of the transparent union.
3975 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3976 &E, 1,
3977 SourceLocation());
3978 Initializer->setType(UnionType);
3979 Initializer->setInitializedFieldInUnion(Field);
3980
3981 // Build a compound literal constructing a value of the transparent
3982 // union type from this initializer list.
3983 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3984 false);
3985}
3986
3987Sema::AssignConvertType
3988Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3989 QualType FromType = rExpr->getType();
3990
Mike Stump11289f42009-09-09 15:08:12 +00003991 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003992 // transparent_union GCC extension.
3993 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003994 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00003995 return Incompatible;
3996
3997 // The field to initialize within the transparent union.
3998 RecordDecl *UD = UT->getDecl();
3999 FieldDecl *InitField = 0;
4000 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004001 for (RecordDecl::field_iterator it = UD->field_begin(),
4002 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004003 it != itend; ++it) {
4004 if (it->getType()->isPointerType()) {
4005 // If the transparent union contains a pointer type, we allow:
4006 // 1) void pointer
4007 // 2) null pointer constant
4008 if (FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004009 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004010 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004011 InitField = *it;
4012 break;
4013 }
Mike Stump11289f42009-09-09 15:08:12 +00004014
Douglas Gregor56751b52009-09-25 04:25:58 +00004015 if (rExpr->isNullPointerConstant(Context,
4016 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004017 ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004018 InitField = *it;
4019 break;
4020 }
4021 }
4022
4023 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4024 == Compatible) {
4025 InitField = *it;
4026 break;
4027 }
4028 }
4029
4030 if (!InitField)
4031 return Incompatible;
4032
4033 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4034 return Compatible;
4035}
4036
Chris Lattner9bad62c2008-01-04 18:04:52 +00004037Sema::AssignConvertType
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004038Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor9a657932008-10-21 23:43:52 +00004039 if (getLangOptions().CPlusPlus) {
4040 if (!lhsType->isRecordType()) {
4041 // C++ 5.17p3: If the left operand is not of class type, the
4042 // expression is implicitly converted (C++ 4) to the
4043 // cv-unqualified type of the left operand.
Douglas Gregor47d3f272008-12-19 17:40:08 +00004044 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4045 "assigning"))
Douglas Gregor9a657932008-10-21 23:43:52 +00004046 return Incompatible;
Chris Lattner0d5640c2009-04-12 09:02:39 +00004047 return Compatible;
Douglas Gregor9a657932008-10-21 23:43:52 +00004048 }
4049
4050 // FIXME: Currently, we fall through and treat C++ classes like C
4051 // structures.
4052 }
4053
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004054 // C99 6.5.16.1p1: the left operand is a pointer and the right is
4055 // a null pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00004056 if ((lhsType->isPointerType() ||
4057 lhsType->isObjCObjectPointerType() ||
Mike Stump4e1f26a2009-02-19 03:04:26 +00004058 lhsType->isBlockPointerType())
Douglas Gregor56751b52009-09-25 04:25:58 +00004059 && rExpr->isNullPointerConstant(Context,
4060 Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004061 ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00004062 return Compatible;
4063 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004064
Chris Lattnere6dcd502007-10-16 02:55:40 +00004065 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004066 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff30d242c2007-09-15 18:49:24 +00004067 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004068 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00004069 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00004070 // Suppress this for references: C++ 8.5.3p5.
Chris Lattnere6dcd502007-10-16 02:55:40 +00004071 if (!lhsType->isReferenceType())
4072 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004073
Chris Lattner9bad62c2008-01-04 18:04:52 +00004074 Sema::AssignConvertType result =
4075 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004076
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004077 // C99 6.5.16.1p2: The value of the right operand is converted to the
4078 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00004079 // CheckAssignmentConstraints allows the left-hand side to be a reference,
4080 // so that we can use references in built-in functions even in C.
4081 // The getNonReferenceType() call makes sure that the resulting expression
4082 // does not have reference type.
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00004083 if (result != Incompatible && rExpr->getType() != lhsType)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004084 ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4085 CastExpr::CK_Unknown);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00004086 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004087}
4088
Chris Lattner326f7572008-11-18 01:30:42 +00004089QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004090 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00004091 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004092 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00004093 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00004094}
4095
Mike Stump4e1f26a2009-02-19 03:04:26 +00004096inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Steve Naroff7a5af782007-07-13 16:58:59 +00004097 Expr *&rex) {
Mike Stump4e1f26a2009-02-19 03:04:26 +00004098 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004099 // For example, "const float" and "float" are equivalent.
Chris Lattner574dee62008-07-26 22:17:49 +00004100 QualType lhsType =
4101 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4102 QualType rhsType =
4103 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004104
Nate Begeman191a6b12008-07-14 18:02:46 +00004105 // If the vector types are identical, return.
Nate Begeman002e4bd2008-04-04 01:30:25 +00004106 if (lhsType == rhsType)
Steve Naroff84ff4b42007-07-09 21:31:10 +00004107 return lhsType;
Nate Begeman330aaa72007-12-30 02:59:45 +00004108
Nate Begeman191a6b12008-07-14 18:02:46 +00004109 // Handle the case of a vector & extvector type of the same size and element
4110 // type. It would be nice if we only had one vector type someday.
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004111 if (getLangOptions().LaxVectorConversions) {
4112 // FIXME: Should we warn here?
John McCall9dd450b2009-09-21 23:43:11 +00004113 if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4114 if (const VectorType *RV = rhsType->getAs<VectorType>())
Nate Begeman191a6b12008-07-14 18:02:46 +00004115 if (LV->getElementType() == RV->getElementType() &&
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004116 LV->getNumElements() == RV->getNumElements()) {
Nate Begeman191a6b12008-07-14 18:02:46 +00004117 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00004118 }
4119 }
4120 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004121
Nate Begemanbd956c42009-06-28 02:36:38 +00004122 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4123 // swap back (so that we don't reverse the inputs to a subtract, for instance.
4124 bool swapped = false;
4125 if (rhsType->isExtVectorType()) {
4126 swapped = true;
4127 std::swap(rex, lex);
4128 std::swap(rhsType, lhsType);
4129 }
Mike Stump11289f42009-09-09 15:08:12 +00004130
Nate Begeman886448d2009-06-28 19:12:57 +00004131 // Handle the case of an ext vector and scalar.
John McCall9dd450b2009-09-21 23:43:11 +00004132 if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00004133 QualType EltTy = LV->getElementType();
4134 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4135 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004136 ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004137 if (swapped) std::swap(rex, lex);
4138 return lhsType;
4139 }
4140 }
4141 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4142 rhsType->isRealFloatingType()) {
4143 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004144 ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
Nate Begemanbd956c42009-06-28 02:36:38 +00004145 if (swapped) std::swap(rex, lex);
4146 return lhsType;
4147 }
Nate Begeman330aaa72007-12-30 02:59:45 +00004148 }
4149 }
Mike Stump11289f42009-09-09 15:08:12 +00004150
Nate Begeman886448d2009-06-28 19:12:57 +00004151 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner377d1f82008-11-18 22:52:51 +00004152 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004153 << lex->getType() << rex->getType()
Chris Lattner377d1f82008-11-18 22:52:51 +00004154 << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00004155 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00004156}
4157
Steve Naroff218bc2b2007-05-04 21:54:46 +00004158inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004159 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar060d5e22009-01-05 22:42:10 +00004160 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004161 return CheckVectorOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004162
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004163 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004164
Steve Naroffdbd9e892007-07-17 00:58:39 +00004165 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004166 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004167 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004168}
4169
Steve Naroff218bc2b2007-05-04 21:54:46 +00004170inline QualType Sema::CheckRemainderOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004171 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00004172 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4173 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4174 return CheckVectorOperands(Loc, lex, rex);
4175 return InvalidOperands(Loc, lex, rex);
4176 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004177
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004178 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004179
Steve Naroffdbd9e892007-07-17 00:58:39 +00004180 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004181 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004182 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004183}
4184
4185inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Mike Stump11289f42009-09-09 15:08:12 +00004186 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004187 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4188 QualType compType = CheckVectorOperands(Loc, lex, rex);
4189 if (CompLHSTy) *CompLHSTy = compType;
4190 return compType;
4191 }
Steve Naroff7a5af782007-07-13 16:58:59 +00004192
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004193 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00004194
Steve Naroffe4718892007-04-27 18:30:00 +00004195 // handle the common case first (both operands are arithmetic).
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004196 if (lex->getType()->isArithmeticType() &&
4197 rex->getType()->isArithmeticType()) {
4198 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004199 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004200 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00004201
Eli Friedman8e122982008-05-18 18:08:51 +00004202 // Put any potential pointer into PExp
4203 Expr* PExp = lex, *IExp = rex;
Steve Naroff6b712a72009-07-14 18:25:06 +00004204 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00004205 std::swap(PExp, IExp);
4206
Steve Naroff6b712a72009-07-14 18:25:06 +00004207 if (PExp->getType()->isAnyPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00004208
Eli Friedman8e122982008-05-18 18:08:51 +00004209 if (IExp->getType()->isIntegerType()) {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004210 QualType PointeeTy = PExp->getType()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004211
Chris Lattner12bdebb2009-04-24 23:50:08 +00004212 // Check for arithmetic on pointers to incomplete types.
4213 if (PointeeTy->isVoidType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004214 if (getLangOptions().CPlusPlus) {
4215 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner3b054132008-11-19 05:08:23 +00004216 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregordd430f72009-01-19 19:26:10 +00004217 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00004218 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004219
4220 // GNU extension: arithmetic on pointer to void
4221 Diag(Loc, diag::ext_gnu_void_ptr)
4222 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner12bdebb2009-04-24 23:50:08 +00004223 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorac1fb652009-03-24 19:52:54 +00004224 if (getLangOptions().CPlusPlus) {
4225 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4226 << lex->getType() << lex->getSourceRange();
4227 return QualType();
4228 }
4229
4230 // GNU extension: arithmetic on pointer to function
4231 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4232 << lex->getType() << lex->getSourceRange();
Steve Naroffa63372d2009-07-13 21:32:29 +00004233 } else {
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004234 // Check if we require a complete type.
Mike Stump11289f42009-09-09 15:08:12 +00004235 if (((PExp->getType()->isPointerType() &&
Steve Naroffa63372d2009-07-13 21:32:29 +00004236 !PExp->getType()->isDependentType()) ||
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004237 PExp->getType()->isObjCObjectPointerType()) &&
4238 RequireCompleteType(Loc, PointeeTy,
Mike Stump11289f42009-09-09 15:08:12 +00004239 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4240 << PExp->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004241 << PExp->getType()))
Steve Naroffaacd4cc2009-07-13 21:20:41 +00004242 return QualType();
4243 }
Chris Lattner12bdebb2009-04-24 23:50:08 +00004244 // Diagnose bad cases where we step over interface counts.
4245 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4246 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4247 << PointeeTy << PExp->getSourceRange();
4248 return QualType();
4249 }
Mike Stump11289f42009-09-09 15:08:12 +00004250
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004251 if (CompLHSTy) {
Eli Friedman629ffb92009-08-20 04:21:42 +00004252 QualType LHSTy = Context.isPromotableBitField(lex);
4253 if (LHSTy.isNull()) {
4254 LHSTy = lex->getType();
4255 if (LHSTy->isPromotableIntegerType())
4256 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004257 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004258 *CompLHSTy = LHSTy;
4259 }
Eli Friedman8e122982008-05-18 18:08:51 +00004260 return PExp->getType();
4261 }
4262 }
4263
Chris Lattner326f7572008-11-18 01:30:42 +00004264 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004265}
4266
Chris Lattner2a3569b2008-04-07 05:30:13 +00004267// C99 6.5.6
4268QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004269 SourceLocation Loc, QualType* CompLHSTy) {
4270 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4271 QualType compType = CheckVectorOperands(Loc, lex, rex);
4272 if (CompLHSTy) *CompLHSTy = compType;
4273 return compType;
4274 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004275
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004276 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004277
Chris Lattner4d62f422007-12-09 21:53:25 +00004278 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00004279
Chris Lattner4d62f422007-12-09 21:53:25 +00004280 // Handle the common case first (both operands are arithmetic).
Mike Stumpf70bcf72009-05-07 18:43:07 +00004281 if (lex->getType()->isArithmeticType()
4282 && rex->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004283 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004284 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004285 }
Mike Stump11289f42009-09-09 15:08:12 +00004286
Chris Lattner4d62f422007-12-09 21:53:25 +00004287 // Either ptr - int or ptr - ptr.
Steve Naroff6b712a72009-07-14 18:25:06 +00004288 if (lex->getType()->isAnyPointerType()) {
Steve Naroff4eed7a12009-07-13 17:19:15 +00004289 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004290
Douglas Gregorac1fb652009-03-24 19:52:54 +00004291 // The LHS must be an completely-defined object type.
Douglas Gregorf6cd9282009-01-23 00:36:41 +00004292
Douglas Gregorac1fb652009-03-24 19:52:54 +00004293 bool ComplainAboutVoid = false;
4294 Expr *ComplainAboutFunc = 0;
4295 if (lpointee->isVoidType()) {
4296 if (getLangOptions().CPlusPlus) {
4297 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4298 << lex->getSourceRange() << rex->getSourceRange();
4299 return QualType();
4300 }
4301
4302 // GNU C extension: arithmetic on pointer to void
4303 ComplainAboutVoid = true;
4304 } else if (lpointee->isFunctionType()) {
4305 if (getLangOptions().CPlusPlus) {
4306 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004307 << lex->getType() << lex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004308 return QualType();
4309 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004310
4311 // GNU C extension: arithmetic on pointer to function
4312 ComplainAboutFunc = lex;
4313 } else if (!lpointee->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00004314 RequireCompleteType(Loc, lpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004315 PDiag(diag::err_typecheck_sub_ptr_object)
Mike Stump11289f42009-09-09 15:08:12 +00004316 << lex->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00004317 << lex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004318 return QualType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004319
Chris Lattner12bdebb2009-04-24 23:50:08 +00004320 // Diagnose bad cases where we step over interface counts.
4321 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4322 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4323 << lpointee << lex->getSourceRange();
4324 return QualType();
4325 }
Mike Stump11289f42009-09-09 15:08:12 +00004326
Chris Lattner4d62f422007-12-09 21:53:25 +00004327 // The result type of a pointer-int computation is the pointer type.
Douglas Gregorac1fb652009-03-24 19:52:54 +00004328 if (rex->getType()->isIntegerType()) {
4329 if (ComplainAboutVoid)
4330 Diag(Loc, diag::ext_gnu_void_ptr)
4331 << lex->getSourceRange() << rex->getSourceRange();
4332 if (ComplainAboutFunc)
4333 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004334 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004335 << ComplainAboutFunc->getSourceRange();
4336
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004337 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004338 return lex->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00004339 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004340
Chris Lattner4d62f422007-12-09 21:53:25 +00004341 // Handle pointer-pointer subtractions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004342 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00004343 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004344
Douglas Gregorac1fb652009-03-24 19:52:54 +00004345 // RHS must be a completely-type object type.
4346 // Handle the GNU void* extension.
4347 if (rpointee->isVoidType()) {
4348 if (getLangOptions().CPlusPlus) {
4349 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4350 << lex->getSourceRange() << rex->getSourceRange();
4351 return QualType();
4352 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004353
Douglas Gregorac1fb652009-03-24 19:52:54 +00004354 ComplainAboutVoid = true;
4355 } else if (rpointee->isFunctionType()) {
4356 if (getLangOptions().CPlusPlus) {
4357 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004358 << rex->getType() << rex->getSourceRange();
Chris Lattner4d62f422007-12-09 21:53:25 +00004359 return QualType();
4360 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004361
4362 // GNU extension: arithmetic on pointer to function
4363 if (!ComplainAboutFunc)
4364 ComplainAboutFunc = rex;
4365 } else if (!rpointee->isDependentType() &&
4366 RequireCompleteType(Loc, rpointee,
Anders Carlsson029fc692009-08-26 22:59:12 +00004367 PDiag(diag::err_typecheck_sub_ptr_object)
4368 << rex->getSourceRange()
4369 << rex->getType()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00004370 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004371
Eli Friedman168fe152009-05-16 13:54:38 +00004372 if (getLangOptions().CPlusPlus) {
4373 // Pointee types must be the same: C++ [expr.add]
4374 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4375 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4376 << lex->getType() << rex->getType()
4377 << lex->getSourceRange() << rex->getSourceRange();
4378 return QualType();
4379 }
4380 } else {
4381 // Pointee types must be compatible C99 6.5.6p3
4382 if (!Context.typesAreCompatible(
4383 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4384 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4385 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4386 << lex->getType() << rex->getType()
4387 << lex->getSourceRange() << rex->getSourceRange();
4388 return QualType();
4389 }
Chris Lattner4d62f422007-12-09 21:53:25 +00004390 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004391
Douglas Gregorac1fb652009-03-24 19:52:54 +00004392 if (ComplainAboutVoid)
4393 Diag(Loc, diag::ext_gnu_void_ptr)
4394 << lex->getSourceRange() << rex->getSourceRange();
4395 if (ComplainAboutFunc)
4396 Diag(Loc, diag::ext_gnu_ptr_func_arith)
Mike Stump11289f42009-09-09 15:08:12 +00004397 << ComplainAboutFunc->getType()
Douglas Gregorac1fb652009-03-24 19:52:54 +00004398 << ComplainAboutFunc->getSourceRange();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004399
4400 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00004401 return Context.getPointerDiffType();
4402 }
4403 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004404
Chris Lattner326f7572008-11-18 01:30:42 +00004405 return InvalidOperands(Loc, lex, rex);
Steve Naroff218bc2b2007-05-04 21:54:46 +00004406}
4407
Chris Lattner2a3569b2008-04-07 05:30:13 +00004408// C99 6.5.7
Chris Lattner326f7572008-11-18 01:30:42 +00004409QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattner2a3569b2008-04-07 05:30:13 +00004410 bool isCompAssign) {
Chris Lattner5c11c412007-12-12 05:47:28 +00004411 // C99 6.5.7p2: Each of the operands shall have integer type.
4412 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner326f7572008-11-18 01:30:42 +00004413 return InvalidOperands(Loc, lex, rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004414
Chris Lattner5c11c412007-12-12 05:47:28 +00004415 // Shifts don't perform usual arithmetic conversions, they just do integer
4416 // promotions on each operand. C99 6.5.7p3
Eli Friedman629ffb92009-08-20 04:21:42 +00004417 QualType LHSTy = Context.isPromotableBitField(lex);
4418 if (LHSTy.isNull()) {
4419 LHSTy = lex->getType();
4420 if (LHSTy->isPromotableIntegerType())
4421 LHSTy = Context.getPromotedIntegerType(LHSTy);
Douglas Gregord2c2d172009-05-02 00:36:19 +00004422 }
Chris Lattner3c133402007-12-13 07:28:16 +00004423 if (!isCompAssign)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004424 ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004425
Chris Lattner5c11c412007-12-12 05:47:28 +00004426 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004427
Ryan Flynnf53fab82009-08-07 16:20:20 +00004428 // Sanity-check shift operands
4429 llvm::APSInt Right;
4430 // Check right/shifter operand
Daniel Dunbar687fa862009-09-17 06:31:27 +00004431 if (!rex->isValueDependent() &&
4432 rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynn2f085712009-08-08 19:18:23 +00004433 if (Right.isNegative())
Ryan Flynnf53fab82009-08-07 16:20:20 +00004434 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4435 else {
4436 llvm::APInt LeftBits(Right.getBitWidth(),
4437 Context.getTypeSize(lex->getType()));
4438 if (Right.uge(LeftBits))
4439 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4440 }
4441 }
4442
Chris Lattner5c11c412007-12-12 05:47:28 +00004443 // "The type of the result is that of the promoted left operand."
Eli Friedman8b7b1b12009-03-28 01:22:36 +00004444 return LHSTy;
Steve Naroff26c8ea52007-03-21 21:08:52 +00004445}
4446
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004447// C99 6.5.8, C++ [expr.rel]
Chris Lattner326f7572008-11-18 01:30:42 +00004448QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004449 unsigned OpaqueOpc, bool isRelational) {
4450 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4451
Nate Begeman191a6b12008-07-14 18:02:46 +00004452 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004453 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004454
Chris Lattnerb620c342007-08-26 01:18:55 +00004455 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroff47fea352007-08-10 18:26:40 +00004456 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4457 UsualArithmeticConversions(lex, rex);
4458 else {
4459 UsualUnaryConversions(lex);
4460 UsualUnaryConversions(rex);
4461 }
Steve Naroff31090012007-07-16 21:54:35 +00004462 QualType lType = lex->getType();
4463 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004464
Mike Stumpf70bcf72009-05-07 18:43:07 +00004465 if (!lType->isFloatingType()
4466 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00004467 // For non-floating point types, check for self-comparisons of the form
4468 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4469 // often indicate logic errors in the program.
Mike Stump11289f42009-09-09 15:08:12 +00004470 // NOTE: Don't warn about comparisons of enum constants. These can arise
Ted Kremenekde9e9682009-03-20 19:57:37 +00004471 // from macro expansions, and are usually quite deliberate.
Chris Lattner222b8bd2009-03-08 19:39:53 +00004472 Expr *LHSStripped = lex->IgnoreParens();
4473 Expr *RHSStripped = rex->IgnoreParens();
4474 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4475 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenek9ffbe412009-03-20 18:35:45 +00004476 if (DRL->getDecl() == DRR->getDecl() &&
4477 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump4e1f26a2009-02-19 03:04:26 +00004478 Diag(Loc, diag::warn_selfcomparison);
Mike Stump11289f42009-09-09 15:08:12 +00004479
Chris Lattner222b8bd2009-03-08 19:39:53 +00004480 if (isa<CastExpr>(LHSStripped))
4481 LHSStripped = LHSStripped->IgnoreParenCasts();
4482 if (isa<CastExpr>(RHSStripped))
4483 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00004484
Chris Lattner222b8bd2009-03-08 19:39:53 +00004485 // Warn about comparisons against a string constant (unless the other
4486 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004487 Expr *literalString = 0;
4488 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00004489 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004490 !RHSStripped->isNullPointerConstant(Context,
4491 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004492 literalString = lex;
4493 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00004494 } else if ((isa<StringLiteral>(RHSStripped) ||
4495 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor56751b52009-09-25 04:25:58 +00004496 !LHSStripped->isNullPointerConstant(Context,
4497 Expr::NPC_ValueDependentIsNull)) {
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004498 literalString = rex;
4499 literalStringStripped = RHSStripped;
4500 }
4501
4502 if (literalString) {
4503 std::string resultComparison;
4504 switch (Opc) {
4505 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4506 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4507 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4508 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4509 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4510 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4511 default: assert(false && "Invalid comparison operator");
4512 }
4513 Diag(Loc, diag::warn_stringcompare)
4514 << isa<ObjCEncodeExpr>(literalStringStripped)
4515 << literalString->getSourceRange()
Douglas Gregor170512f2009-04-01 23:51:29 +00004516 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4517 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4518 "strcmp(")
4519 << CodeModificationHint::CreateInsertion(
4520 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor7a5bc762009-04-06 18:45:53 +00004521 resultComparison);
4522 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00004523 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004524
Douglas Gregorca63811b2008-11-19 03:25:36 +00004525 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner222b8bd2009-03-08 19:39:53 +00004526 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregorca63811b2008-11-19 03:25:36 +00004527
Chris Lattnerb620c342007-08-26 01:18:55 +00004528 if (isRelational) {
4529 if (lType->isRealType() && rType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00004530 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00004531 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00004532 // Check for comparisons of floating point operands using != and ==.
Ted Kremeneke2763b02007-10-29 17:13:39 +00004533 if (lType->isFloatingType()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00004534 assert(rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00004535 CheckFloatComparison(Loc,lex,rex);
Ted Kremenekd4ecc6d2007-10-29 16:40:01 +00004536 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004537
Chris Lattnerb620c342007-08-26 01:18:55 +00004538 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00004539 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00004540 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004541
Douglas Gregor56751b52009-09-25 04:25:58 +00004542 bool LHSIsNull = lex->isNullPointerConstant(Context,
4543 Expr::NPC_ValueDependentIsNull);
4544 bool RHSIsNull = rex->isNullPointerConstant(Context,
4545 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004546
Chris Lattnerb620c342007-08-26 01:18:55 +00004547 // All of the following pointer related warnings are GCC extensions, except
4548 // when handling null pointer constants. One day, we can consider making them
4549 // errors (when -pedantic-errors is enabled).
Steve Naroff808eb8f2007-08-27 04:08:11 +00004550 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00004551 QualType LCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004552 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner3a0702e2008-04-03 05:07:25 +00004553 QualType RCanPointeeTy =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004554 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00004555
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004556 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00004557 if (LCanPointeeTy == RCanPointeeTy)
4558 return ResultTy;
4559
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004560 // C++ [expr.rel]p2:
4561 // [...] Pointer conversions (4.10) and qualification
4562 // conversions (4.4) are performed on pointer operands (or on
4563 // a pointer operand and a null pointer constant) to bring
4564 // them to their composite pointer type. [...]
4565 //
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004566 // C++ [expr.eq]p1 uses the same notion for (in)equality
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004567 // comparisons of pointers.
Douglas Gregorb8420462009-05-05 04:50:50 +00004568 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004569 if (T.isNull()) {
4570 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4571 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4572 return QualType();
4573 }
4574
Eli Friedman06ed2a52009-10-20 08:27:19 +00004575 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4576 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00004577 return ResultTy;
4578 }
Eli Friedman16c209612009-08-23 00:27:47 +00004579 // C99 6.5.9p2 and C99 6.5.8p2
4580 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4581 RCanPointeeTy.getUnqualifiedType())) {
4582 // Valid unless a relational comparison of function pointers
4583 if (isRelational && LCanPointeeTy->isFunctionType()) {
4584 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4585 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4586 }
4587 } else if (!isRelational &&
4588 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4589 // Valid unless comparison between non-null pointer and function pointer
4590 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4591 && !LHSIsNull && !RHSIsNull) {
4592 Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4593 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4594 }
4595 } else {
4596 // Invalid
Chris Lattner377d1f82008-11-18 22:52:51 +00004597 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004598 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff75c17232007-06-13 21:41:08 +00004599 }
Eli Friedman16c209612009-08-23 00:27:47 +00004600 if (LCanPointeeTy != RCanPointeeTy)
Eli Friedman06ed2a52009-10-20 08:27:19 +00004601 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004602 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00004603 }
Mike Stump11289f42009-09-09 15:08:12 +00004604
Sebastian Redl576fd422009-05-10 18:38:11 +00004605 if (getLangOptions().CPlusPlus) {
Mike Stump11289f42009-09-09 15:08:12 +00004606 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004607 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00004608 if (RHSIsNull &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004609 (lType->isPointerType() ||
4610 (!isRelational && lType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00004611 ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00004612 return ResultTy;
4613 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004614 if (LHSIsNull &&
4615 (rType->isPointerType() ||
4616 (!isRelational && rType->isMemberPointerType()))) {
Anders Carlsson83133d92009-08-24 18:03:14 +00004617 ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00004618 return ResultTy;
4619 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004620
4621 // Comparison of member pointers.
Mike Stump11289f42009-09-09 15:08:12 +00004622 if (!isRelational &&
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004623 lType->isMemberPointerType() && rType->isMemberPointerType()) {
4624 // C++ [expr.eq]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004625 // In addition, pointers to members can be compared, or a pointer to
4626 // member and a null pointer constant. Pointer to member conversions
4627 // (4.11) and qualification conversions (4.4) are performed to bring
4628 // them to a common type. If one operand is a null pointer constant,
4629 // the common type is the type of the other operand. Otherwise, the
4630 // common type is a pointer to member type similar (4.4) to the type
4631 // of one of the operands, with a cv-qualification signature (4.4)
4632 // that is the union of the cv-qualification signatures of the operand
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004633 // types.
4634 QualType T = FindCompositePointerType(lex, rex);
4635 if (T.isNull()) {
4636 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4637 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4638 return QualType();
4639 }
Mike Stump11289f42009-09-09 15:08:12 +00004640
Eli Friedman06ed2a52009-10-20 08:27:19 +00004641 ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
4642 ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004643 return ResultTy;
4644 }
Mike Stump11289f42009-09-09 15:08:12 +00004645
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004646 // Comparison of nullptr_t with itself.
Sebastian Redl576fd422009-05-10 18:38:11 +00004647 if (lType->isNullPtrType() && rType->isNullPtrType())
4648 return ResultTy;
4649 }
Mike Stump11289f42009-09-09 15:08:12 +00004650
Steve Naroff081c7422008-09-04 15:10:53 +00004651 // Handle block pointer types.
Mike Stump1b821b42009-05-07 03:14:14 +00004652 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004653 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4654 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004655
Steve Naroff081c7422008-09-04 15:10:53 +00004656 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00004657 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004658 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004659 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00004660 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004661 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004662 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00004663 }
Steve Naroffe18f94c2008-09-28 01:11:11 +00004664 // Allow block pointers to be compared with null pointer constants.
Mike Stump1b821b42009-05-07 03:14:14 +00004665 if (!isRelational
4666 && ((lType->isBlockPointerType() && rType->isPointerType())
4667 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00004668 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004669 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00004670 ->getPointeeType()->isVoidType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004671 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00004672 ->getPointeeType()->isVoidType())))
4673 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4674 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00004675 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004676 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004677 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00004678 }
Steve Naroff081c7422008-09-04 15:10:53 +00004679
Steve Naroff7cae42b2009-07-10 23:34:53 +00004680 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff1d4a9a32008-10-27 10:33:19 +00004681 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004682 const PointerType *LPT = lType->getAs<PointerType>();
4683 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004684 bool LPtrToVoid = LPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00004685 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004686 bool RPtrToVoid = RPT ?
Steve Naroff753567f2008-11-17 19:49:16 +00004687 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004688
Steve Naroff753567f2008-11-17 19:49:16 +00004689 if (!LPtrToVoid && !RPtrToVoid &&
4690 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00004691 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004692 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff1d4a9a32008-10-27 10:33:19 +00004693 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004694 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004695 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00004696 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00004697 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00004698 if (!Context.areComparableObjCPointerTypes(lType, rType))
Steve Naroff7cae42b2009-07-10 23:34:53 +00004699 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4700 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004701 ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004702 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00004703 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00004704 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004705 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00004706 unsigned DiagID = 0;
4707 if (RHSIsNull) {
4708 if (isRelational)
4709 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4710 } else if (isRelational)
4711 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4712 else
4713 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00004714
Chris Lattnerd99bd522009-08-23 00:03:44 +00004715 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00004716 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00004717 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00004718 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004719 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004720 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00004721 }
Steve Naroff6b712a72009-07-14 18:25:06 +00004722 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00004723 unsigned DiagID = 0;
4724 if (LHSIsNull) {
4725 if (isRelational)
4726 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4727 } else if (isRelational)
4728 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4729 else
4730 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00004731
Chris Lattnerd99bd522009-08-23 00:03:44 +00004732 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00004733 Diag(Loc, DiagID)
Chris Lattnerd466ea12009-06-30 06:24:05 +00004734 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf8344db2009-08-22 18:58:31 +00004735 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004736 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004737 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00004738 }
Steve Naroff4b191572008-09-04 16:56:14 +00004739 // Handle block pointers.
Mike Stumpf70bcf72009-05-07 18:43:07 +00004740 if (!isRelational && RHSIsNull
4741 && lType->isBlockPointerType() && rType->isIntegerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004742 ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004743 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00004744 }
Mike Stumpf70bcf72009-05-07 18:43:07 +00004745 if (!isRelational && LHSIsNull
4746 && lType->isIntegerType() && rType->isBlockPointerType()) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004747 ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00004748 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00004749 }
Chris Lattner326f7572008-11-18 01:30:42 +00004750 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004751}
4752
Nate Begeman191a6b12008-07-14 18:02:46 +00004753/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00004754/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00004755/// like a scalar comparison, a vector comparison produces a vector of integer
4756/// types.
4757QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner326f7572008-11-18 01:30:42 +00004758 SourceLocation Loc,
Nate Begeman191a6b12008-07-14 18:02:46 +00004759 bool isRelational) {
4760 // Check to make sure we're operating on vectors of the same type and width,
4761 // Allowing one side to be a scalar of element type.
Chris Lattner326f7572008-11-18 01:30:42 +00004762 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00004763 if (vType.isNull())
4764 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004765
Nate Begeman191a6b12008-07-14 18:02:46 +00004766 QualType lType = lex->getType();
4767 QualType rType = rex->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004768
Nate Begeman191a6b12008-07-14 18:02:46 +00004769 // For non-floating point types, check for self-comparisons of the form
4770 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4771 // often indicate logic errors in the program.
4772 if (!lType->isFloatingType()) {
4773 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4774 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4775 if (DRL->getDecl() == DRR->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004776 Diag(Loc, diag::warn_selfcomparison);
Nate Begeman191a6b12008-07-14 18:02:46 +00004777 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004778
Nate Begeman191a6b12008-07-14 18:02:46 +00004779 // Check for comparisons of floating point operands using != and ==.
4780 if (!isRelational && lType->isFloatingType()) {
4781 assert (rType->isFloatingType());
Chris Lattner326f7572008-11-18 01:30:42 +00004782 CheckFloatComparison(Loc,lex,rex);
Nate Begeman191a6b12008-07-14 18:02:46 +00004783 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004784
Nate Begeman191a6b12008-07-14 18:02:46 +00004785 // Return the type for the comparison, which is the same as vector type for
4786 // integer vectors, or an integer type of identical size and number of
4787 // elements for floating point vectors.
4788 if (lType->isIntegerType())
4789 return lType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004790
John McCall9dd450b2009-09-21 23:43:11 +00004791 const VectorType *VTy = lType->getAs<VectorType>();
Nate Begeman191a6b12008-07-14 18:02:46 +00004792 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004793 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begeman191a6b12008-07-14 18:02:46 +00004794 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner5d688962009-03-31 07:46:52 +00004795 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004796 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4797
Mike Stump4e1f26a2009-02-19 03:04:26 +00004798 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00004799 "Unhandled vector element size in vector compare");
Nate Begeman191a6b12008-07-14 18:02:46 +00004800 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4801}
4802
Steve Naroff218bc2b2007-05-04 21:54:46 +00004803inline QualType Sema::CheckBitwiseOperands(
Mike Stump11289f42009-09-09 15:08:12 +00004804 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
Steve Naroff94a5aca2007-07-16 22:23:01 +00004805 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner326f7572008-11-18 01:30:42 +00004806 return CheckVectorOperands(Loc, lex, rex);
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00004807
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004808 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004809
Steve Naroffdbd9e892007-07-17 00:58:39 +00004810 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00004811 return compType;
Chris Lattner326f7572008-11-18 01:30:42 +00004812 return InvalidOperands(Loc, lex, rex);
Steve Naroff26c8ea52007-03-21 21:08:52 +00004813}
4814
Steve Naroff218bc2b2007-05-04 21:54:46 +00004815inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump11289f42009-09-09 15:08:12 +00004816 Expr *&lex, Expr *&rex, SourceLocation Loc) {
Steve Naroff31090012007-07-16 21:54:35 +00004817 UsualUnaryConversions(lex);
4818 UsualUnaryConversions(rex);
Mike Stump4e1f26a2009-02-19 03:04:26 +00004819
Anders Carlsson35a99d92009-10-16 01:44:21 +00004820 if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
4821 return InvalidOperands(Loc, lex, rex);
4822
4823 if (Context.getLangOptions().CPlusPlus) {
4824 // C++ [expr.log.and]p2
4825 // C++ [expr.log.or]p2
4826 return Context.BoolTy;
4827 }
4828
4829 return Context.IntTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00004830}
4831
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004832/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4833/// is a read-only property; return true if so. A readonly property expression
4834/// depends on various declarations and thus must be treated specially.
4835///
Mike Stump11289f42009-09-09 15:08:12 +00004836static bool IsReadonlyProperty(Expr *E, Sema &S) {
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004837 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4838 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4839 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4840 QualType BaseType = PropExpr->getBase()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004841 if (const ObjCObjectPointerType *OPT =
Steve Naroff7cae42b2009-07-10 23:34:53 +00004842 BaseType->getAsObjCInterfacePointerType())
4843 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4844 if (S.isPropertyReadonly(PDecl, IFace))
4845 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004846 }
4847 }
4848 return false;
4849}
4850
Chris Lattner30bd3272008-11-18 01:22:49 +00004851/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4852/// emit an error and return true. If so, return false.
4853static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004854 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00004855 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004856 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00004857 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4858 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner30bd3272008-11-18 01:22:49 +00004859 if (IsLV == Expr::MLV_Valid)
4860 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004861
Chris Lattner30bd3272008-11-18 01:22:49 +00004862 unsigned Diag = 0;
4863 bool NeedType = false;
4864 switch (IsLV) { // C99 6.5.16p2
4865 default: assert(0 && "Unknown result from isModifiableLvalue!");
4866 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004867 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00004868 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4869 NeedType = true;
4870 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004871 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00004872 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4873 NeedType = true;
4874 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00004875 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00004876 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4877 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00004878 case Expr::MLV_InvalidExpression:
Chris Lattner30bd3272008-11-18 01:22:49 +00004879 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4880 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00004881 case Expr::MLV_IncompleteType:
4882 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00004883 return S.RequireCompleteType(Loc, E->getType(),
Anders Carlssond624e162009-08-26 23:45:07 +00004884 PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4885 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00004886 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00004887 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4888 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00004889 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00004890 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4891 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00004892 case Expr::MLV_ReadonlyProperty:
4893 Diag = diag::error_readonly_property_assignment;
4894 break;
Fariborz Jahanian5118c412008-11-22 20:25:50 +00004895 case Expr::MLV_NoSetterProperty:
4896 Diag = diag::error_nosetter_property_assignment;
4897 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00004898 }
Steve Naroffad373bd2007-07-31 12:34:36 +00004899
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004900 SourceRange Assign;
4901 if (Loc != OrigLoc)
4902 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00004903 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00004904 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00004905 else
Mike Stump11289f42009-09-09 15:08:12 +00004906 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00004907 return true;
4908}
4909
4910
4911
4912// C99 6.5.16.1
Chris Lattner326f7572008-11-18 01:30:42 +00004913QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4914 SourceLocation Loc,
4915 QualType CompoundType) {
4916 // Verify that LHS is a modifiable lvalue, and emit error if not.
4917 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00004918 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00004919
4920 QualType LHSType = LHS->getType();
4921 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004922
Chris Lattner9bad62c2008-01-04 18:04:52 +00004923 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00004924 if (CompoundType.isNull()) {
Chris Lattnerea714382008-08-21 18:04:13 +00004925 // Simple assignment "x = y".
Chris Lattner326f7572008-11-18 01:30:42 +00004926 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004927 // Special case of NSObject attributes on c-style pointer types.
4928 if (ConvTy == IncompatiblePointer &&
4929 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00004930 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004931 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00004932 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00004933 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004934
Chris Lattnerea714382008-08-21 18:04:13 +00004935 // If the RHS is a unary plus or minus, check to see if they = and + are
4936 // right next to each other. If so, the user may have typo'd "x =+ 4"
4937 // instead of "x += 4".
Chris Lattner326f7572008-11-18 01:30:42 +00004938 Expr *RHSCheck = RHS;
Chris Lattnerea714382008-08-21 18:04:13 +00004939 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4940 RHSCheck = ICE->getSubExpr();
4941 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4942 if ((UO->getOpcode() == UnaryOperator::Plus ||
4943 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00004944 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00004945 // Only if the two operators are exactly adjacent.
Chris Lattner36c39c92009-03-08 06:51:10 +00004946 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4947 // And there is a space or other character before the subexpr of the
4948 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnered9f14c2009-03-09 07:11:10 +00004949 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4950 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00004951 Diag(Loc, diag::warn_not_compound_assign)
4952 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4953 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00004954 }
Chris Lattnerea714382008-08-21 18:04:13 +00004955 }
4956 } else {
4957 // Compound assignment "x += y"
Eli Friedmanb05c41e2009-05-16 05:56:02 +00004958 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00004959 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00004960
Chris Lattner326f7572008-11-18 01:30:42 +00004961 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4962 RHS, "assigning"))
Chris Lattner9bad62c2008-01-04 18:04:52 +00004963 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004964
Steve Naroff98cf3e92007-06-06 18:38:38 +00004965 // C99 6.5.16p3: The type of an assignment expression is the type of the
4966 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00004967 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00004968 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4969 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00004970 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00004971 // operand.
Chris Lattner326f7572008-11-18 01:30:42 +00004972 return LHSType.getUnqualifiedType();
Steve Naroffae4143e2007-04-26 20:39:23 +00004973}
4974
Chris Lattner326f7572008-11-18 01:30:42 +00004975// C99 6.5.17
4976QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattnerf6e1e302008-07-25 20:54:07 +00004977 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner326f7572008-11-18 01:30:42 +00004978 DefaultFunctionArrayConversion(RHS);
Eli Friedmanba961a92009-03-23 00:24:07 +00004979
4980 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4981 // incomplete in C++).
4982
Chris Lattner326f7572008-11-18 01:30:42 +00004983 return RHS->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00004984}
4985
Steve Naroff7a5af782007-07-13 16:58:59 +00004986/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4987/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redle10c2c32008-12-20 09:35:34 +00004988QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4989 bool isInc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00004990 if (Op->isTypeDependent())
4991 return Context.DependentTy;
4992
Chris Lattner6b0cf142008-11-21 07:05:48 +00004993 QualType ResType = Op->getType();
4994 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00004995
Sebastian Redle10c2c32008-12-20 09:35:34 +00004996 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4997 // Decrement of bool is not allowed.
4998 if (!isInc) {
4999 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5000 return QualType();
5001 }
5002 // Increment of bool sets it to true, but is deprecated.
5003 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5004 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00005005 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00005006 } else if (ResType->isAnyPointerType()) {
5007 QualType PointeeTy = ResType->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00005008
Chris Lattner6b0cf142008-11-21 07:05:48 +00005009 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff7cae42b2009-07-10 23:34:53 +00005010 if (PointeeTy->isVoidType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005011 if (getLangOptions().CPlusPlus) {
5012 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5013 << Op->getSourceRange();
5014 return QualType();
5015 }
5016
5017 // Pointer to void is a GNU extension in C.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005018 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005019 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorf6cd9282009-01-23 00:36:41 +00005020 if (getLangOptions().CPlusPlus) {
5021 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5022 << Op->getType() << Op->getSourceRange();
5023 return QualType();
5024 }
5025
5026 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005027 << ResType << Op->getSourceRange();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005028 } else if (RequireCompleteType(OpLoc, PointeeTy,
Anders Carlsson029fc692009-08-26 22:59:12 +00005029 PDiag(diag::err_typecheck_arithmetic_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00005030 << Op->getSourceRange()
Anders Carlsson029fc692009-08-26 22:59:12 +00005031 << ResType))
Douglas Gregordd430f72009-01-19 19:26:10 +00005032 return QualType();
Fariborz Jahanianca75db72009-07-16 17:59:14 +00005033 // Diagnose bad cases where we step over interface counts.
5034 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5035 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5036 << PointeeTy << Op->getSourceRange();
5037 return QualType();
5038 }
Chris Lattner6b0cf142008-11-21 07:05:48 +00005039 } else if (ResType->isComplexType()) {
5040 // C99 does not support ++/-- on complex types, we allow as an extension.
5041 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005042 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005043 } else {
5044 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005045 << ResType << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005046 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00005047 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005048 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00005049 // Now make sure the operand is a modifiable lvalue.
Chris Lattner6b0cf142008-11-21 07:05:48 +00005050 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Steve Naroff35d85152007-05-07 00:24:15 +00005051 return QualType();
Chris Lattner6b0cf142008-11-21 07:05:48 +00005052 return ResType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005053}
5054
Anders Carlsson806700f2008-02-01 07:15:58 +00005055/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00005056/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005057/// where the declaration is needed for type checking. We only need to
5058/// handle cases when the expression references a function designator
5059/// or is an lvalue. Here are some examples:
5060/// - &(x) => x
5061/// - &*****f => f for f a function designator.
5062/// - &s.xx => s
5063/// - &s.zz[1].yy -> s, if zz is an array
5064/// - *(x + 1) -> x, if x is an array
5065/// - &"123"[2] -> 0
5066/// - & __real__ x -> x
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005067static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005068 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00005069 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005070 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00005071 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005072 // If this is an arrow operator, the address is an offset from
5073 // the base's value, so the object the base refers to is
5074 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005075 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00005076 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00005077 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005078 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00005079 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00005080 // FIXME: This code shouldn't be necessary! We should catch the implicit
5081 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00005082 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5083 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5084 if (ICE->getSubExpr()->getType()->isArrayType())
5085 return getPrimaryDecl(ICE->getSubExpr());
5086 }
5087 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00005088 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005089 case Stmt::UnaryOperatorClass: {
5090 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005091
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005092 switch(UO->getOpcode()) {
Daniel Dunbarb692ef42008-08-04 20:02:37 +00005093 case UnaryOperator::Real:
5094 case UnaryOperator::Imag:
5095 case UnaryOperator::Extension:
5096 return getPrimaryDecl(UO->getSubExpr());
5097 default:
5098 return 0;
5099 }
5100 }
Steve Naroff47500512007-04-19 23:00:49 +00005101 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005102 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00005103 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00005104 // If the result of an implicit cast is an l-value, we care about
5105 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00005106 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00005107 default:
5108 return 0;
5109 }
5110}
5111
5112/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00005113/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00005114/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005115/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00005116/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005117/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00005118/// we allow the '&' but retain the overloaded-function type.
Steve Naroff35d85152007-05-07 00:24:15 +00005119QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00005120 // Make sure to ignore parentheses in subsequent checks
5121 op = op->IgnoreParens();
5122
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00005123 if (op->isTypeDependent())
5124 return Context.DependentTy;
5125
Steve Naroff826e91a2008-01-13 17:10:08 +00005126 if (getLangOptions().C99) {
5127 // Implement C99-only parts of addressof rules.
5128 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5129 if (uOp->getOpcode() == UnaryOperator::Deref)
5130 // Per C99 6.5.3.2, the address of a deref always returns a valid result
5131 // (assuming the deref expression is valid).
5132 return uOp->getSubExpr()->getType();
5133 }
5134 // Technically, there should be a check for array subscript
5135 // expressions here, but the result of one is always an lvalue anyway.
5136 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005137 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner67315442008-07-26 21:30:36 +00005138 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes17f345f2008-12-16 22:59:47 +00005139
Eli Friedmance7f9002009-05-16 23:27:50 +00005140 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5141 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005142 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00005143 if (!op->getType()->isFunctionType()) {
Chris Lattner48d52842007-11-16 17:46:48 +00005144 // FIXME: emit more specific diag...
Chris Lattnerf490e152008-11-19 05:27:50 +00005145 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5146 << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005147 return QualType();
5148 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00005149 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00005150 // The operand cannot be a bit-field
5151 Diag(OpLoc, diag::err_typecheck_address_of)
5152 << "bit-field" << op->getSourceRange();
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00005153 return QualType();
Nate Begemana6b47a42009-02-15 22:45:20 +00005154 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5155 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman3a1e6922009-04-20 08:23:18 +00005156 // The operand cannot be an element of a vector
Chris Lattner29e812b2008-11-20 06:06:08 +00005157 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana6b47a42009-02-15 22:45:20 +00005158 << "vector element" << op->getSourceRange();
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005159 return QualType();
Fariborz Jahanian385db802009-07-07 18:50:52 +00005160 } else if (isa<ObjCPropertyRefExpr>(op)) {
5161 // cannot take address of a property expression.
5162 Diag(OpLoc, diag::err_typecheck_address_of)
5163 << "property expression" << op->getSourceRange();
5164 return QualType();
Anders Carlsson3fa58d12009-09-14 23:15:26 +00005165 } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5166 // FIXME: Can LHS ever be null here?
Anders Carlsson01ccf992009-09-15 16:03:44 +00005167 if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5168 return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
Steve Naroffb96e4ab62008-02-29 23:30:25 +00005169 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00005170 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00005171 // with the register storage-class specifier.
5172 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Steve Naroff35d85152007-05-07 00:24:15 +00005173 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner29e812b2008-11-20 06:06:08 +00005174 Diag(OpLoc, diag::err_typecheck_address_of)
5175 << "register variable" << op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005176 return QualType();
5177 }
Douglas Gregor9b146582009-07-08 20:55:45 +00005178 } else if (isa<OverloadedFunctionDecl>(dcl) ||
5179 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005180 return Context.OverloadTy;
Anders Carlsson0b675f52009-07-08 21:45:58 +00005181 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00005182 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005183 // Could be a pointer to member, though, if there is an explicit
5184 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005185 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005186 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00005187 if (Ctx && Ctx->isRecord()) {
5188 if (FD->getType()->isReferenceType()) {
Mike Stump11289f42009-09-09 15:08:12 +00005189 Diag(OpLoc,
Anders Carlsson0b675f52009-07-08 21:45:58 +00005190 diag::err_cannot_form_pointer_to_member_of_reference_type)
5191 << FD->getDeclName() << FD->getType();
5192 return QualType();
5193 }
Mike Stump11289f42009-09-09 15:08:12 +00005194
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005195 return Context.getMemberPointerType(op->getType(),
5196 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00005197 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00005198 }
Anders Carlsson5b535762009-05-16 21:43:42 +00005199 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopes5773a1b2008-12-16 22:58:26 +00005200 // Okay: we can take the address of a function.
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005201 // As above.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005202 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
5203 MD->isInstance())
Anders Carlsson5b535762009-05-16 21:43:42 +00005204 return Context.getMemberPointerType(op->getType(),
5205 Context.getTypeDeclType(MD->getParent()).getTypePtr());
5206 } else if (!isa<FunctionDecl>(dcl))
Steve Narofff633d092007-04-25 19:01:39 +00005207 assert(0 && "Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00005208 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005209
Eli Friedmance7f9002009-05-16 23:27:50 +00005210 if (lval == Expr::LV_IncompleteVoidType) {
5211 // Taking the address of a void variable is technically illegal, but we
5212 // allow it in cases which are otherwise valid.
5213 // Example: "extern void x; void* y = &x;".
5214 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5215 }
5216
Steve Naroff47500512007-04-19 23:00:49 +00005217 // If the operand has type "type", the result has type "pointer to type".
Steve Naroff35d85152007-05-07 00:24:15 +00005218 return Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00005219}
5220
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005221QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005222 if (Op->isTypeDependent())
5223 return Context.DependentTy;
5224
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005225 UsualUnaryConversions(Op);
5226 QualType Ty = Op->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005227
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005228 // Note that per both C89 and C99, this is always legal, even if ptype is an
5229 // incomplete type or void. It would be possible to warn about dereferencing
5230 // a void pointer, but it's completely well-defined, and such a warning is
5231 // unlikely to catch any mistakes.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005232 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff826e91a2008-01-13 17:10:08 +00005233 return PT->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005234
John McCall9dd450b2009-09-21 23:43:11 +00005235 if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
Fariborz Jahanianf15d4b62009-09-03 00:43:07 +00005236 return OPT->getPointeeType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00005237
Chris Lattner29e812b2008-11-20 06:06:08 +00005238 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner6a2ed6f2008-11-23 09:13:29 +00005239 << Ty << Op->getSourceRange();
Steve Naroff35d85152007-05-07 00:24:15 +00005240 return QualType();
Steve Naroff1926c832007-04-24 00:23:05 +00005241}
Steve Naroff218bc2b2007-05-04 21:54:46 +00005242
5243static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5244 tok::TokenKind Kind) {
5245 BinaryOperator::Opcode Opc;
5246 switch (Kind) {
5247 default: assert(0 && "Unknown binop!");
Sebastian Redl112a97662009-02-07 00:15:38 +00005248 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5249 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005250 case tok::star: Opc = BinaryOperator::Mul; break;
5251 case tok::slash: Opc = BinaryOperator::Div; break;
5252 case tok::percent: Opc = BinaryOperator::Rem; break;
5253 case tok::plus: Opc = BinaryOperator::Add; break;
5254 case tok::minus: Opc = BinaryOperator::Sub; break;
5255 case tok::lessless: Opc = BinaryOperator::Shl; break;
5256 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5257 case tok::lessequal: Opc = BinaryOperator::LE; break;
5258 case tok::less: Opc = BinaryOperator::LT; break;
5259 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5260 case tok::greater: Opc = BinaryOperator::GT; break;
5261 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5262 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5263 case tok::amp: Opc = BinaryOperator::And; break;
5264 case tok::caret: Opc = BinaryOperator::Xor; break;
5265 case tok::pipe: Opc = BinaryOperator::Or; break;
5266 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5267 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5268 case tok::equal: Opc = BinaryOperator::Assign; break;
5269 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5270 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5271 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5272 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5273 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5274 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5275 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5276 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5277 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5278 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5279 case tok::comma: Opc = BinaryOperator::Comma; break;
5280 }
5281 return Opc;
5282}
5283
Steve Naroff35d85152007-05-07 00:24:15 +00005284static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5285 tok::TokenKind Kind) {
5286 UnaryOperator::Opcode Opc;
5287 switch (Kind) {
5288 default: assert(0 && "Unknown unary op!");
5289 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5290 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5291 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5292 case tok::star: Opc = UnaryOperator::Deref; break;
5293 case tok::plus: Opc = UnaryOperator::Plus; break;
5294 case tok::minus: Opc = UnaryOperator::Minus; break;
5295 case tok::tilde: Opc = UnaryOperator::Not; break;
5296 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005297 case tok::kw___real: Opc = UnaryOperator::Real; break;
5298 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
Chris Lattnerd0f76512007-06-08 22:16:53 +00005299 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00005300 }
5301 return Opc;
5302}
5303
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005304/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5305/// operator @p Opc at location @c TokLoc. This routine only supports
5306/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005307Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5308 unsigned Op,
5309 Expr *lhs, Expr *rhs) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005310 QualType ResultTy; // Result type of the binary operator.
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005311 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005312 // The following two variables are used for compound assignment operators
5313 QualType CompLHSTy; // Type of LHS after promotions for computation
5314 QualType CompResultTy; // Type of computation result
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005315
5316 switch (Opc) {
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005317 case BinaryOperator::Assign:
5318 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5319 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00005320 case BinaryOperator::PtrMemD:
5321 case BinaryOperator::PtrMemI:
5322 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5323 Opc == BinaryOperator::PtrMemI);
5324 break;
5325 case BinaryOperator::Mul:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005326 case BinaryOperator::Div:
5327 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5328 break;
5329 case BinaryOperator::Rem:
5330 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5331 break;
5332 case BinaryOperator::Add:
5333 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5334 break;
5335 case BinaryOperator::Sub:
5336 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5337 break;
Sebastian Redl112a97662009-02-07 00:15:38 +00005338 case BinaryOperator::Shl:
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005339 case BinaryOperator::Shr:
5340 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5341 break;
5342 case BinaryOperator::LE:
5343 case BinaryOperator::LT:
5344 case BinaryOperator::GE:
5345 case BinaryOperator::GT:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005346 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005347 break;
5348 case BinaryOperator::EQ:
5349 case BinaryOperator::NE:
Douglas Gregor7a5bc762009-04-06 18:45:53 +00005350 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005351 break;
5352 case BinaryOperator::And:
5353 case BinaryOperator::Xor:
5354 case BinaryOperator::Or:
5355 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5356 break;
5357 case BinaryOperator::LAnd:
5358 case BinaryOperator::LOr:
5359 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5360 break;
5361 case BinaryOperator::MulAssign:
5362 case BinaryOperator::DivAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005363 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5364 CompLHSTy = CompResultTy;
5365 if (!CompResultTy.isNull())
5366 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005367 break;
5368 case BinaryOperator::RemAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005369 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5370 CompLHSTy = CompResultTy;
5371 if (!CompResultTy.isNull())
5372 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005373 break;
5374 case BinaryOperator::AddAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005375 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5376 if (!CompResultTy.isNull())
5377 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005378 break;
5379 case BinaryOperator::SubAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005380 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5381 if (!CompResultTy.isNull())
5382 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005383 break;
5384 case BinaryOperator::ShlAssign:
5385 case BinaryOperator::ShrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005386 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5387 CompLHSTy = CompResultTy;
5388 if (!CompResultTy.isNull())
5389 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005390 break;
5391 case BinaryOperator::AndAssign:
5392 case BinaryOperator::XorAssign:
5393 case BinaryOperator::OrAssign:
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005394 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5395 CompLHSTy = CompResultTy;
5396 if (!CompResultTy.isNull())
5397 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005398 break;
5399 case BinaryOperator::Comma:
5400 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5401 break;
5402 }
5403 if (ResultTy.isNull())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005404 return ExprError();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005405 if (CompResultTy.isNull())
Steve Narofff6009ed2009-01-21 00:14:39 +00005406 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5407 else
5408 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman8b7b1b12009-03-28 01:22:36 +00005409 CompLHSTy, CompResultTy,
5410 OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005411}
5412
Steve Naroff218bc2b2007-05-04 21:54:46 +00005413// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redlb5d49352009-01-19 22:31:54 +00005414Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5415 tok::TokenKind Kind,
5416 ExprArg LHS, ExprArg RHS) {
Steve Naroff218bc2b2007-05-04 21:54:46 +00005417 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlssonb781bcd2009-05-01 19:49:17 +00005418 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Steve Naroff218bc2b2007-05-04 21:54:46 +00005419
Steve Naroff83895f72007-09-16 03:34:24 +00005420 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5421 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00005422
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005423 if (getLangOptions().CPlusPlus &&
Mike Stump11289f42009-09-09 15:08:12 +00005424 (lhs->getType()->isOverloadableType() ||
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005425 rhs->getType()->isOverloadableType())) {
5426 // Find all of the overloaded operators visible from this
5427 // point. We perform both an operator-name lookup from the local
5428 // scope and an argument-dependent lookup based on the types of
5429 // the arguments.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005430 FunctionSet Functions;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005431 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5432 if (OverOp != OO_None) {
5433 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5434 Functions);
5435 Expr *Args[2] = { lhs, rhs };
Mike Stump11289f42009-09-09 15:08:12 +00005436 DeclarationName OpName
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005437 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00005438 ArgumentDependentLookup(OpName, /*Operator*/true, Args, 2, Functions);
Douglas Gregora11693b2008-11-12 17:17:38 +00005439 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005440
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005441 // Build the (potentially-overloaded, potentially-dependent)
5442 // binary operation.
5443 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redlb5d49352009-01-19 22:31:54 +00005444 }
5445
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00005446 // Build a built-in binary operation.
5447 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Steve Naroff218bc2b2007-05-04 21:54:46 +00005448}
5449
Douglas Gregor084d8552009-03-13 23:49:33 +00005450Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00005451 unsigned OpcIn,
Douglas Gregor084d8552009-03-13 23:49:33 +00005452 ExprArg InputArg) {
5453 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregord08452f2008-11-19 15:42:04 +00005454
Mike Stump87c57ac2009-05-16 07:39:55 +00005455 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregor084d8552009-03-13 23:49:33 +00005456 Expr *Input = (Expr *)InputArg.get();
Steve Naroff35d85152007-05-07 00:24:15 +00005457 QualType resultType;
5458 switch (Opc) {
Douglas Gregor084d8552009-03-13 23:49:33 +00005459 case UnaryOperator::OffsetOf:
5460 assert(false && "Invalid unary operator");
5461 break;
5462
Steve Naroff35d85152007-05-07 00:24:15 +00005463 case UnaryOperator::PreInc:
5464 case UnaryOperator::PreDec:
Eli Friedman6aea5752009-07-22 22:25:00 +00005465 case UnaryOperator::PostInc:
5466 case UnaryOperator::PostDec:
Sebastian Redle10c2c32008-12-20 09:35:34 +00005467 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman6aea5752009-07-22 22:25:00 +00005468 Opc == UnaryOperator::PreInc ||
5469 Opc == UnaryOperator::PostInc);
Steve Naroff35d85152007-05-07 00:24:15 +00005470 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005471 case UnaryOperator::AddrOf:
Chris Lattner86554282007-06-08 22:32:33 +00005472 resultType = CheckAddressOfOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00005473 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005474 case UnaryOperator::Deref:
Steve Naroffb7235642007-12-18 04:06:57 +00005475 DefaultFunctionArrayConversion(Input);
Chris Lattner86554282007-06-08 22:32:33 +00005476 resultType = CheckIndirectionOperand(Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00005477 break;
5478 case UnaryOperator::Plus:
5479 case UnaryOperator::Minus:
Steve Naroff31090012007-07-16 21:54:35 +00005480 UsualUnaryConversions(Input);
5481 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005482 if (resultType->isDependentType())
5483 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005484 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5485 break;
5486 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5487 resultType->isEnumeralType())
5488 break;
5489 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5490 Opc == UnaryOperator::Plus &&
5491 resultType->isPointerType())
5492 break;
5493
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005494 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5495 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00005496 case UnaryOperator::Not: // bitwise complement
Steve Naroff31090012007-07-16 21:54:35 +00005497 UsualUnaryConversions(Input);
5498 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005499 if (resultType->isDependentType())
5500 break;
Chris Lattner0d707612008-07-25 23:52:49 +00005501 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5502 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5503 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00005504 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005505 << resultType << Input->getSourceRange();
Chris Lattner0d707612008-07-25 23:52:49 +00005506 else if (!resultType->isIntegerType())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005507 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5508 << resultType << Input->getSourceRange());
Steve Naroff35d85152007-05-07 00:24:15 +00005509 break;
5510 case UnaryOperator::LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00005511 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
Steve Naroff31090012007-07-16 21:54:35 +00005512 DefaultFunctionArrayConversion(Input);
5513 resultType = Input->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005514 if (resultType->isDependentType())
5515 break;
Steve Naroff35d85152007-05-07 00:24:15 +00005516 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005517 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5518 << resultType << Input->getSourceRange());
Chris Lattnerbe31ed82007-06-02 19:11:33 +00005519 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005520 // In C++, it's bool. C++ 5.3.1p8
5521 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Steve Naroff35d85152007-05-07 00:24:15 +00005522 break;
Chris Lattner30b5dd02007-08-24 21:16:53 +00005523 case UnaryOperator::Real:
Chris Lattner30b5dd02007-08-24 21:16:53 +00005524 case UnaryOperator::Imag:
Chris Lattner709322b2009-02-17 08:12:06 +00005525 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner30b5dd02007-08-24 21:16:53 +00005526 break;
Chris Lattner86554282007-06-08 22:32:33 +00005527 case UnaryOperator::Extension:
Chris Lattner86554282007-06-08 22:32:33 +00005528 resultType = Input->getType();
Steve Naroff043d45d2007-05-15 02:32:35 +00005529 break;
Steve Naroff35d85152007-05-07 00:24:15 +00005530 }
5531 if (resultType.isNull())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005532 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00005533
5534 InputArg.release();
Steve Narofff6009ed2009-01-21 00:14:39 +00005535 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00005536}
Chris Lattnereefa10e2007-05-28 06:56:27 +00005537
Douglas Gregor084d8552009-03-13 23:49:33 +00005538// Unary Operators. 'Tok' is the token for the operator.
5539Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5540 tok::TokenKind Op, ExprArg input) {
5541 Expr *Input = (Expr*)input.get();
5542 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5543
5544 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5545 // Find all of the overloaded operators visible from this
5546 // point. We perform both an operator-name lookup from the local
5547 // scope and an argument-dependent lookup based on the types of
5548 // the arguments.
5549 FunctionSet Functions;
5550 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5551 if (OverOp != OO_None) {
5552 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5553 Functions);
Mike Stump11289f42009-09-09 15:08:12 +00005554 DeclarationName OpName
Douglas Gregor084d8552009-03-13 23:49:33 +00005555 = Context.DeclarationNames.getCXXOperatorName(OverOp);
Sebastian Redlc057f422009-10-23 19:23:15 +00005556 ArgumentDependentLookup(OpName, /*Operator*/true, &Input, 1, Functions);
Douglas Gregor084d8552009-03-13 23:49:33 +00005557 }
5558
5559 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5560 }
5561
5562 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5563}
5564
Steve Naroff66356bd2007-09-16 14:56:35 +00005565/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005566Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5567 SourceLocation LabLoc,
5568 IdentifierInfo *LabelII) {
Chris Lattnereefa10e2007-05-28 06:56:27 +00005569 // Look up the record for this label identifier.
Chris Lattner3318e862009-04-18 20:01:55 +00005570 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump4e1f26a2009-02-19 03:04:26 +00005571
Daniel Dunbar88402ce2008-08-04 16:51:22 +00005572 // If we haven't seen this label yet, create a forward reference. It
5573 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroff846b1ec2009-03-13 15:38:40 +00005574 if (LabelDecl == 0)
Steve Narofff6009ed2009-01-21 00:14:39 +00005575 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005576
Chris Lattnereefa10e2007-05-28 06:56:27 +00005577 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005578 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5579 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00005580}
5581
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005582Sema::OwningExprResult
5583Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5584 SourceLocation RPLoc) { // "({..})"
5585 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner366727f2007-07-24 16:58:17 +00005586 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5587 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5588
Eli Friedman52cc0162009-01-24 23:09:00 +00005589 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattnera69b0762009-04-25 19:11:05 +00005590 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005591 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00005592
Chris Lattner366727f2007-07-24 16:58:17 +00005593 // FIXME: there are a variety of strange constraints to enforce here, for
5594 // example, it is not possible to goto into a stmt expression apparently.
5595 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00005596
Chris Lattner366727f2007-07-24 16:58:17 +00005597 // If there are sub stmts in the compound stmt, take the type of the last one
5598 // as the type of the stmtexpr.
5599 QualType Ty = Context.VoidTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005600
Chris Lattner944d3062008-07-26 19:51:01 +00005601 if (!Compound->body_empty()) {
5602 Stmt *LastStmt = Compound->body_back();
5603 // If LastStmt is a label, skip down through into the body.
5604 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5605 LastStmt = Label->getSubStmt();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005606
Chris Lattner944d3062008-07-26 19:51:01 +00005607 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner366727f2007-07-24 16:58:17 +00005608 Ty = LastExpr->getType();
Chris Lattner944d3062008-07-26 19:51:01 +00005609 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005610
Eli Friedmanba961a92009-03-23 00:24:07 +00005611 // FIXME: Check that expression type is complete/non-abstract; statement
5612 // expressions are not lvalues.
5613
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005614 substmt.release();
5615 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner366727f2007-07-24 16:58:17 +00005616}
Steve Naroff78864672007-08-01 22:05:33 +00005617
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005618Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5619 SourceLocation BuiltinLoc,
5620 SourceLocation TypeLoc,
5621 TypeTy *argty,
5622 OffsetOfComponent *CompPtr,
5623 unsigned NumComponents,
5624 SourceLocation RPLoc) {
5625 // FIXME: This function leaks all expressions in the offset components on
5626 // error.
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005627 // FIXME: Preserve type source info.
5628 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattnerf17bd422007-08-30 17:45:32 +00005629 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005630
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005631 bool Dependent = ArgTy->isDependentType();
5632
Chris Lattnerf17bd422007-08-30 17:45:32 +00005633 // We must have at least one component that refers to the type, and the first
5634 // one is known to be a field designator. Verify that the ArgTy represents
5635 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005636 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005637 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005638
Eli Friedmanba961a92009-03-23 00:24:07 +00005639 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5640 // with an incomplete type would be illegal.
Douglas Gregor26897462009-03-11 16:48:53 +00005641
Eli Friedman988a16b2009-02-27 06:44:11 +00005642 // Otherwise, create a null pointer as the base, and iteratively process
5643 // the offsetof designators.
5644 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5645 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005646 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman988a16b2009-02-27 06:44:11 +00005647 ArgTy, SourceLocation());
Eli Friedman16c88df2009-01-26 01:33:06 +00005648
Chris Lattner78502cf2007-08-31 21:49:13 +00005649 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5650 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00005651 // FIXME: This diagnostic isn't actually visible because the location is in
5652 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00005653 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00005654 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5655 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005656
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005657 if (!Dependent) {
Eli Friedman8469bc72009-05-03 21:22:18 +00005658 bool DidWarnAboutNonPOD = false;
Mike Stump11289f42009-09-09 15:08:12 +00005659
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005660 // FIXME: Dependent case loses a lot of information here. And probably
5661 // leaks like a sieve.
5662 for (unsigned i = 0; i != NumComponents; ++i) {
5663 const OffsetOfComponent &OC = CompPtr[i];
5664 if (OC.isBrackets) {
5665 // Offset of an array sub-field. TODO: Should we allow vector elements?
5666 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5667 if (!AT) {
5668 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005669 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5670 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005671 }
5672
5673 // FIXME: C++: Verify that operator[] isn't overloaded.
5674
Eli Friedman988a16b2009-02-27 06:44:11 +00005675 // Promote the array so it looks more like a normal array subscript
5676 // expression.
5677 DefaultFunctionArrayConversion(Res);
5678
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005679 // C99 6.5.2.1p1
5680 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005681 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005682 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005683 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner003af242009-04-25 22:50:55 +00005684 diag::err_typecheck_subscript_not_integer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005685 << Idx->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005686
5687 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5688 OC.LocEnd);
5689 continue;
Chris Lattnerf17bd422007-08-30 17:45:32 +00005690 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005691
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005692 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005693 if (!RC) {
5694 Res->Destroy(Context);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005695 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5696 << Res->getType());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005697 }
Chris Lattner98dbf0a2007-08-30 17:59:59 +00005698
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005699 // Get the decl corresponding to this.
5700 RecordDecl *RD = RC->getDecl();
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00005701 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00005702 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlsson8b98d022009-05-02 17:45:47 +00005703 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5704 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5705 << Res->getType());
Anders Carlsson38ebcaa2009-05-02 18:36:10 +00005706 DidWarnAboutNonPOD = true;
5707 }
Anders Carlsson2bbb86b2009-05-01 23:20:30 +00005708 }
Mike Stump11289f42009-09-09 15:08:12 +00005709
John McCall9f3059a2009-10-09 21:13:30 +00005710 LookupResult R;
5711 LookupQualifiedName(R, RD, OC.U.IdentInfo, LookupMemberName);
5712
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005713 FieldDecl *MemberDecl
John McCall9f3059a2009-10-09 21:13:30 +00005714 = dyn_cast_or_null<FieldDecl>(R.getAsSingleDecl(Context));
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005715 // FIXME: Leaks Res
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005716 if (!MemberDecl)
Douglas Gregore40876a2009-10-13 21:16:44 +00005717 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
5718 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump4e1f26a2009-02-19 03:04:26 +00005719
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005720 // FIXME: C++: Verify that MemberDecl isn't a static field.
5721 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman64fc3c62009-04-26 20:50:44 +00005722 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlsson3cbc8592009-05-01 19:30:39 +00005723 Res = BuildAnonymousStructUnionMemberReference(
5724 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman64fc3c62009-04-26 20:50:44 +00005725 } else {
5726 // MemberDecl->getType() doesn't get the right qualifiers, but it
5727 // doesn't matter here.
5728 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5729 MemberDecl->getType().getNonReferenceType());
5730 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005731 }
Chris Lattnerf17bd422007-08-30 17:45:32 +00005732 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005733
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005734 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5735 Context.getSizeType(), BuiltinLoc));
Chris Lattnerf17bd422007-08-30 17:45:32 +00005736}
5737
5738
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005739Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5740 TypeTy *arg1,TypeTy *arg2,
5741 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005742 // FIXME: Preserve type source info.
5743 QualType argT1 = GetTypeFromParser(arg1);
5744 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005745
Steve Naroff78864672007-08-01 22:05:33 +00005746 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005747
Douglas Gregorf907cbf2009-05-19 22:28:02 +00005748 if (getLangOptions().CPlusPlus) {
5749 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5750 << SourceRange(BuiltinLoc, RPLoc);
5751 return ExprError();
5752 }
5753
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005754 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5755 argT1, argT2, RPLoc));
Steve Naroff78864672007-08-01 22:05:33 +00005756}
5757
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005758Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5759 ExprArg cond,
5760 ExprArg expr1, ExprArg expr2,
5761 SourceLocation RPLoc) {
5762 Expr *CondExpr = static_cast<Expr*>(cond.get());
5763 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5764 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005765
Steve Naroff9efdabc2007-08-03 21:21:27 +00005766 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5767
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005768 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00005769 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00005770 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005771 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00005772 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005773 } else {
5774 // The conditional expression is required to be a constant expression.
5775 llvm::APSInt condEval(32);
5776 SourceLocation ExpLoc;
5777 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005778 return ExprError(Diag(ExpLoc,
5779 diag::err_typecheck_choose_expr_requires_constant)
5780 << CondExpr->getSourceRange());
Steve Naroff9efdabc2007-08-03 21:21:27 +00005781
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005782 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5783 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
Douglas Gregor56751b52009-09-25 04:25:58 +00005784 ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
5785 : RHSExpr->isValueDependent();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00005786 }
5787
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005788 cond.release(); expr1.release(); expr2.release();
5789 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
Douglas Gregor56751b52009-09-25 04:25:58 +00005790 resType, RPLoc,
5791 resType->isDependentType(),
5792 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00005793}
5794
Steve Naroffc540d662008-09-03 18:15:37 +00005795//===----------------------------------------------------------------------===//
5796// Clang Extensions.
5797//===----------------------------------------------------------------------===//
5798
5799/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005800void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroffc540d662008-09-03 18:15:37 +00005801 // Analyze block parameters.
5802 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005803
Steve Naroffc540d662008-09-03 18:15:37 +00005804 // Add BSI to CurBlock.
5805 BSI->PrevBlockInfo = CurBlock;
5806 CurBlock = BSI;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005807
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00005808 BSI->ReturnType = QualType();
Steve Naroffc540d662008-09-03 18:15:37 +00005809 BSI->TheScope = BlockScope;
Mike Stumpa6703322009-02-19 22:01:56 +00005810 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarb9a68612009-07-29 01:59:17 +00005811 BSI->hasPrototype = false;
Chris Lattner45542ea2009-04-19 05:28:12 +00005812 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5813 CurFunctionNeedsScopeChecking = false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005814
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005815 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00005816 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005817}
5818
Mike Stump82f071f2009-02-04 22:31:32 +00005819void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00005820 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stump82f071f2009-02-04 22:31:32 +00005821
5822 if (ParamInfo.getNumTypeObjects() == 0
5823 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor758a8692009-06-17 21:51:59 +00005824 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stump82f071f2009-02-04 22:31:32 +00005825 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5826
Mike Stumpd456c482009-04-28 01:10:27 +00005827 if (T->isArrayType()) {
5828 Diag(ParamInfo.getSourceRange().getBegin(),
5829 diag::err_block_returns_array);
5830 return;
5831 }
5832
Mike Stump82f071f2009-02-04 22:31:32 +00005833 // The parameter list is optional, if there was none, assume ().
5834 if (!T->isFunctionType())
5835 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5836
5837 CurBlock->hasPrototype = true;
5838 CurBlock->isVariadic = false;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00005839 // Check for a valid sentinel attribute on this block.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005840 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00005841 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00005842 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00005843 // FIXME: remove the attribute.
5844 }
John McCall9dd450b2009-09-21 23:43:11 +00005845 QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00005846
Chris Lattner6de05082009-04-11 19:27:54 +00005847 // Do not allow returning a objc interface by-value.
5848 if (RetTy->isObjCInterfaceType()) {
5849 Diag(ParamInfo.getSourceRange().getBegin(),
5850 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5851 return;
5852 }
Mike Stump82f071f2009-02-04 22:31:32 +00005853 return;
5854 }
5855
Steve Naroffc540d662008-09-03 18:15:37 +00005856 // Analyze arguments to block.
5857 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5858 "Not a function declarator!");
5859 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005860
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005861 CurBlock->hasPrototype = FTI.hasPrototype;
5862 CurBlock->isVariadic = true;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005863
Steve Naroffc540d662008-09-03 18:15:37 +00005864 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5865 // no arguments, not a function that takes a single void argument.
5866 if (FTI.hasPrototype &&
5867 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner83f095c2009-03-28 19:18:32 +00005868 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5869 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroffc540d662008-09-03 18:15:37 +00005870 // empty arg list, don't push any params.
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005871 CurBlock->isVariadic = false;
Steve Naroffc540d662008-09-03 18:15:37 +00005872 } else if (FTI.hasPrototype) {
5873 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner83f095c2009-03-28 19:18:32 +00005874 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005875 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroffc540d662008-09-03 18:15:37 +00005876 }
Jay Foad7d0479f2009-05-21 09:52:38 +00005877 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattner6de05082009-04-11 19:27:54 +00005878 CurBlock->Params.size());
Fariborz Jahanian960910a2009-05-19 17:08:59 +00005879 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor758a8692009-06-17 21:51:59 +00005880 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005881 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5882 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5883 // If this has an identifier, add it to the scope stack.
5884 if ((*AI)->getIdentifier())
5885 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattner6de05082009-04-11 19:27:54 +00005886
Fariborz Jahanian6607b212009-05-14 20:53:39 +00005887 // Check for a valid sentinel attribute on this block.
Mike Stump11289f42009-09-09 15:08:12 +00005888 if (!CurBlock->isVariadic &&
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005889 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Mike Stump11289f42009-09-09 15:08:12 +00005890 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6802ed92009-05-15 21:18:04 +00005891 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian6607b212009-05-14 20:53:39 +00005892 // FIXME: remove the attribute.
5893 }
Mike Stump11289f42009-09-09 15:08:12 +00005894
Chris Lattner6de05082009-04-11 19:27:54 +00005895 // Analyze the return type.
5896 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall9dd450b2009-09-21 23:43:11 +00005897 QualType RetTy = T->getAs<FunctionType>()->getResultType();
Mike Stump11289f42009-09-09 15:08:12 +00005898
Chris Lattner6de05082009-04-11 19:27:54 +00005899 // Do not allow returning a objc interface by-value.
5900 if (RetTy->isObjCInterfaceType()) {
5901 Diag(ParamInfo.getSourceRange().getBegin(),
5902 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5903 } else if (!RetTy->isDependentType())
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00005904 CurBlock->ReturnType = RetTy;
Steve Naroffc540d662008-09-03 18:15:37 +00005905}
5906
5907/// ActOnBlockError - If there is an error parsing a block, this callback
5908/// is invoked to pop the information about the block from the action impl.
5909void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5910 // Ensure that CurBlock is deleted.
5911 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005912
Chris Lattner45542ea2009-04-19 05:28:12 +00005913 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5914
Steve Naroffc540d662008-09-03 18:15:37 +00005915 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00005916 PopDeclContext();
Steve Naroffc540d662008-09-03 18:15:37 +00005917 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroffc540d662008-09-03 18:15:37 +00005918 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroffc540d662008-09-03 18:15:37 +00005919}
5920
5921/// ActOnBlockStmtExpr - This is called when the body of a block statement
5922/// literal was successfully completed. ^(int x){...}
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005923Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5924 StmtArg body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00005925 // If blocks are disabled, emit an error.
5926 if (!LangOpts.Blocks)
5927 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00005928
Steve Naroffc540d662008-09-03 18:15:37 +00005929 // Ensure that CurBlock is deleted.
5930 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroffc540d662008-09-03 18:15:37 +00005931
Steve Naroff1d95e5a2008-10-10 01:28:17 +00005932 PopDeclContext();
5933
Steve Naroffc540d662008-09-03 18:15:37 +00005934 // Pop off CurBlock, handle nested blocks.
5935 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005936
Steve Naroffc540d662008-09-03 18:15:37 +00005937 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00005938 if (!BSI->ReturnType.isNull())
5939 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005940
Steve Naroffc540d662008-09-03 18:15:37 +00005941 llvm::SmallVector<QualType, 8> ArgTypes;
5942 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5943 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump4e1f26a2009-02-19 03:04:26 +00005944
Mike Stump3bf1ab42009-07-28 22:04:01 +00005945 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00005946 QualType BlockTy;
5947 if (!BSI->hasPrototype)
Mike Stump3bf1ab42009-07-28 22:04:01 +00005948 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5949 NoReturn);
Steve Naroffc540d662008-09-03 18:15:37 +00005950 else
Jay Foad7d0479f2009-05-21 09:52:38 +00005951 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump3bf1ab42009-07-28 22:04:01 +00005952 BSI->isVariadic, 0, false, false, 0, 0,
5953 NoReturn);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005954
Eli Friedmanba961a92009-03-23 00:24:07 +00005955 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005956 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroffc540d662008-09-03 18:15:37 +00005957 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005958
Chris Lattner45542ea2009-04-19 05:28:12 +00005959 // If needed, diagnose invalid gotos and switches in the block.
5960 if (CurFunctionNeedsScopeChecking)
5961 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5962 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
Mike Stump11289f42009-09-09 15:08:12 +00005963
Anders Carlssonb781bcd2009-05-01 19:49:17 +00005964 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump3bf1ab42009-07-28 22:04:01 +00005965 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005966 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5967 BSI->hasBlockDeclRefExprs));
Steve Naroffc540d662008-09-03 18:15:37 +00005968}
5969
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005970Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5971 ExprArg expr, TypeTy *type,
5972 SourceLocation RPLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00005973 QualType T = GetTypeFromParser(type);
Chris Lattner56382aa2009-04-05 15:49:53 +00005974 Expr *E = static_cast<Expr*>(expr.get());
5975 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00005976
Anders Carlsson7e13ab82007-10-15 20:28:48 +00005977 InitBuiltinVaListType();
Eli Friedman121ba0c2008-08-09 23:32:40 +00005978
5979 // Get the va_list type
5980 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00005981 if (VaListType->isArrayType()) {
5982 // Deal with implicit array decay; for example, on x86-64,
5983 // va_list is an array, but it's supposed to decay to
5984 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00005985 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00005986 // Make sure the input expression also decays appropriately.
5987 UsualUnaryConversions(E);
5988 } else {
5989 // Otherwise, the va_list argument must be an l-value because
5990 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00005991 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00005992 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00005993 return ExprError();
5994 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00005995
Douglas Gregorad3150c2009-05-19 23:10:31 +00005996 if (!E->isTypeDependent() &&
5997 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00005998 return ExprError(Diag(E->getLocStart(),
5999 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00006000 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00006001 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006002
Eli Friedmanba961a92009-03-23 00:24:07 +00006003 // FIXME: Check that type is complete/non-abstract
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006004 // FIXME: Warn if a non-POD type is passed in.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006005
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006006 expr.release();
6007 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
6008 RPLoc));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00006009}
6010
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006011Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00006012 // The type of __null will be int or long, depending on the size of
6013 // pointers on the target.
6014 QualType Ty;
6015 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6016 Ty = Context.IntTy;
6017 else
6018 Ty = Context.LongTy;
6019
Sebastian Redl6d4256c2009-03-15 17:47:39 +00006020 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00006021}
6022
Chris Lattner9bad62c2008-01-04 18:04:52 +00006023bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6024 SourceLocation Loc,
6025 QualType DstType, QualType SrcType,
6026 Expr *SrcExpr, const char *Flavor) {
6027 // Decode the result (notice that AST's are still created for extensions).
6028 bool isInvalid = false;
6029 unsigned DiagKind;
6030 switch (ConvTy) {
6031 default: assert(0 && "Unknown conversion type");
6032 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006033 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00006034 DiagKind = diag::ext_typecheck_convert_pointer_int;
6035 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00006036 case IntToPointer:
6037 DiagKind = diag::ext_typecheck_convert_int_pointer;
6038 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006039 case IncompatiblePointer:
6040 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6041 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00006042 case IncompatiblePointerSign:
6043 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6044 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006045 case FunctionVoidPointer:
6046 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6047 break;
6048 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00006049 // If the qualifiers lost were because we were applying the
6050 // (deprecated) C++ conversion from a string literal to a char*
6051 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
6052 // Ideally, this check would be performed in
6053 // CheckPointerTypesForAssignment. However, that would require a
6054 // bit of refactoring (so that the second argument is an
6055 // expression, rather than a type), which should be done as part
6056 // of a larger effort to fix CheckPointerTypesForAssignment for
6057 // C++ semantics.
6058 if (getLangOptions().CPlusPlus &&
6059 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6060 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006061 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6062 break;
Steve Naroff081c7422008-09-04 15:10:53 +00006063 case IntToBlockPointer:
6064 DiagKind = diag::err_int_to_block_pointer;
6065 break;
6066 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00006067 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00006068 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00006069 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00006070 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00006071 // it can give a more specific diagnostic.
6072 DiagKind = diag::warn_incompatible_qualified_id;
6073 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00006074 case IncompatibleVectors:
6075 DiagKind = diag::warn_incompatible_vectors;
6076 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00006077 case Incompatible:
6078 DiagKind = diag::err_typecheck_convert_incompatible;
6079 isInvalid = true;
6080 break;
6081 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006082
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00006083 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
6084 << SrcExpr->getSourceRange();
Chris Lattner9bad62c2008-01-04 18:04:52 +00006085 return isInvalid;
6086}
Anders Carlssone54e8a12008-11-30 19:50:32 +00006087
Chris Lattnerc71d08b2009-04-25 21:59:05 +00006088bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006089 llvm::APSInt ICEResult;
6090 if (E->isIntegerConstantExpr(ICEResult, Context)) {
6091 if (Result)
6092 *Result = ICEResult;
6093 return false;
6094 }
6095
Anders Carlssone54e8a12008-11-30 19:50:32 +00006096 Expr::EvalResult EvalResult;
6097
Mike Stump4e1f26a2009-02-19 03:04:26 +00006098 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssone54e8a12008-11-30 19:50:32 +00006099 EvalResult.HasSideEffects) {
6100 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6101
6102 if (EvalResult.Diag) {
6103 // We only show the note if it's not the usual "invalid subexpression"
6104 // or if it's actually in a subexpression.
6105 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6106 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6107 Diag(EvalResult.DiagLoc, EvalResult.Diag);
6108 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006109
Anders Carlssone54e8a12008-11-30 19:50:32 +00006110 return true;
6111 }
6112
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006113 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6114 E->getSourceRange();
Anders Carlssone54e8a12008-11-30 19:50:32 +00006115
Eli Friedmanbb967cc2009-04-25 22:26:58 +00006116 if (EvalResult.Diag &&
6117 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6118 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006119
Anders Carlssone54e8a12008-11-30 19:50:32 +00006120 if (Result)
6121 *Result = EvalResult.Val.getInt();
6122 return false;
6123}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006124
Mike Stump11289f42009-09-09 15:08:12 +00006125Sema::ExpressionEvaluationContext
6126Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006127 // Introduce a new set of potentially referenced declarations to the stack.
6128 if (NewContext == PotentiallyPotentiallyEvaluated)
6129 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
Mike Stump11289f42009-09-09 15:08:12 +00006130
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006131 std::swap(ExprEvalContext, NewContext);
6132 return NewContext;
6133}
6134
Mike Stump11289f42009-09-09 15:08:12 +00006135void
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006136Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6137 ExpressionEvaluationContext NewContext) {
6138 ExprEvalContext = NewContext;
6139
6140 if (OldContext == PotentiallyPotentiallyEvaluated) {
6141 // Mark any remaining declarations in the current position of the stack
6142 // as "referenced". If they were not meant to be referenced, semantic
6143 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6144 PotentiallyReferencedDecls RemainingDecls;
6145 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6146 PotentiallyReferencedDeclStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00006147
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006148 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6149 IEnd = RemainingDecls.end();
6150 I != IEnd; ++I)
6151 MarkDeclarationReferenced(I->first, I->second);
6152 }
6153}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006154
6155/// \brief Note that the given declaration was referenced in the source code.
6156///
6157/// This routine should be invoke whenever a given declaration is referenced
6158/// in the source code, and where that reference occurred. If this declaration
6159/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6160/// C99 6.9p3), then the declaration will be marked as used.
6161///
6162/// \param Loc the location where the declaration was referenced.
6163///
6164/// \param D the declaration that has been referenced by the source code.
6165void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6166 assert(D && "No declaration?");
Mike Stump11289f42009-09-09 15:08:12 +00006167
Douglas Gregor77b50e12009-06-22 23:06:13 +00006168 if (D->isUsed())
6169 return;
Mike Stump11289f42009-09-09 15:08:12 +00006170
Douglas Gregor3beaf9b2009-10-08 21:35:42 +00006171 // Mark a parameter or variable declaration "used", regardless of whether we're in a
6172 // template or not. The reason for this is that unevaluated expressions
6173 // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6174 // -Wunused-parameters)
6175 if (isa<ParmVarDecl>(D) ||
6176 (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006177 D->setUsed(true);
Mike Stump11289f42009-09-09 15:08:12 +00006178
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006179 // Do not mark anything as "used" within a dependent context; wait for
6180 // an instantiation.
6181 if (CurContext->isDependentContext())
6182 return;
Mike Stump11289f42009-09-09 15:08:12 +00006183
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006184 switch (ExprEvalContext) {
6185 case Unevaluated:
6186 // We are in an expression that is not potentially evaluated; do nothing.
6187 return;
Mike Stump11289f42009-09-09 15:08:12 +00006188
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006189 case PotentiallyEvaluated:
6190 // We are in a potentially-evaluated expression, so this declaration is
6191 // "used"; handle this below.
6192 break;
Mike Stump11289f42009-09-09 15:08:12 +00006193
Douglas Gregor0b6a6242009-06-22 20:57:11 +00006194 case PotentiallyPotentiallyEvaluated:
6195 // We are in an expression that may be potentially evaluated; queue this
6196 // declaration reference until we know whether the expression is
6197 // potentially evaluated.
6198 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6199 return;
6200 }
Mike Stump11289f42009-09-09 15:08:12 +00006201
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006202 // Note that this declaration has been used.
Fariborz Jahanian3a363432009-06-22 17:30:33 +00006203 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006204 unsigned TypeQuals;
Fariborz Jahanian18eb69a2009-06-22 20:37:23 +00006205 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6206 if (!Constructor->isUsed())
6207 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump11289f42009-09-09 15:08:12 +00006208 } else if (Constructor->isImplicit() &&
Mike Stump12b8ce12009-08-04 21:02:39 +00006209 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian477d2422009-06-22 23:34:40 +00006210 if (!Constructor->isUsed())
6211 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6212 }
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00006213 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6214 if (Destructor->isImplicit() && !Destructor->isUsed())
6215 DefineImplicitDestructor(Loc, Destructor);
Mike Stump11289f42009-09-09 15:08:12 +00006216
Fariborz Jahanian41f79272009-06-25 21:45:19 +00006217 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6218 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6219 MethodDecl->getOverloadedOperator() == OO_Equal) {
6220 if (!MethodDecl->isUsed())
6221 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6222 }
6223 }
Fariborz Jahanian49796cc72009-06-24 22:09:44 +00006224 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00006225 // Implicit instantiation of function templates and member functions of
Douglas Gregor4adbc6d2009-06-26 00:10:03 +00006226 // class templates.
Douglas Gregor06db9f52009-10-12 20:18:28 +00006227 if (!Function->getBody() &&
6228 Function->getTemplateSpecializationKind()
6229 == TSK_ImplicitInstantiation) {
6230 bool AlreadyInstantiated = false;
6231 if (FunctionTemplateSpecializationInfo *SpecInfo
6232 = Function->getTemplateSpecializationInfo()) {
6233 if (SpecInfo->getPointOfInstantiation().isInvalid())
6234 SpecInfo->setPointOfInstantiation(Loc);
6235 else
6236 AlreadyInstantiated = true;
6237 } else if (MemberSpecializationInfo *MSInfo
6238 = Function->getMemberSpecializationInfo()) {
6239 if (MSInfo->getPointOfInstantiation().isInvalid())
6240 MSInfo->setPointOfInstantiation(Loc);
6241 else
6242 AlreadyInstantiated = true;
6243 }
6244
6245 if (!AlreadyInstantiated)
6246 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6247 }
6248
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006249 // FIXME: keep track of references to static functions
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006250 Function->setUsed(true);
6251 return;
Douglas Gregor77b50e12009-06-22 23:06:13 +00006252 }
Mike Stump11289f42009-09-09 15:08:12 +00006253
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006254 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006255 // Implicit instantiation of static data members of class templates.
Mike Stump11289f42009-09-09 15:08:12 +00006256 if (Var->isStaticDataMember() &&
Douglas Gregor06db9f52009-10-12 20:18:28 +00006257 Var->getInstantiatedFromStaticDataMember()) {
6258 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6259 assert(MSInfo && "Missing member specialization information?");
6260 if (MSInfo->getPointOfInstantiation().isInvalid() &&
6261 MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6262 MSInfo->setPointOfInstantiation(Loc);
6263 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6264 }
6265 }
Mike Stump11289f42009-09-09 15:08:12 +00006266
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006267 // FIXME: keep track of references to static data?
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006268
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006269 D->setUsed(true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00006270 return;
Sam Weinigbae69142009-09-11 03:29:30 +00006271 }
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006272}
Anders Carlsson7f84ed92009-10-09 23:51:55 +00006273
6274bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
6275 CallExpr *CE, FunctionDecl *FD) {
6276 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
6277 return false;
6278
6279 PartialDiagnostic Note =
6280 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
6281 << FD->getDeclName() : PDiag();
6282 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
6283
6284 if (RequireCompleteType(Loc, ReturnType,
6285 FD ?
6286 PDiag(diag::err_call_function_incomplete_return)
6287 << CE->getSourceRange() << FD->getDeclName() :
6288 PDiag(diag::err_call_incomplete_return)
6289 << CE->getSourceRange(),
6290 std::make_pair(NoteLoc, Note)))
6291 return true;
6292
6293 return false;
6294}
6295
John McCalld5707ab2009-10-12 21:59:07 +00006296// Diagnose the common s/=/==/ typo. Note that adding parentheses
6297// will prevent this condition from triggering, which is what we want.
6298void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
6299 SourceLocation Loc;
6300
6301 if (isa<BinaryOperator>(E)) {
6302 BinaryOperator *Op = cast<BinaryOperator>(E);
6303 if (Op->getOpcode() != BinaryOperator::Assign)
6304 return;
6305
6306 Loc = Op->getOperatorLoc();
6307 } else if (isa<CXXOperatorCallExpr>(E)) {
6308 CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
6309 if (Op->getOperator() != OO_Equal)
6310 return;
6311
6312 Loc = Op->getOperatorLoc();
6313 } else {
6314 // Not an assignment.
6315 return;
6316 }
6317
John McCalld5707ab2009-10-12 21:59:07 +00006318 SourceLocation Open = E->getSourceRange().getBegin();
John McCalle724ae92009-10-12 22:25:59 +00006319 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
John McCalld5707ab2009-10-12 21:59:07 +00006320
6321 Diag(Loc, diag::warn_condition_is_assignment)
6322 << E->getSourceRange()
6323 << CodeModificationHint::CreateInsertion(Open, "(")
6324 << CodeModificationHint::CreateInsertion(Close, ")");
6325}
6326
6327bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
6328 DiagnoseAssignmentAsCondition(E);
6329
6330 if (!E->isTypeDependent()) {
6331 DefaultFunctionArrayConversion(E);
6332
6333 QualType T = E->getType();
6334
6335 if (getLangOptions().CPlusPlus) {
6336 if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
6337 return true;
6338 } else if (!T->isScalarType()) { // C99 6.8.4.1p1
6339 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
6340 << T << E->getSourceRange();
6341 return true;
6342 }
6343 }
6344
6345 return false;
6346}