blob: 4b8cc0e5e8f0f92862b2485bcd4a6d29f59ec522 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000016#include "clang/AST/DeclObjC.h"
Chris Lattner3e254fb2008-04-08 04:40:51 +000017#include "clang/AST/ExprCXX.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
Chris Lattner4b009652007-07-25 00:24:17 +000023#include "clang/Basic/TargetInfo.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000024#include "clang/Parse/DeclSpec.h"
Chris Lattner71ca8c82008-10-26 23:43:26 +000025#include "clang/Parse/Designator.h"
Steve Naroff52a81c02008-09-03 18:15:37 +000026#include "clang/Parse/Scope.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027using namespace clang;
28
David Chisnall44663db2009-08-17 16:35:33 +000029
Douglas Gregoraa57e862009-02-18 21:56:37 +000030/// \brief Determine whether the use of this declaration is valid, and
31/// emit any corresponding diagnostics.
32///
33/// This routine diagnoses various problems with referencing
34/// declarations that can occur when using a declaration. For example,
35/// it might warn if a deprecated or unavailable declaration is being
36/// used, or produce an error (and return true) if a C++0x deleted
37/// function is being used.
38///
39/// \returns true if there was an error (this declaration cannot be
40/// referenced), false otherwise.
41bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000042 // See if the decl is deprecated.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000043 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000044 // Implementing deprecated stuff requires referencing deprecated
45 // stuff. Don't warn if we are implementing a deprecated
46 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000047 bool isSilenced = false;
48
49 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
50 // If this reference happens *in* a deprecated function or method, don't
51 // warn.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000052 isSilenced = ND->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000053
54 // If this is an Objective-C method implementation, check to see if the
55 // method was deprecated on the declaration, not the definition.
56 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
57 // The semantic decl context of a ObjCMethodDecl is the
58 // ObjCImplementationDecl.
59 if (ObjCImplementationDecl *Impl
60 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
61
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +000062 MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
Chris Lattnerfb1bb822009-02-16 19:35:30 +000063 MD->isInstanceMethod());
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000064 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
Chris Lattnerfb1bb822009-02-16 19:35:30 +000065 }
66 }
67 }
68
69 if (!isSilenced)
Chris Lattner2cb744b2009-02-15 22:43:40 +000070 Diag(Loc, diag::warn_deprecated) << D->getDeclName();
71 }
72
Douglas Gregoraa57e862009-02-18 21:56:37 +000073 // See if this is a deleted function.
Douglas Gregor6f8c3682009-02-24 04:26:15 +000074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000075 if (FD->isDeleted()) {
76 Diag(Loc, diag::err_deleted_function_use);
77 Diag(D->getLocation(), diag::note_unavailable_here) << true;
78 return true;
79 }
Douglas Gregor6f8c3682009-02-24 04:26:15 +000080 }
Douglas Gregoraa57e862009-02-18 21:56:37 +000081
82 // See if the decl is unavailable
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000083 if (D->getAttr<UnavailableAttr>()) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000084 Diag(Loc, diag::warn_unavailable) << D->getDeclName();
Douglas Gregoraa57e862009-02-18 21:56:37 +000085 Diag(D->getLocation(), diag::note_unavailable_here) << 0;
86 }
87
Douglas Gregoraa57e862009-02-18 21:56:37 +000088 return false;
Chris Lattner2cb744b2009-02-15 22:43:40 +000089}
90
Fariborz Jahanian180f3412009-05-13 18:09:35 +000091/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
92/// (and other functions in future), which have been declared with sentinel
93/// attribute. It warns if call does not have the sentinel argument.
94///
95void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
96 Expr **Args, unsigned NumArgs)
97{
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +000098 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Fariborz Jahanian79d29e72009-05-13 23:20:50 +000099 if (!attr)
100 return;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000101 int sentinelPos = attr->getSentinel();
102 int nullPos = attr->getNullPos();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000103
Mike Stumpe127ae32009-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 Jahanian79d29e72009-05-13 23:20:50 +0000106 unsigned int i = 0;
Fariborz Jahanian09f2e3f2009-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 Stump90fc78e2009-08-04 21:02:39 +0000120 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Fariborz Jahanian09f2e3f2009-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 Stump90fc78e2009-08-04 21:02:39 +0000130 } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000131 // block or function pointer call.
132 QualType Ty = V->getType();
133 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
134 const FunctionType *FT = Ty->isFunctionPointerType()
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000135 ? Ty->getAs<PointerType>()->getPointeeType()->getAsFunctionType()
136 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
Fariborz Jahanianc10357d2009-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 Stump90fc78e2009-08-04 21:02:39 +0000150 } else
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000151 return;
Mike Stump90fc78e2009-08-04 21:02:39 +0000152 } else
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000153 return;
154
155 if (warnNotEnoughArgs) {
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000156 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000157 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-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 Jahanian09f2e3f2009-05-14 18:00:00 +0000167 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-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() ||
176 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000177 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000178 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000179 }
180 return;
Fariborz Jahanian180f3412009-05-13 18:09:35 +0000181}
182
Douglas Gregor3bb30002009-02-26 21:00:50 +0000183SourceRange Sema::getExprRange(ExprTy *E) const {
184 Expr *Ex = (Expr *)E;
185 return Ex? Ex->getSourceRange() : SourceRange();
186}
187
Chris Lattner299b8842008-07-25 21:10:04 +0000188//===----------------------------------------------------------------------===//
189// Standard Promotions and Conversions
190//===----------------------------------------------------------------------===//
191
Chris Lattner299b8842008-07-25 21:10:04 +0000192/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
193void Sema::DefaultFunctionArrayConversion(Expr *&E) {
194 QualType Ty = E->getType();
195 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
196
Chris Lattner299b8842008-07-25 21:10:04 +0000197 if (Ty->isFunctionType())
198 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000199 else if (Ty->isArrayType()) {
200 // In C90 mode, arrays only promote to pointers if the array expression is
201 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
202 // type 'array of type' is converted to an expression that has type 'pointer
203 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
204 // that has type 'array of type' ...". The relevant change is "an lvalue"
205 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000206 //
207 // C++ 4.2p1:
208 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
209 // T" can be converted to an rvalue of type "pointer to T".
210 //
211 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
212 E->isLvalue(Context) == Expr::LV_Valid)
Anders Carlsson5c09af02009-08-07 23:48:20 +0000213 ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
214 CastExpr::CK_ArrayToPointerDecay);
Chris Lattner2aa68822008-07-25 21:33:13 +0000215 }
Chris Lattner299b8842008-07-25 21:10:04 +0000216}
217
Douglas Gregor70b307e2009-05-01 20:41:21 +0000218/// \brief Whether this is a promotable bitfield reference according
219/// to C99 6.3.1.1p2, bullet 2.
220///
221/// \returns the type this bit-field will promote to, or NULL if no
222/// promotion occurs.
223static QualType isPromotableBitField(Expr *E, ASTContext &Context) {
Douglas Gregor531434b2009-05-02 02:18:30 +0000224 FieldDecl *Field = E->getBitField();
225 if (!Field)
Douglas Gregor70b307e2009-05-01 20:41:21 +0000226 return QualType();
227
228 const BuiltinType *BT = Field->getType()->getAsBuiltinType();
229 if (!BT)
230 return QualType();
231
232 if (BT->getKind() != BuiltinType::Bool &&
233 BT->getKind() != BuiltinType::Int &&
234 BT->getKind() != BuiltinType::UInt)
235 return QualType();
236
237 llvm::APSInt BitWidthAP;
238 if (!Field->getBitWidth()->isIntegerConstantExpr(BitWidthAP, Context))
239 return QualType();
240
241 uint64_t BitWidth = BitWidthAP.getZExtValue();
242 uint64_t IntSize = Context.getTypeSize(Context.IntTy);
243 if (BitWidth < IntSize ||
244 (Field->getType()->isSignedIntegerType() && BitWidth == IntSize))
245 return Context.IntTy;
246
247 if (BitWidth == IntSize && Field->getType()->isUnsignedIntegerType())
248 return Context.UnsignedIntTy;
249
250 return QualType();
251}
252
Chris Lattner299b8842008-07-25 21:10:04 +0000253/// UsualUnaryConversions - Performs various conversions that are common to most
254/// operators (C99 6.3). The conversions of array and function types are
255/// sometimes surpressed. For example, the array->pointer conversion doesn't
256/// apply if the array is an argument to the sizeof or address (&) operators.
257/// In these instances, this routine should *not* be called.
258Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
259 QualType Ty = Expr->getType();
260 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
261
Douglas Gregor70b307e2009-05-01 20:41:21 +0000262 // C99 6.3.1.1p2:
263 //
264 // The following may be used in an expression wherever an int or
265 // unsigned int may be used:
266 // - an object or expression with an integer type whose integer
267 // conversion rank is less than or equal to the rank of int
268 // and unsigned int.
269 // - A bit-field of type _Bool, int, signed int, or unsigned int.
270 //
271 // If an int can represent all values of the original type, the
272 // value is converted to an int; otherwise, it is converted to an
273 // unsigned int. These are called the integer promotions. All
274 // other types are unchanged by the integer promotions.
275 if (Ty->isPromotableIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000276 ImpCastExprToType(Expr, Context.IntTy);
Douglas Gregor70b307e2009-05-01 20:41:21 +0000277 return Expr;
278 } else {
279 QualType T = isPromotableBitField(Expr, Context);
280 if (!T.isNull()) {
281 ImpCastExprToType(Expr, T);
282 return Expr;
283 }
284 }
285
286 DefaultFunctionArrayConversion(Expr);
Chris Lattner299b8842008-07-25 21:10:04 +0000287 return Expr;
288}
289
Chris Lattner9305c3d2008-07-25 22:25:12 +0000290/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
291/// do not have a prototype. Arguments that have type float are promoted to
292/// double. All other argument types are converted by UsualUnaryConversions().
293void Sema::DefaultArgumentPromotion(Expr *&Expr) {
294 QualType Ty = Expr->getType();
295 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
296
297 // If this is a 'float' (CVR qualified or typedef) promote to double.
298 if (const BuiltinType *BT = Ty->getAsBuiltinType())
299 if (BT->getKind() == BuiltinType::Float)
300 return ImpCastExprToType(Expr, Context.DoubleTy);
301
302 UsualUnaryConversions(Expr);
303}
304
Chris Lattner81f00ed2009-04-12 08:11:20 +0000305/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
306/// will warn if the resulting type is not a POD type, and rejects ObjC
307/// interfaces passed by value. This returns true if the argument type is
308/// completely illegal.
309bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000310 DefaultArgumentPromotion(Expr);
311
Chris Lattner81f00ed2009-04-12 08:11:20 +0000312 if (Expr->getType()->isObjCInterfaceType()) {
313 Diag(Expr->getLocStart(),
314 diag::err_cannot_pass_objc_interface_to_vararg)
315 << Expr->getType() << CT;
316 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000317 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000318
319 if (!Expr->getType()->isPODType())
320 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
321 << Expr->getType() << CT;
322
323 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000324}
325
326
Chris Lattner299b8842008-07-25 21:10:04 +0000327/// UsualArithmeticConversions - Performs various conversions that are common to
328/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
329/// routine returns the first non-arithmetic type found. The client is
330/// responsible for emitting appropriate error diagnostics.
331/// FIXME: verify the conversion rules for "complex int" are consistent with
332/// GCC.
333QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
334 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000335 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000336 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000337
338 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000339
Chris Lattner299b8842008-07-25 21:10:04 +0000340 // For conversion purposes, we ignore any qualifiers.
341 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000342 QualType lhs =
343 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
344 QualType rhs =
345 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000346
347 // If both types are identical, no conversion is needed.
348 if (lhs == rhs)
349 return lhs;
350
351 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
352 // The caller can deal with this (e.g. pointer + int).
353 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
354 return lhs;
355
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000356 // Perform bitfield promotions.
357 QualType LHSBitfieldPromoteTy = isPromotableBitField(lhsExpr, Context);
358 if (!LHSBitfieldPromoteTy.isNull())
359 lhs = LHSBitfieldPromoteTy;
360 QualType RHSBitfieldPromoteTy = isPromotableBitField(rhsExpr, Context);
361 if (!RHSBitfieldPromoteTy.isNull())
362 rhs = RHSBitfieldPromoteTy;
363
Douglas Gregor70d26122008-11-12 17:17:38 +0000364 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000365 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000366 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000367 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000368 return destType;
369}
370
371QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
372 // Perform the usual unary conversions. We do this early so that
373 // integral promotions to "int" can allow us to exit early, in the
374 // lhs == rhs check. Also, for conversion purposes, we ignore any
375 // qualifiers. For example, "const float" and "float" are
376 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000377 if (lhs->isPromotableIntegerType())
378 lhs = Context.IntTy;
379 else
380 lhs = lhs.getUnqualifiedType();
381 if (rhs->isPromotableIntegerType())
382 rhs = Context.IntTy;
383 else
384 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000385
Chris Lattner299b8842008-07-25 21:10:04 +0000386 // If both types are identical, no conversion is needed.
387 if (lhs == rhs)
388 return lhs;
389
390 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
391 // The caller can deal with this (e.g. pointer + int).
392 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
393 return lhs;
394
395 // At this point, we have two different arithmetic types.
396
397 // Handle complex types first (C99 6.3.1.8p1).
398 if (lhs->isComplexType() || rhs->isComplexType()) {
399 // if we have an integer operand, the result is the complex type.
400 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
401 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000402 return lhs;
403 }
404 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
405 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000406 return rhs;
407 }
408 // This handles complex/complex, complex/float, or float/complex.
409 // When both operands are complex, the shorter operand is converted to the
410 // type of the longer, and that is the type of the result. This corresponds
411 // to what is done when combining two real floating-point operands.
412 // The fun begins when size promotion occur across type domains.
413 // From H&S 6.3.4: When one operand is complex and the other is a real
414 // floating-point type, the less precise type is converted, within it's
415 // real or complex domain, to the precision of the other type. For example,
416 // when combining a "long double" with a "double _Complex", the
417 // "double _Complex" is promoted to "long double _Complex".
418 int result = Context.getFloatingTypeOrder(lhs, rhs);
419
420 if (result > 0) { // The left side is bigger, convert rhs.
421 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000422 } else if (result < 0) { // The right side is bigger, convert lhs.
423 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000424 }
425 // At this point, lhs and rhs have the same rank/size. Now, make sure the
426 // domains match. This is a requirement for our implementation, C99
427 // does not require this promotion.
428 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
429 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000430 return rhs;
431 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000432 return lhs;
433 }
434 }
435 return lhs; // The domain/size match exactly.
436 }
437 // Now handle "real" floating types (i.e. float, double, long double).
438 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
439 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000440 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000441 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000442 return lhs;
443 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000444 if (rhs->isComplexIntegerType()) {
445 // convert rhs to the complex floating point type.
446 return Context.getComplexType(lhs);
447 }
448 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000449 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000450 return rhs;
451 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000452 if (lhs->isComplexIntegerType()) {
453 // convert lhs to the complex floating point type.
454 return Context.getComplexType(rhs);
455 }
Chris Lattner299b8842008-07-25 21:10:04 +0000456 // We have two real floating types, float/complex combos were handled above.
457 // Convert the smaller operand to the bigger result.
458 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000459 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000460 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000461 assert(result < 0 && "illegal float comparison");
462 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000463 }
464 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
465 // Handle GCC complex int extension.
466 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
467 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
468
469 if (lhsComplexInt && rhsComplexInt) {
470 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000471 rhsComplexInt->getElementType()) >= 0)
472 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000473 return rhs;
474 } else if (lhsComplexInt && rhs->isIntegerType()) {
475 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000476 return lhs;
477 } else if (rhsComplexInt && lhs->isIntegerType()) {
478 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000479 return rhs;
480 }
481 }
482 // Finally, we have two differing integer types.
483 // The rules for this case are in C99 6.3.1.8
484 int compare = Context.getIntegerTypeOrder(lhs, rhs);
485 bool lhsSigned = lhs->isSignedIntegerType(),
486 rhsSigned = rhs->isSignedIntegerType();
487 QualType destType;
488 if (lhsSigned == rhsSigned) {
489 // Same signedness; use the higher-ranked type
490 destType = compare >= 0 ? lhs : rhs;
491 } else if (compare != (lhsSigned ? 1 : -1)) {
492 // The unsigned type has greater than or equal rank to the
493 // signed type, so use the unsigned type
494 destType = lhsSigned ? rhs : lhs;
495 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
496 // The two types are different widths; if we are here, that
497 // means the signed type is larger than the unsigned type, so
498 // use the signed type.
499 destType = lhsSigned ? lhs : rhs;
500 } else {
501 // The signed type is higher-ranked than the unsigned type,
502 // but isn't actually any bigger (like unsigned int and long
503 // on most 32-bit systems). Use the unsigned type corresponding
504 // to the signed type.
505 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
506 }
Chris Lattner299b8842008-07-25 21:10:04 +0000507 return destType;
508}
509
510//===----------------------------------------------------------------------===//
511// Semantic Analysis for various Expression Types
512//===----------------------------------------------------------------------===//
513
514
Steve Naroff87d58b42007-09-16 03:34:24 +0000515/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000516/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
517/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
518/// multiple tokens. However, the common case is that StringToks points to one
519/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000520///
521Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000522Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000523 assert(NumStringToks && "Must have at least one string!");
524
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000525 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000526 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000527 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000528
529 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
530 for (unsigned i = 0; i != NumStringToks; ++i)
531 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000532
Chris Lattnera6dcce32008-02-11 00:02:17 +0000533 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000534 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000535 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000536
537 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
538 if (getLangOptions().CPlusPlus)
539 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000540
Chris Lattnera6dcce32008-02-11 00:02:17 +0000541 // Get an array type for the string, according to C99 6.4.5. This includes
542 // the nul terminator character as well as the string length for pascal
543 // strings.
544 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000545 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000546 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000547
Chris Lattner4b009652007-07-25 00:24:17 +0000548 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000549 return Owned(StringLiteral::Create(Context, Literal.GetString(),
550 Literal.GetStringLength(),
551 Literal.AnyWide, StrTy,
552 &StringTokLocs[0],
553 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000554}
555
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000556/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
557/// CurBlock to VD should cause it to be snapshotted (as we do for auto
558/// variables defined outside the block) or false if this is not needed (e.g.
559/// for values inside the block or for globals).
560///
Chris Lattner0b464252009-04-21 22:26:47 +0000561/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
562/// up-to-date.
563///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000564static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
565 ValueDecl *VD) {
566 // If the value is defined inside the block, we couldn't snapshot it even if
567 // we wanted to.
568 if (CurBlock->TheDecl == VD->getDeclContext())
569 return false;
570
571 // If this is an enum constant or function, it is constant, don't snapshot.
572 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
573 return false;
574
575 // If this is a reference to an extern, static, or global variable, no need to
576 // snapshot it.
577 // FIXME: What about 'const' variables in C++?
578 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000579 if (!Var->hasLocalStorage())
580 return false;
581
582 // Blocks that have these can't be constant.
583 CurBlock->hasBlockDeclRefExprs = true;
584
585 // If we have nested blocks, the decl may be declared in an outer block (in
586 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
587 // be defined outside all of the current blocks (in which case the blocks do
588 // all get the bit). Walk the nesting chain.
589 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
590 NextBlock = NextBlock->PrevBlockInfo) {
591 // If we found the defining block for the variable, don't mark the block as
592 // having a reference outside it.
593 if (NextBlock->TheDecl == VD->getDeclContext())
594 break;
595
596 // Otherwise, the DeclRef from the inner block causes the outer one to need
597 // a snapshot as well.
598 NextBlock->hasBlockDeclRefExprs = true;
599 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000600
601 return true;
602}
603
604
605
Steve Naroff0acc9c92007-09-15 18:49:24 +0000606/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000607/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000608/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000609/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000610/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000611Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
612 IdentifierInfo &II,
613 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000614 const CXXScopeSpec *SS,
615 bool isAddressOfOperand) {
616 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000617 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000618}
619
Douglas Gregor566782a2009-01-06 05:10:23 +0000620/// BuildDeclRefExpr - Build either a DeclRefExpr or a
621/// QualifiedDeclRefExpr based on whether or not SS is a
622/// nested-name-specifier.
Anders Carlsson4571d812009-06-24 00:10:43 +0000623Sema::OwningExprResult
Sebastian Redl0c9da212009-02-03 20:19:35 +0000624Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
625 bool TypeDependent, bool ValueDependent,
626 const CXXScopeSpec *SS) {
Anders Carlsson9bd48662009-06-26 19:16:07 +0000627 if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
628 Diag(Loc,
629 diag::err_auto_variable_cannot_appear_in_own_initializer)
630 << D->getDeclName();
631 return ExprError();
632 }
Anders Carlsson4571d812009-06-24 00:10:43 +0000633
634 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
635 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
636 if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
637 if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
638 Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
639 << D->getIdentifier() << FD->getDeclName();
640 Diag(D->getLocation(), diag::note_local_variable_declared_here)
641 << D->getIdentifier();
642 return ExprError();
643 }
644 }
645 }
646 }
647
Douglas Gregor98189262009-06-19 23:52:42 +0000648 MarkDeclarationReferenced(Loc, D);
Anders Carlsson4571d812009-06-24 00:10:43 +0000649
650 Expr *E;
Douglas Gregor7e508262009-03-19 03:51:16 +0000651 if (SS && !SS->isEmpty()) {
Anders Carlsson4571d812009-06-24 00:10:43 +0000652 E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
653 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000654 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000655 } else
Anders Carlsson4571d812009-06-24 00:10:43 +0000656 E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
657
658 return Owned(E);
Douglas Gregor566782a2009-01-06 05:10:23 +0000659}
660
Douglas Gregor723d3332009-01-07 00:43:41 +0000661/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
662/// variable corresponding to the anonymous union or struct whose type
663/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000664static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
665 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000666 assert(Record->isAnonymousStructOrUnion() &&
667 "Record must be an anonymous struct or union!");
668
Mike Stumpe127ae32009-05-16 07:39:55 +0000669 // FIXME: Once Decls are directly linked together, this will be an O(1)
670 // operation rather than a slow walk through DeclContext's vector (which
671 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor723d3332009-01-07 00:43:41 +0000672 DeclContext *Ctx = Record->getDeclContext();
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000673 for (DeclContext::decl_iterator D = Ctx->decls_begin(),
674 DEnd = Ctx->decls_end();
Douglas Gregor723d3332009-01-07 00:43:41 +0000675 D != DEnd; ++D) {
676 if (*D == Record) {
677 // The object for the anonymous struct/union directly
678 // follows its type in the list of declarations.
679 ++D;
680 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000681 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000682 return *D;
683 }
684 }
685
686 assert(false && "Missing object for anonymous record");
687 return 0;
688}
689
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000690/// \brief Given a field that represents a member of an anonymous
691/// struct/union, build the path from that field's context to the
692/// actual member.
693///
694/// Construct the sequence of field member references we'll have to
695/// perform to get to the field in the anonymous union/struct. The
696/// list of members is built from the field outward, so traverse it
697/// backwards to go from an object in the current context to the field
698/// we found.
699///
700/// \returns The variable from which the field access should begin,
701/// for an anonymous struct/union that is not a member of another
702/// class. Otherwise, returns NULL.
703VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
704 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000705 assert(Field->getDeclContext()->isRecord() &&
706 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
707 && "Field must be stored inside an anonymous struct or union");
708
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000709 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000710 VarDecl *BaseObject = 0;
711 DeclContext *Ctx = Field->getDeclContext();
712 do {
713 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000714 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000715 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000716 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000717 else {
718 BaseObject = cast<VarDecl>(AnonObject);
719 break;
720 }
721 Ctx = Ctx->getParent();
722 } while (Ctx->isRecord() &&
723 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000724
725 return BaseObject;
726}
727
728Sema::OwningExprResult
729Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
730 FieldDecl *Field,
731 Expr *BaseObjectExpr,
732 SourceLocation OpLoc) {
733 llvm::SmallVector<FieldDecl *, 4> AnonFields;
734 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
735 AnonFields);
736
Douglas Gregor723d3332009-01-07 00:43:41 +0000737 // Build the expression that refers to the base object, from
738 // which we will build a sequence of member references to each
739 // of the anonymous union objects and, eventually, the field we
740 // found via name lookup.
741 bool BaseObjectIsPointer = false;
742 unsigned ExtraQuals = 0;
743 if (BaseObject) {
744 // BaseObject is an anonymous struct/union variable (and is,
745 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000746 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Douglas Gregor98189262009-06-19 23:52:42 +0000747 MarkDeclarationReferenced(Loc, BaseObject);
Steve Naroff774e4152009-01-21 00:14:39 +0000748 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000749 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000750 ExtraQuals
751 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
752 } else if (BaseObjectExpr) {
753 // The caller provided the base object expression. Determine
754 // whether its a pointer and whether it adds any qualifiers to the
755 // anonymous struct/union fields we're looking into.
756 QualType ObjectType = BaseObjectExpr->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000757 if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000758 BaseObjectIsPointer = true;
759 ObjectType = ObjectPtr->getPointeeType();
760 }
761 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
762 } else {
763 // We've found a member of an anonymous struct/union that is
764 // inside a non-anonymous struct/union, so in a well-formed
765 // program our base object expression is "this".
766 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
767 if (!MD->isStatic()) {
768 QualType AnonFieldType
769 = Context.getTagDeclType(
770 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
771 QualType ThisType = Context.getTagDeclType(MD->getParent());
772 if ((Context.getCanonicalType(AnonFieldType)
773 == Context.getCanonicalType(ThisType)) ||
774 IsDerivedFrom(ThisType, AnonFieldType)) {
775 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000776 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000777 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000778 BaseObjectIsPointer = true;
779 }
780 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000781 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
782 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000783 }
784 ExtraQuals = MD->getTypeQualifiers();
785 }
786
787 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000788 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
789 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000790 }
791
792 // Build the implicit member references to the field of the
793 // anonymous struct/union.
794 Expr *Result = BaseObjectExpr;
Mon P Wang04d89cb2009-07-22 03:08:17 +0000795 unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
Douglas Gregor723d3332009-01-07 00:43:41 +0000796 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
797 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
798 FI != FIEnd; ++FI) {
799 QualType MemberType = (*FI)->getType();
800 if (!(*FI)->isMutable()) {
801 unsigned combinedQualifiers
802 = MemberType.getCVRQualifiers() | ExtraQuals;
803 MemberType = MemberType.getQualifiedType(combinedQualifiers);
804 }
Mon P Wang04d89cb2009-07-22 03:08:17 +0000805 if (BaseAddrSpace != MemberType.getAddressSpace())
806 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor98189262009-06-19 23:52:42 +0000807 MarkDeclarationReferenced(Loc, *FI);
Steve Naroff774e4152009-01-21 00:14:39 +0000808 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
809 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000810 BaseObjectIsPointer = false;
811 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000812 }
813
Sebastian Redlcd883f72009-01-18 18:53:16 +0000814 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000815}
816
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000817/// ActOnDeclarationNameExpr - The parser has read some kind of name
818/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
819/// performs lookup on that name and returns an expression that refers
820/// to that name. This routine isn't directly called from the parser,
821/// because the parser doesn't know about DeclarationName. Rather,
822/// this routine is called by ActOnIdentifierExpr,
823/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
824/// which form the DeclarationName from the corresponding syntactic
825/// forms.
826///
827/// HasTrailingLParen indicates whether this identifier is used in a
828/// function call context. LookupCtx is only used for a C++
829/// qualified-id (foo::bar) to indicate the class or namespace that
830/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000831///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000832/// isAddressOfOperand means that this expression is the direct operand
833/// of an address-of operator. This matters because this is the only
834/// situation where a qualified name referencing a non-static member may
835/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000836Sema::OwningExprResult
837Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
838 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000839 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000840 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000841 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000842 if (SS && SS->isInvalid())
843 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000844
845 // C++ [temp.dep.expr]p3:
846 // An id-expression is type-dependent if it contains:
847 // -- a nested-name-specifier that contains a class-name that
848 // names a dependent type.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000849 // FIXME: Member of the current instantiation.
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000850 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000851 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
852 Loc, SS->getRange(),
Anders Carlsson4e8d5692009-07-09 00:05:08 +0000853 static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
854 isAddressOfOperand));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000855 }
856
Douglas Gregor411889e2009-02-13 23:20:09 +0000857 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
858 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000859
Sebastian Redlcd883f72009-01-18 18:53:16 +0000860 if (Lookup.isAmbiguous()) {
861 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
862 SS && SS->isSet() ? SS->getRange()
863 : SourceRange());
864 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000865 }
866
867 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000868
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000869 // If this reference is in an Objective-C method, then ivar lookup happens as
870 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000871 IdentifierInfo *II = Name.getAsIdentifierInfo();
872 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000873 // There are two cases to handle here. 1) scoped lookup could have failed,
874 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000875 // found a decl, but that decl is outside the current instance method (i.e.
876 // a global variable). In these two cases, we do a lookup for an ivar with
877 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000878 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000879 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000880 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000881 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000882 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000883 if (DiagnoseUseOfDecl(IV, Loc))
884 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000885
886 // If we're referencing an invalid decl, just return this as a silent
887 // error node. The error diagnostic was already emitted on the decl.
888 if (IV->isInvalidDecl())
889 return ExprError();
890
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000891 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
892 // If a class method attemps to use a free standing ivar, this is
893 // an error.
894 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
895 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
896 << IV->getDeclName());
897 // If a class method uses a global variable, even if an ivar with
898 // same name exists, use the global.
899 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000900 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
901 ClassDeclared != IFace)
902 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stumpe127ae32009-05-16 07:39:55 +0000903 // FIXME: This should use a new expr for a direct reference, don't
904 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000905 IdentifierInfo &II = Context.Idents.get("self");
Argiris Kirtzidis3bb49042009-07-18 08:49:37 +0000906 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
907 II, false);
Douglas Gregor98189262009-06-19 23:52:42 +0000908 MarkDeclarationReferenced(Loc, IV);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000909 return Owned(new (Context)
910 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000911 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000912 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000913 }
Mike Stump90fc78e2009-08-04 21:02:39 +0000914 } else if (getCurMethodDecl()->isInstanceMethod()) {
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000915 // We should warn if a local variable hides an ivar.
916 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000917 ObjCInterfaceDecl *ClassDeclared;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +0000918 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000919 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
920 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000921 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000922 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000923 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000924 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000925 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000926 QualType T;
927
928 if (getCurMethodDecl()->isInstanceMethod())
Steve Naroff329ec222009-07-10 23:34:53 +0000929 T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
930 getCurMethodDecl()->getClassInterface()));
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000931 else
932 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000933 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000934 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000935 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000936
Douglas Gregoraa57e862009-02-18 21:56:37 +0000937 // Determine whether this name might be a candidate for
938 // argument-dependent lookup.
939 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
940 HasTrailingLParen;
941
942 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000943 // We've seen something of the form
944 //
945 // identifier(
946 //
947 // and we did not find any entity by the name
948 // "identifier". However, this identifier is still subject to
949 // argument-dependent lookup, so keep track of the name.
950 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
951 Context.OverloadTy,
952 Loc));
953 }
954
Chris Lattner4b009652007-07-25 00:24:17 +0000955 if (D == 0) {
956 // Otherwise, this could be an implicitly declared function reference (legal
957 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000958 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000959 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000960 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000961 else {
962 // If this name wasn't predeclared and if this is not a function call,
963 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000964 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000965 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
966 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000967 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
968 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000969 return ExprError(Diag(Loc, diag::err_undeclared_use)
970 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000971 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000972 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000973 }
974 }
Douglas Gregor6ef403d2009-06-30 15:47:41 +0000975
976 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
977 // Warn about constructs like:
978 // if (void *X = foo()) { ... } else { X }.
979 // In the else block, the pointer is always false.
980
981 // FIXME: In a template instantiation, we don't have scope
982 // information to check this property.
983 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
984 Scope *CheckS = S;
985 while (CheckS) {
986 if (CheckS->isWithinElse() &&
987 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
988 if (Var->getType()->isBooleanType())
989 ExprError(Diag(Loc, diag::warn_value_always_false)
990 << Var->getDeclName());
991 else
992 ExprError(Diag(Loc, diag::warn_value_always_zero)
993 << Var->getDeclName());
994 break;
995 }
996
997 // Move up one more control parent to check again.
998 CheckS = CheckS->getControlParent();
999 if (CheckS)
1000 CheckS = CheckS->getParent();
1001 }
1002 }
1003 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
1004 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1005 // C99 DR 316 says that, if a function type comes from a
1006 // function definition (without a prototype), that type is only
1007 // used for checking compatibility. Therefore, when referencing
1008 // the function, we pretend that we don't have the full function
1009 // type.
1010 if (DiagnoseUseOfDecl(Func, Loc))
1011 return ExprError();
Douglas Gregor723d3332009-01-07 00:43:41 +00001012
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001013 QualType T = Func->getType();
1014 QualType NoProtoType = T;
1015 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
1016 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
1017 return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
1018 }
1019 }
1020
1021 return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
1022}
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001023/// \brief Cast member's object to its own class if necessary.
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001024bool
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001025Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
1026 if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
1027 if (CXXRecordDecl *RD =
1028 dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
1029 QualType DestType =
1030 Context.getCanonicalType(Context.getTypeDeclType(RD));
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +00001031 if (DestType->isDependentType() || From->getType()->isDependentType())
1032 return false;
1033 QualType FromRecordType = From->getType();
1034 QualType DestRecordType = DestType;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001035 if (FromRecordType->getAs<PointerType>()) {
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +00001036 DestType = Context.getPointerType(DestType);
1037 FromRecordType = FromRecordType->getPointeeType();
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001038 }
Fariborz Jahanian3ae1c802009-07-29 20:41:46 +00001039 if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
1040 CheckDerivedToBaseConversion(FromRecordType,
1041 DestRecordType,
1042 From->getSourceRange().getBegin(),
1043 From->getSourceRange()))
1044 return true;
Anders Carlsson85186942009-07-31 01:23:52 +00001045 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
1046 /*isLvalue=*/true);
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001047 }
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001048 return false;
Fariborz Jahanian80b859e2009-07-29 18:40:24 +00001049}
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001050
1051/// \brief Complete semantic analysis for a reference to the given declaration.
1052Sema::OwningExprResult
1053Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
1054 bool HasTrailingLParen,
1055 const CXXScopeSpec *SS,
1056 bool isAddressOfOperand) {
1057 assert(D && "Cannot refer to a NULL declaration");
1058 DeclarationName Name = D->getDeclName();
1059
Sebastian Redl0c9da212009-02-03 20:19:35 +00001060 // If this is an expression of the form &Class::member, don't build an
1061 // implicit member ref, because we want a pointer to the member in general,
1062 // not any specific instance's member.
1063 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001064 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +00001065 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +00001066 QualType DType;
1067 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1068 DType = FD->getType().getNonReferenceType();
1069 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1070 DType = Method->getType();
1071 } else if (isa<OverloadedFunctionDecl>(D)) {
1072 DType = Context.OverloadTy;
1073 }
1074 // Could be an inner type. That's diagnosed below, so ignore it here.
1075 if (!DType.isNull()) {
1076 // The pointer is type- and value-dependent if it points into something
1077 // dependent.
Douglas Gregorf3a200f2009-05-29 14:49:33 +00001078 bool Dependent = DC->isDependentContext();
Anders Carlsson4571d812009-06-24 00:10:43 +00001079 return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
Sebastian Redl0c9da212009-02-03 20:19:35 +00001080 }
1081 }
1082 }
1083
Douglas Gregor723d3332009-01-07 00:43:41 +00001084 // We may have found a field within an anonymous union or struct
1085 // (C++ [class.union]).
1086 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
1087 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1088 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001089
Douglas Gregor3257fb52008-12-22 05:46:06 +00001090 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1091 if (!MD->isStatic()) {
1092 // C++ [class.mfct.nonstatic]p2:
1093 // [...] if name lookup (3.4.1) resolves the name in the
1094 // id-expression to a nonstatic nontype member of class X or of
1095 // a base class of X, the id-expression is transformed into a
1096 // class member access expression (5.2.5) using (*this) (9.3.2)
1097 // as the postfix-expression to the left of the '.' operator.
1098 DeclContext *Ctx = 0;
1099 QualType MemberType;
1100 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1101 Ctx = FD->getDeclContext();
1102 MemberType = FD->getType();
1103
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001104 if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
Douglas Gregor3257fb52008-12-22 05:46:06 +00001105 MemberType = RefType->getPointeeType();
1106 else if (!FD->isMutable()) {
1107 unsigned combinedQualifiers
1108 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
1109 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1110 }
1111 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1112 if (!Method->isStatic()) {
1113 Ctx = Method->getParent();
1114 MemberType = Method->getType();
1115 }
1116 } else if (OverloadedFunctionDecl *Ovl
1117 = dyn_cast<OverloadedFunctionDecl>(D)) {
1118 for (OverloadedFunctionDecl::function_iterator
1119 Func = Ovl->function_begin(),
1120 FuncEnd = Ovl->function_end();
1121 Func != FuncEnd; ++Func) {
1122 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
1123 if (!DMethod->isStatic()) {
1124 Ctx = Ovl->getDeclContext();
1125 MemberType = Context.OverloadTy;
1126 break;
1127 }
1128 }
1129 }
Douglas Gregor723d3332009-01-07 00:43:41 +00001130
1131 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001132 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
1133 QualType ThisType = Context.getTagDeclType(MD->getParent());
1134 if ((Context.getCanonicalType(CtxType)
1135 == Context.getCanonicalType(ThisType)) ||
1136 IsDerivedFrom(ThisType, CtxType)) {
1137 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +00001138 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +00001139 MD->getThisType(Context));
Douglas Gregor98189262009-06-19 23:52:42 +00001140 MarkDeclarationReferenced(Loc, D);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00001141 if (PerformObjectMemberConversion(This, D))
1142 return ExprError();
Anders Carlsson9fbe6872009-08-08 16:55:18 +00001143 if (DiagnoseUseOfDecl(D, Loc))
1144 return ExprError();
Douglas Gregor09be81b2009-02-04 17:27:36 +00001145 return Owned(new (Context) MemberExpr(This, true, D,
Eli Friedman1653e232009-04-29 17:56:47 +00001146 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001147 }
1148 }
1149 }
1150 }
1151
Douglas Gregor8acb7272008-12-11 16:49:14 +00001152 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001153 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1154 if (MD->isStatic())
1155 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001156 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1157 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001158 }
1159
Douglas Gregor3257fb52008-12-22 05:46:06 +00001160 // Any other ways we could have found the field in a well-formed
1161 // program would have been turned into implicit member expressions
1162 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001163 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1164 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001165 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001166
Chris Lattner4b009652007-07-25 00:24:17 +00001167 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001168 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001169 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001170 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001171 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001172 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001173
Steve Naroffd6163f32008-09-05 22:11:13 +00001174 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001175 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001176 return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1177 false, false, SS);
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001178 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
Anders Carlsson4571d812009-06-24 00:10:43 +00001179 return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1180 false, false, SS);
Steve Naroffd6163f32008-09-05 22:11:13 +00001181 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001182
Douglas Gregoraa57e862009-02-18 21:56:37 +00001183 // Check whether this declaration can be used. Note that we suppress
1184 // this check when we're going to perform argument-dependent lookup
1185 // on this function name, because this might not be the function
1186 // that overload resolution actually selects.
Douglas Gregor6ef403d2009-06-30 15:47:41 +00001187 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1188 HasTrailingLParen;
Douglas Gregoraa57e862009-02-18 21:56:37 +00001189 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1190 return ExprError();
1191
Steve Naroffd6163f32008-09-05 22:11:13 +00001192 // Only create DeclRefExpr's for valid Decl's.
1193 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001194 return ExprError();
1195
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001196 // If the identifier reference is inside a block, and it refers to a value
1197 // that is outside the block, create a BlockDeclRefExpr instead of a
1198 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1199 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001200 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001201 // We do not do this for things like enum constants, global variables, etc,
1202 // as they do not get snapshotted.
1203 //
1204 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Douglas Gregor98189262009-06-19 23:52:42 +00001205 MarkDeclarationReferenced(Loc, VD);
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001206 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001207 // The BlocksAttr indicates the variable is bound by-reference.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00001208 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001209 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001210 // This is to record that a 'const' was actually synthesize and added.
1211 bool constAdded = !ExprTy.isConstQualified();
Steve Naroff52059382008-10-10 01:28:17 +00001212 // Variable will be bound by-copy, make it const within the closure.
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001213
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001214 ExprTy.addConst();
Fariborz Jahanian89942a02009-06-19 23:37:08 +00001215 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1216 constAdded));
Steve Naroff52059382008-10-10 01:28:17 +00001217 }
1218 // If this reference is not in a block or if the referenced variable is
1219 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001220
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001221 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001222 bool ValueDependent = false;
1223 if (getLangOptions().CPlusPlus) {
1224 // C++ [temp.dep.expr]p3:
1225 // An id-expression is type-dependent if it contains:
1226 // - an identifier that was declared with a dependent type,
1227 if (VD->getType()->isDependentType())
1228 TypeDependent = true;
1229 // - FIXME: a template-id that is dependent,
1230 // - a conversion-function-id that specifies a dependent type,
1231 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1232 Name.getCXXNameType()->isDependentType())
1233 TypeDependent = true;
1234 // - a nested-name-specifier that contains a class-name that
1235 // names a dependent type.
1236 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001237 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001238 DC; DC = DC->getParent()) {
1239 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001240 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001241 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1242 if (Context.getTypeDeclType(Record)->isDependentType()) {
1243 TypeDependent = true;
1244 break;
1245 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001246 }
1247 }
1248 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001249
Douglas Gregora5d84612008-12-10 20:57:37 +00001250 // C++ [temp.dep.constexpr]p2:
1251 //
1252 // An identifier is value-dependent if it is:
1253 // - a name declared with a dependent type,
1254 if (TypeDependent)
1255 ValueDependent = true;
1256 // - the name of a non-type template parameter,
1257 else if (isa<NonTypeTemplateParmDecl>(VD))
1258 ValueDependent = true;
1259 // - a constant with integral or enumeration type and is
1260 // initialized with an expression that is value-dependent
Eli Friedman1f7744a2009-06-11 01:11:20 +00001261 else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1262 if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1263 Dcl->getInit()) {
1264 ValueDependent = Dcl->getInit()->isValueDependent();
1265 }
1266 }
Douglas Gregora5d84612008-12-10 20:57:37 +00001267 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001268
Anders Carlsson4571d812009-06-24 00:10:43 +00001269 return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1270 TypeDependent, ValueDependent, SS);
Chris Lattner4b009652007-07-25 00:24:17 +00001271}
1272
Sebastian Redlcd883f72009-01-18 18:53:16 +00001273Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1274 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001275 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001276
Chris Lattner4b009652007-07-25 00:24:17 +00001277 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001278 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001279 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1280 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1281 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001282 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001283
Chris Lattner7e637512008-01-12 08:14:25 +00001284 // Pre-defined identifiers are of type char[x], where x is the length of the
1285 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001286 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001287 if (FunctionDecl *FD = getCurFunctionDecl())
1288 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001289 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1290 Length = MD->getSynthesizedMethodSize();
1291 else {
1292 Diag(Loc, diag::ext_predef_outside_function);
1293 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1294 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1295 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001296
1297
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001298 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001299 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001300 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001301 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001302}
1303
Sebastian Redlcd883f72009-01-18 18:53:16 +00001304Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001305 llvm::SmallString<16> CharBuffer;
1306 CharBuffer.resize(Tok.getLength());
1307 const char *ThisTokBegin = &CharBuffer[0];
1308 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001309
Chris Lattner4b009652007-07-25 00:24:17 +00001310 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1311 Tok.getLocation(), PP);
1312 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001313 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001314
1315 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1316
Sebastian Redl75324932009-01-20 22:23:13 +00001317 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1318 Literal.isWide(),
1319 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001320}
1321
Sebastian Redlcd883f72009-01-18 18:53:16 +00001322Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1323 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001324 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1325 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001326 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001327 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001328 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001329 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001330 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001331
Chris Lattner4b009652007-07-25 00:24:17 +00001332 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001333 // Add padding so that NumericLiteralParser can overread by one character.
1334 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001335 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001336
Chris Lattner4b009652007-07-25 00:24:17 +00001337 // Get the spelling of the token, which eliminates trigraphs, etc.
1338 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001339
Chris Lattner4b009652007-07-25 00:24:17 +00001340 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1341 Tok.getLocation(), PP);
1342 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001343 return ExprError();
1344
Chris Lattner1de66eb2007-08-26 03:42:43 +00001345 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001346
Chris Lattner1de66eb2007-08-26 03:42:43 +00001347 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001348 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001349 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001350 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001351 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001352 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001353 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001354 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001355
1356 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1357
Ted Kremenekddedbe22007-11-29 00:56:49 +00001358 // isExact will be set by GetFloatValue().
1359 bool isExact = false;
Chris Lattnerff1bf1a2009-06-29 17:34:55 +00001360 llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1361 Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001362
Chris Lattner1de66eb2007-08-26 03:42:43 +00001363 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001364 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001365 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001366 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001367
Neil Booth7421e9c2007-08-29 22:00:19 +00001368 // long long is a C99 feature.
1369 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001370 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001371 Diag(Tok.getLocation(), diag::ext_longlong);
1372
Chris Lattner4b009652007-07-25 00:24:17 +00001373 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001374 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001375
Chris Lattner4b009652007-07-25 00:24:17 +00001376 if (Literal.GetIntegerValue(ResultVal)) {
1377 // If this value didn't fit into uintmax_t, warn and force to ull.
1378 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001379 Ty = Context.UnsignedLongLongTy;
1380 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001381 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001382 } else {
1383 // If this value fits into a ULL, try to figure out what else it fits into
1384 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001385
Chris Lattner4b009652007-07-25 00:24:17 +00001386 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1387 // be an unsigned int.
1388 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1389
1390 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001391 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001392 if (!Literal.isLong && !Literal.isLongLong) {
1393 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001394 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001395
Chris Lattner4b009652007-07-25 00:24:17 +00001396 // Does it fit in a unsigned int?
1397 if (ResultVal.isIntN(IntSize)) {
1398 // Does it fit in a signed int?
1399 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001400 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001401 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001402 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001403 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001404 }
Chris Lattner4b009652007-07-25 00:24:17 +00001405 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001406
Chris Lattner4b009652007-07-25 00:24:17 +00001407 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001408 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001409 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001410
Chris Lattner4b009652007-07-25 00:24:17 +00001411 // Does it fit in a unsigned long?
1412 if (ResultVal.isIntN(LongSize)) {
1413 // Does it fit in a signed long?
1414 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001415 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001416 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001417 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001418 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001419 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001420 }
1421
Chris Lattner4b009652007-07-25 00:24:17 +00001422 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001423 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001424 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001425
Chris Lattner4b009652007-07-25 00:24:17 +00001426 // Does it fit in a unsigned long long?
1427 if (ResultVal.isIntN(LongLongSize)) {
1428 // Does it fit in a signed long long?
1429 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001430 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001431 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001432 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001433 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001434 }
1435 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001436
Chris Lattner4b009652007-07-25 00:24:17 +00001437 // If we still couldn't decide a type, we probably have something that
1438 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001439 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001440 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001441 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001442 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001443 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001444
Chris Lattnere4068872008-05-09 05:59:00 +00001445 if (ResultVal.getBitWidth() != Width)
1446 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001447 }
Sebastian Redl75324932009-01-20 22:23:13 +00001448 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001449 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001450
Chris Lattner1de66eb2007-08-26 03:42:43 +00001451 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1452 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001453 Res = new (Context) ImaginaryLiteral(Res,
1454 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001455
1456 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001457}
1458
Sebastian Redlcd883f72009-01-18 18:53:16 +00001459Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1460 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001461 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001462 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001463 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001464}
1465
1466/// The UsualUnaryConversions() function is *not* called by this routine.
1467/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001468bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001469 SourceLocation OpLoc,
1470 const SourceRange &ExprRange,
1471 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001472 if (exprType->isDependentType())
1473 return false;
1474
Chris Lattner4b009652007-07-25 00:24:17 +00001475 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001476 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001477 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001478 if (isSizeof)
1479 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1480 return false;
1481 }
1482
Chris Lattner95933c12009-04-24 00:30:45 +00001483 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001484 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001485 Diag(OpLoc, diag::ext_sizeof_void_type)
1486 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001487 return false;
1488 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001489
Chris Lattner95933c12009-04-24 00:30:45 +00001490 if (RequireCompleteType(OpLoc, exprType,
1491 isSizeof ? diag::err_sizeof_incomplete_type :
1492 diag::err_alignof_incomplete_type,
1493 ExprRange))
1494 return true;
1495
1496 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001497 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001498 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001499 << exprType << isSizeof << ExprRange;
1500 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001501 }
1502
Chris Lattner95933c12009-04-24 00:30:45 +00001503 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001504}
1505
Chris Lattner8d9f7962009-01-24 20:17:12 +00001506bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1507 const SourceRange &ExprRange) {
1508 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001509
Chris Lattner8d9f7962009-01-24 20:17:12 +00001510 // alignof decl is always ok.
1511 if (isa<DeclRefExpr>(E))
1512 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001513
1514 // Cannot know anything else if the expression is dependent.
1515 if (E->isTypeDependent())
1516 return false;
1517
Douglas Gregor531434b2009-05-02 02:18:30 +00001518 if (E->getBitField()) {
1519 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1520 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001521 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001522
1523 // Alignment of a field access is always okay, so long as it isn't a
1524 // bit-field.
1525 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump6eeaa782009-07-22 18:58:19 +00001526 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor531434b2009-05-02 02:18:30 +00001527 return false;
1528
Chris Lattner8d9f7962009-01-24 20:17:12 +00001529 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1530}
1531
Douglas Gregor396f1142009-03-13 21:01:28 +00001532/// \brief Build a sizeof or alignof expression given a type operand.
1533Action::OwningExprResult
1534Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1535 bool isSizeOf, SourceRange R) {
1536 if (T.isNull())
1537 return ExprError();
1538
1539 if (!T->isDependentType() &&
1540 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1541 return ExprError();
1542
1543 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1544 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1545 Context.getSizeType(), OpLoc,
1546 R.getEnd()));
1547}
1548
1549/// \brief Build a sizeof or alignof expression given an expression
1550/// operand.
1551Action::OwningExprResult
1552Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1553 bool isSizeOf, SourceRange R) {
1554 // Verify that the operand is valid.
1555 bool isInvalid = false;
1556 if (E->isTypeDependent()) {
1557 // Delay type-checking for type-dependent expressions.
1558 } else if (!isSizeOf) {
1559 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001560 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001561 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1562 isInvalid = true;
1563 } else {
1564 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1565 }
1566
1567 if (isInvalid)
1568 return ExprError();
1569
1570 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1571 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1572 Context.getSizeType(), OpLoc,
1573 R.getEnd()));
1574}
1575
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001576/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1577/// the same for @c alignof and @c __alignof
1578/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001579Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001580Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1581 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001582 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001583 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001584
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001585 if (isType) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00001586 // FIXME: Preserve type source info.
1587 QualType ArgTy = GetTypeFromParser(TyOrEx);
Douglas Gregor396f1142009-03-13 21:01:28 +00001588 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1589 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001590
Douglas Gregor396f1142009-03-13 21:01:28 +00001591 // Get the end location.
1592 Expr *ArgEx = (Expr *)TyOrEx;
1593 Action::OwningExprResult Result
1594 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1595
1596 if (Result.isInvalid())
1597 DeleteExpr(ArgEx);
1598
1599 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001600}
1601
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001602QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001603 if (V->isTypeDependent())
1604 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001605
Chris Lattnera16e42d2007-08-26 05:39:26 +00001606 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001607 if (const ComplexType *CT = V->getType()->getAsComplexType())
1608 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001609
1610 // Otherwise they pass through real integer and floating point types here.
1611 if (V->getType()->isArithmeticType())
1612 return V->getType();
1613
1614 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001615 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1616 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001617 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001618}
1619
1620
Chris Lattner4b009652007-07-25 00:24:17 +00001621
Sebastian Redl8b769972009-01-19 00:08:26 +00001622Action::OwningExprResult
1623Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1624 tok::TokenKind Kind, ExprArg Input) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001625 // Since this might be a postfix expression, get rid of ParenListExprs.
1626 Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
Sebastian Redl8b769972009-01-19 00:08:26 +00001627 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001628
Chris Lattner4b009652007-07-25 00:24:17 +00001629 UnaryOperator::Opcode Opc;
1630 switch (Kind) {
1631 default: assert(0 && "Unknown unary op!");
1632 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1633 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1634 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001635
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001636 if (getLangOptions().CPlusPlus &&
1637 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1638 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001639 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001640 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1641
1642 // C++ [over.inc]p1:
1643 //
1644 // [...] If the function is a member function with one
1645 // parameter (which shall be of type int) or a non-member
1646 // function with two parameters (the second of which shall be
1647 // of type int), it defines the postfix increment operator ++
1648 // for objects of that type. When the postfix increment is
1649 // called as a result of using the ++ operator, the int
1650 // argument will have value zero.
1651 Expr *Args[2] = {
1652 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001653 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1654 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001655 };
1656
1657 // Build the candidate set for overloading
1658 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001659 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001660
1661 // Perform overload resolution.
1662 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001663 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001664 case OR_Success: {
1665 // We found a built-in operator or an overloaded operator.
1666 FunctionDecl *FnDecl = Best->Function;
1667
1668 if (FnDecl) {
1669 // We matched an overloaded operator. Build a call to that
1670 // operator.
1671
1672 // Convert the arguments.
1673 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1674 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001675 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001676 } else {
1677 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001678 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001679 FnDecl->getParamDecl(0)->getType(),
1680 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001681 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001682 }
1683
1684 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001685 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001686 = FnDecl->getType()->getAsFunctionType()->getResultType();
1687 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001688
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001689 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001690 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001691 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001692 UsualUnaryConversions(FnExpr);
1693
Sebastian Redl8b769972009-01-19 00:08:26 +00001694 Input.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001695 Args[0] = Arg;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001696 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1697 Args, 2, ResultTy,
1698 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001699 } else {
1700 // We matched a built-in operator. Convert the arguments, then
1701 // break out so that we will build the appropriate built-in
1702 // operator node.
1703 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1704 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001705 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001706
1707 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001708 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001709 }
1710
1711 case OR_No_Viable_Function:
1712 // No viable function; fall through to handling this as a
1713 // built-in operator, which will produce an error message for us.
1714 break;
1715
1716 case OR_Ambiguous:
1717 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1718 << UnaryOperator::getOpcodeStr(Opc)
1719 << Arg->getSourceRange();
1720 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001721 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001722
1723 case OR_Deleted:
1724 Diag(OpLoc, diag::err_ovl_deleted_oper)
1725 << Best->Function->isDeleted()
1726 << UnaryOperator::getOpcodeStr(Opc)
1727 << Arg->getSourceRange();
1728 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1729 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001730 }
1731
1732 // Either we found no viable overloaded operator or we matched a
1733 // built-in operator. In either case, fall through to trying to
1734 // build a built-in operation.
1735 }
1736
Eli Friedman94d30952009-07-22 23:24:42 +00001737 Input.release();
1738 Input = Arg;
Eli Friedman79341142009-07-22 22:25:00 +00001739 return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
Chris Lattner4b009652007-07-25 00:24:17 +00001740}
1741
Sebastian Redl8b769972009-01-19 00:08:26 +00001742Action::OwningExprResult
1743Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1744 ExprArg Idx, SourceLocation RLoc) {
Nate Begemane85f43d2009-08-10 23:49:36 +00001745 // Since this might be a postfix expression, get rid of ParenListExprs.
1746 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1747
Sebastian Redl8b769972009-01-19 00:08:26 +00001748 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1749 *RHSExp = static_cast<Expr*>(Idx.get());
Nate Begemane85f43d2009-08-10 23:49:36 +00001750
Douglas Gregor80723c52008-11-19 17:17:41 +00001751 if (getLangOptions().CPlusPlus &&
Douglas Gregorde72f3e2009-05-19 00:01:19 +00001752 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1753 Base.release();
1754 Idx.release();
1755 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1756 Context.DependentTy, RLoc));
1757 }
1758
1759 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001760 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001761 LHSExp->getType()->isEnumeralType() ||
1762 RHSExp->getType()->isRecordType() ||
1763 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001764 // Add the appropriate overloaded operators (C++ [over.match.oper])
1765 // to the candidate set.
1766 OverloadCandidateSet CandidateSet;
1767 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001768 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1769 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001770
Douglas Gregor80723c52008-11-19 17:17:41 +00001771 // Perform overload resolution.
1772 OverloadCandidateSet::iterator Best;
Douglas Gregor98189262009-06-19 23:52:42 +00001773 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001774 case OR_Success: {
1775 // We found a built-in operator or an overloaded operator.
1776 FunctionDecl *FnDecl = Best->Function;
1777
1778 if (FnDecl) {
1779 // We matched an overloaded operator. Build a call to that
1780 // operator.
1781
1782 // Convert the arguments.
1783 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1784 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1785 PerformCopyInitialization(RHSExp,
1786 FnDecl->getParamDecl(0)->getType(),
1787 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001788 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001789 } else {
1790 // Convert the arguments.
1791 if (PerformCopyInitialization(LHSExp,
1792 FnDecl->getParamDecl(0)->getType(),
1793 "passing") ||
1794 PerformCopyInitialization(RHSExp,
1795 FnDecl->getParamDecl(1)->getType(),
1796 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001797 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001798 }
1799
1800 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001801 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001802 = FnDecl->getType()->getAsFunctionType()->getResultType();
1803 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001804
Douglas Gregor80723c52008-11-19 17:17:41 +00001805 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001806 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1807 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001808 UsualUnaryConversions(FnExpr);
1809
Sebastian Redl8b769972009-01-19 00:08:26 +00001810 Base.release();
1811 Idx.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001812 Args[0] = LHSExp;
1813 Args[1] = RHSExp;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001814 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1815 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001816 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001817 } else {
1818 // We matched a built-in operator. Convert the arguments, then
1819 // break out so that we will build the appropriate built-in
1820 // operator node.
1821 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1822 "passing") ||
1823 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1824 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001825 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001826
1827 break;
1828 }
1829 }
1830
1831 case OR_No_Viable_Function:
1832 // No viable function; fall through to handling this as a
1833 // built-in operator, which will produce an error message for us.
1834 break;
1835
1836 case OR_Ambiguous:
1837 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1838 << "[]"
1839 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1840 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001841 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001842
1843 case OR_Deleted:
1844 Diag(LLoc, diag::err_ovl_deleted_oper)
1845 << Best->Function->isDeleted()
1846 << "[]"
1847 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1848 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1849 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001850 }
1851
1852 // Either we found no viable overloaded operator or we matched a
1853 // built-in operator. In either case, fall through to trying to
1854 // build a built-in operation.
1855 }
1856
Chris Lattner4b009652007-07-25 00:24:17 +00001857 // Perform default conversions.
1858 DefaultFunctionArrayConversion(LHSExp);
1859 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001860
Chris Lattner4b009652007-07-25 00:24:17 +00001861 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1862
1863 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001864 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001865 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001866 // and index from the expression types.
1867 Expr *BaseExpr, *IndexExpr;
1868 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001869 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1870 BaseExpr = LHSExp;
1871 IndexExpr = RHSExp;
1872 ResultType = Context.DependentTy;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001873 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001874 BaseExpr = LHSExp;
1875 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001876 ResultType = PTy->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001877 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001878 // Handle the uncommon case of "123[Ptr]".
1879 BaseExpr = RHSExp;
1880 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001881 ResultType = PTy->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00001882 } else if (const ObjCObjectPointerType *PTy =
1883 LHSTy->getAsObjCObjectPointerType()) {
1884 BaseExpr = LHSExp;
1885 IndexExpr = RHSExp;
1886 ResultType = PTy->getPointeeType();
1887 } else if (const ObjCObjectPointerType *PTy =
1888 RHSTy->getAsObjCObjectPointerType()) {
1889 // Handle the uncommon case of "123[Ptr]".
1890 BaseExpr = RHSExp;
1891 IndexExpr = LHSExp;
1892 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001893 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1894 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001895 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001896
Chris Lattner4b009652007-07-25 00:24:17 +00001897 // FIXME: need to deal with const...
1898 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001899 } else if (LHSTy->isArrayType()) {
1900 // If we see an array that wasn't promoted by
1901 // DefaultFunctionArrayConversion, it must be an array that
1902 // wasn't promoted because of the C90 rule that doesn't
1903 // allow promoting non-lvalue arrays. Warn, then
1904 // force the promotion here.
1905 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1906 LHSExp->getSourceRange();
1907 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1908 LHSTy = LHSExp->getType();
1909
1910 BaseExpr = LHSExp;
1911 IndexExpr = RHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001912 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmand4614072009-04-25 23:46:54 +00001913 } else if (RHSTy->isArrayType()) {
1914 // Same as previous, except for 123[f().a] case
1915 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1916 RHSExp->getSourceRange();
1917 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1918 RHSTy = RHSExp->getType();
1919
1920 BaseExpr = RHSExp;
1921 IndexExpr = LHSExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001922 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001923 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001924 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1925 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001926 }
Chris Lattner4b009652007-07-25 00:24:17 +00001927 // C99 6.5.2.1p1
Nate Begemane85f43d2009-08-10 23:49:36 +00001928 if (!(IndexExpr->getType()->isIntegerType() &&
1929 IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001930 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1931 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001932
Douglas Gregor05e28f62009-03-24 19:52:54 +00001933 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1934 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1935 // type. Note that Functions are not objects, and that (in C99 parlance)
1936 // incomplete types are not object types.
1937 if (ResultType->isFunctionType()) {
1938 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1939 << ResultType << BaseExpr->getSourceRange();
1940 return ExprError();
1941 }
Chris Lattner95933c12009-04-24 00:30:45 +00001942
Douglas Gregor05e28f62009-03-24 19:52:54 +00001943 if (!ResultType->isDependentType() &&
Chris Lattner95933c12009-04-24 00:30:45 +00001944 RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type,
Douglas Gregor05e28f62009-03-24 19:52:54 +00001945 BaseExpr->getSourceRange()))
1946 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001947
1948 // Diagnose bad cases where we step over interface counts.
1949 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1950 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1951 << ResultType << BaseExpr->getSourceRange();
1952 return ExprError();
1953 }
1954
Sebastian Redl8b769972009-01-19 00:08:26 +00001955 Base.release();
1956 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001957 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001958 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001959}
1960
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001961QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001962CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001963 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001964 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001965
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001966 // The vector accessor can't exceed the number of elements.
1967 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001968
Mike Stump9afab102009-02-19 03:04:26 +00001969 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001970 // special names that indicate a subset of exactly half the elements are
1971 // to be selected.
1972 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001973
Nate Begeman1486b502009-01-18 01:47:54 +00001974 // This flag determines whether or not CompName has an 's' char prefix,
1975 // indicating that it is a string of hex values to be used as vector indices.
Nate Begemane2ed6f72009-06-25 21:06:09 +00001976 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001977
1978 // Check that we've found one of the special components, or that the component
1979 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001980 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001981 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1982 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001983 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001984 do
1985 compStr++;
1986 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001987 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001988 do
1989 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001990 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001991 }
Nate Begeman1486b502009-01-18 01:47:54 +00001992
Mike Stump9afab102009-02-19 03:04:26 +00001993 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001994 // We didn't get to the end of the string. This means the component names
1995 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001996 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1997 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001998 return QualType();
1999 }
Mike Stump9afab102009-02-19 03:04:26 +00002000
Nate Begeman1486b502009-01-18 01:47:54 +00002001 // Ensure no component accessor exceeds the width of the vector type it
2002 // operates on.
2003 if (!HalvingSwizzle) {
2004 compStr = CompName.getName();
2005
2006 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002007 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00002008
2009 while (*compStr) {
2010 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2011 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2012 << baseType << SourceRange(CompLoc);
2013 return QualType();
2014 }
2015 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002016 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00002017
Nate Begeman1486b502009-01-18 01:47:54 +00002018 // If this is a halving swizzle, verify that the base type has an even
2019 // number of elements.
2020 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002021 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002022 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00002023 return QualType();
2024 }
Mike Stump9afab102009-02-19 03:04:26 +00002025
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002026 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00002027 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002028 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00002029 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00002030 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00002031 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
2032 : CompName.getLength();
2033 if (HexSwizzle)
2034 CompSize--;
2035
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002036 if (CompSize == 1)
2037 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00002038
Nate Begemanaf6ed502008-04-18 23:10:10 +00002039 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00002040 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00002041 // diagostics look bad. We want extended vector types to appear built-in.
2042 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2043 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2044 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00002045 }
2046 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00002047}
2048
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002049static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
2050 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002051 const Selector &Sel,
2052 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002053
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002054 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(&Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002055 return PD;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002056 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002057 return OMD;
2058
2059 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2060 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002061 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
2062 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002063 return D;
2064 }
2065 return 0;
2066}
2067
Steve Naroffc75c1a82009-06-17 22:40:22 +00002068static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002069 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002070 const Selector &Sel,
2071 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002072 // Check protocols on qualified interfaces.
2073 Decl *GDecl = 0;
Steve Naroffc75c1a82009-06-17 22:40:22 +00002074 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002075 E = QIdTy->qual_end(); I != E; ++I) {
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002076 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002077 GDecl = PD;
2078 break;
2079 }
2080 // Also must look for a getter name which uses property syntax.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002081 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002082 GDecl = OMD;
2083 break;
2084 }
2085 }
2086 if (!GDecl) {
Steve Naroffc75c1a82009-06-17 22:40:22 +00002087 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002088 E = QIdTy->qual_end(); I != E; ++I) {
2089 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002090 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002091 if (GDecl)
2092 return GDecl;
2093 }
2094 }
2095 return GDecl;
2096}
Chris Lattner2cb744b2009-02-15 22:43:40 +00002097
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002098/// FindMethodInNestedImplementations - Look up a method in current and
2099/// all base class implementations.
2100///
2101ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
2102 const ObjCInterfaceDecl *IFace,
2103 const Selector &Sel) {
2104 ObjCMethodDecl *Method = 0;
Argiris Kirtzidisb1c4ee52009-07-21 00:06:04 +00002105 if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002106 Method = ImpDecl->getInstanceMethod(Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002107
2108 if (!Method && IFace->getSuperClass())
2109 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
2110 return Method;
2111}
2112
Sebastian Redl8b769972009-01-19 00:08:26 +00002113Action::OwningExprResult
2114Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2115 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002116 IdentifierInfo &Member,
Douglas Gregorda61ad22009-08-06 03:17:00 +00002117 DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2118 // FIXME: handle the CXXScopeSpec for proper lookup of qualified-ids
2119 if (SS && SS->isInvalid())
2120 return ExprError();
2121
Nate Begemane85f43d2009-08-10 23:49:36 +00002122 // Since this might be a postfix expression, get rid of ParenListExprs.
2123 Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2124
Anders Carlssonc154a722009-05-01 19:30:39 +00002125 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00002126 assert(BaseExpr && "no record expression");
Nate Begemane85f43d2009-08-10 23:49:36 +00002127
Steve Naroff137e11d2007-12-16 21:42:28 +00002128 // Perform default conversions.
2129 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00002130
Steve Naroff2cb66382007-07-26 03:11:44 +00002131 QualType BaseType = BaseExpr->getType();
David Chisnall44663db2009-08-17 16:35:33 +00002132 // If this is an Objective-C pseudo-builtin and a definition is provided then
2133 // use that.
2134 if (BaseType->isObjCIdType()) {
2135 // We have an 'id' type. Rather than fall through, we check if this
2136 // is a reference to 'isa'.
2137 if (BaseType != Context.ObjCIdRedefinitionType) {
2138 BaseType = Context.ObjCIdRedefinitionType;
2139 ImpCastExprToType(BaseExpr, BaseType);
2140 }
2141 } else if (BaseType->isObjCClassType() &&
2142 BaseType != Context.ObjCClassRedefinitionType) {
2143 BaseType = Context.ObjCClassRedefinitionType;
2144 ImpCastExprToType(BaseExpr, BaseType);
2145 }
Steve Naroff2cb66382007-07-26 03:11:44 +00002146 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002147
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002148 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2149 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002150 if (OpKind == tok::arrow) {
Anders Carlsson72d3c662009-05-15 23:10:19 +00002151 if (BaseType->isDependentType())
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002152 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2153 BaseExpr, true,
2154 OpLoc,
2155 DeclarationName(&Member),
2156 MemberLoc));
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002157 else if (const PointerType *PT = BaseType->getAs<PointerType>())
Steve Naroff2cb66382007-07-26 03:11:44 +00002158 BaseType = PT->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00002159 else if (BaseType->isObjCObjectPointerType())
2160 ;
Steve Naroff2cb66382007-07-26 03:11:44 +00002161 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002162 return ExprError(Diag(MemberLoc,
2163 diag::err_typecheck_member_reference_arrow)
2164 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002165 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002166 if (BaseType->isDependentType()) {
2167 // Require that the base type isn't a pointer type
2168 // (so we'll report an error for)
2169 // T* t;
2170 // t.f;
2171 //
2172 // In Obj-C++, however, the above expression is valid, since it could be
2173 // accessing the 'f' property if T is an Obj-C interface. The extra check
2174 // allows this, while still reporting an error if T is a struct pointer.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002175 const PointerType *PT = BaseType->getAs<PointerType>();
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002176
2177 if (!PT || (getLangOptions().ObjC1 &&
2178 !PT->getPointeeType()->isRecordType()))
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002179 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2180 BaseExpr, false,
2181 OpLoc,
2182 DeclarationName(&Member),
2183 MemberLoc));
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002184 }
Chris Lattner4b009652007-07-25 00:24:17 +00002185 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002186
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002187 // Handle field access to simple records. This also handles access to fields
2188 // of the ObjC 'id' struct.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002189 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002190 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002191 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002192 diag::err_typecheck_incomplete_tag,
2193 BaseExpr->getSourceRange()))
2194 return ExprError();
2195
Douglas Gregorda61ad22009-08-06 03:17:00 +00002196 DeclContext *DC = RDecl;
2197 if (SS && SS->isSet()) {
2198 // If the member name was a qualified-id, look into the
2199 // nested-name-specifier.
2200 DC = computeDeclContext(*SS, false);
2201
2202 // FIXME: If DC is not computable, we should build a
2203 // CXXUnresolvedMemberExpr.
2204 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2205 }
2206
Steve Naroff2cb66382007-07-26 03:11:44 +00002207 // The record definition is complete, now make sure the member is valid.
Sebastian Redl8b769972009-01-19 00:08:26 +00002208 LookupResult Result
Douglas Gregorda61ad22009-08-06 03:17:00 +00002209 = LookupQualifiedName(DC, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00002210 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002211
Douglas Gregor12431cb2009-08-06 05:28:30 +00002212 if (SS && SS->isSet()) {
Douglas Gregorda61ad22009-08-06 03:17:00 +00002213 QualType BaseTypeCanon
2214 = Context.getCanonicalType(BaseType).getUnqualifiedType();
2215 QualType MemberTypeCanon
2216 = Context.getCanonicalType(
2217 Context.getTypeDeclType(
2218 dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2219
2220 if (BaseTypeCanon != MemberTypeCanon &&
2221 !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2222 return ExprError(Diag(SS->getBeginLoc(),
2223 diag::err_not_direct_base_or_virtual)
2224 << MemberTypeCanon << BaseTypeCanon);
2225 }
2226
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002227 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00002228 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
2229 << &Member << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002230 if (Result.isAmbiguous()) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002231 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
2232 MemberLoc, BaseExpr->getSourceRange());
2233 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002234 }
2235
2236 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002237
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002238 // If the decl being referenced had an error, return an error for this
2239 // sub-expr without emitting another error, in order to avoid cascading
2240 // error cases.
2241 if (MemberDecl->isInvalidDecl())
2242 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002243
Douglas Gregoraa57e862009-02-18 21:56:37 +00002244 // Check the use of this field
2245 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2246 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002247
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002248 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002249 // We may have found a field within an anonymous union or struct
2250 // (C++ [class.union]).
2251 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002252 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002253 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002254
Douglas Gregor82d44772008-12-20 23:49:58 +00002255 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002256 QualType MemberType = FD->getType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002257 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
Douglas Gregor82d44772008-12-20 23:49:58 +00002258 MemberType = Ref->getPointeeType();
2259 else {
Mon P Wang04d89cb2009-07-22 03:08:17 +00002260 unsigned BaseAddrSpace = BaseType.getAddressSpace();
Douglas Gregor82d44772008-12-20 23:49:58 +00002261 unsigned combinedQualifiers =
2262 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002263 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002264 combinedQualifiers &= ~QualType::Const;
2265 MemberType = MemberType.getQualifiedType(combinedQualifiers);
Mon P Wang04d89cb2009-07-22 03:08:17 +00002266 if (BaseAddrSpace != MemberType.getAddressSpace())
2267 MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
Douglas Gregor82d44772008-12-20 23:49:58 +00002268 }
Eli Friedman76b49832008-02-06 22:48:16 +00002269
Douglas Gregorcad27f62009-06-22 23:06:13 +00002270 MarkDeclarationReferenced(MemberLoc, FD);
Fariborz Jahanian843336e2009-07-29 19:40:11 +00002271 if (PerformObjectMemberConversion(BaseExpr, FD))
2272 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002273 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
2274 MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002275 }
2276
Douglas Gregorcad27f62009-06-22 23:06:13 +00002277 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2278 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Steve Naroff774e4152009-01-21 00:14:39 +00002279 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002280 Var, MemberLoc,
2281 Var->getType().getNonReferenceType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002282 }
2283 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2284 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump9afab102009-02-19 03:04:26 +00002285 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002286 MemberFn, MemberLoc,
2287 MemberFn->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002288 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002289 if (OverloadedFunctionDecl *Ovl
2290 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00002291 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Chris Lattner84ad8332009-03-31 08:18:48 +00002292 MemberLoc, Context.OverloadTy));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002293 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2294 MarkDeclarationReferenced(MemberLoc, MemberDecl);
Mike Stump9afab102009-02-19 03:04:26 +00002295 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2296 Enum, MemberLoc, Enum->getType()));
Douglas Gregorcad27f62009-06-22 23:06:13 +00002297 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002298 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002299 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2300 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002301
Douglas Gregor82d44772008-12-20 23:49:58 +00002302 // We found a declaration kind that we didn't expect. This is a
2303 // generic error message that tells the user that she can't refer
2304 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002305 return ExprError(Diag(MemberLoc,
2306 diag::err_typecheck_member_reference_unknown)
2307 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002308 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002309
Steve Naroff329ec222009-07-10 23:34:53 +00002310 // Handle properties on ObjC 'Class' types.
Steve Naroff7982a642009-07-13 17:19:15 +00002311 if (OpKind == tok::period && BaseType->isObjCClassType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00002312 // Also must look for a getter name which uses property syntax.
2313 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2314 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2315 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2316 ObjCMethodDecl *Getter;
2317 // FIXME: need to also look locally in the implementation.
2318 if ((Getter = IFace->lookupClassMethod(Sel))) {
2319 // Check the use of this method.
2320 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2321 return ExprError();
2322 }
2323 // If we found a getter then this may be a valid dot-reference, we
2324 // will look for the matching setter, in case it is needed.
2325 Selector SetterSel =
2326 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2327 PP.getSelectorTable(), &Member);
2328 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2329 if (!Setter) {
2330 // If this reference is in an @implementation, also check for 'private'
2331 // methods.
2332 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2333 }
2334 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002335 if (!Setter)
2336 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff329ec222009-07-10 23:34:53 +00002337
2338 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2339 return ExprError();
2340
2341 if (Getter || Setter) {
2342 QualType PType;
2343
2344 if (Getter)
2345 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002346 else
2347 // Get the expression type from Setter's incoming parameter.
2348 PType = (*(Setter->param_end() -1))->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00002349 // FIXME: we must check that the setter has property type.
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002350 return Owned(new (Context) ObjCImplctSetterGetterRefExpr(Getter, PType,
Steve Naroff329ec222009-07-10 23:34:53 +00002351 Setter, MemberLoc, BaseExpr));
2352 }
2353 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2354 << &Member << BaseType);
2355 }
2356 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002357 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2358 // (*Obj).ivar.
Steve Naroff329ec222009-07-10 23:34:53 +00002359 if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2360 (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2361 const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2362 const ObjCInterfaceType *IFaceT =
2363 OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
Steve Naroff4e743962009-07-16 00:25:06 +00002364 if (IFaceT) {
2365 ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2366 ObjCInterfaceDecl *ClassDeclared;
2367 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(&Member, ClassDeclared);
2368
2369 if (IV) {
2370 // If the decl being referenced had an error, return an error for this
2371 // sub-expr without emitting another error, in order to avoid cascading
2372 // error cases.
2373 if (IV->isInvalidDecl())
2374 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002375
Steve Naroff4e743962009-07-16 00:25:06 +00002376 // Check whether we can reference this field.
2377 if (DiagnoseUseOfDecl(IV, MemberLoc))
2378 return ExprError();
2379 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2380 IV->getAccessControl() != ObjCIvarDecl::Package) {
2381 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2382 if (ObjCMethodDecl *MD = getCurMethodDecl())
2383 ClassOfMethodDecl = MD->getClassInterface();
2384 else if (ObjCImpDecl && getCurFunctionDecl()) {
2385 // Case of a c-function declared inside an objc implementation.
2386 // FIXME: For a c-style function nested inside an objc implementation
2387 // class, there is no implementation context available, so we pass
2388 // down the context as argument to this routine. Ideally, this context
2389 // need be passed down in the AST node and somehow calculated from the
2390 // AST for a function decl.
2391 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2392 if (ObjCImplementationDecl *IMPD =
2393 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2394 ClassOfMethodDecl = IMPD->getClassInterface();
2395 else if (ObjCCategoryImplDecl* CatImplClass =
2396 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2397 ClassOfMethodDecl = CatImplClass->getClassInterface();
2398 }
2399
2400 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2401 if (ClassDeclared != IDecl ||
2402 ClassOfMethodDecl != ClassDeclared)
2403 Diag(MemberLoc, diag::error_private_ivar_access)
2404 << IV->getDeclName();
Mike Stump90fc78e2009-08-04 21:02:39 +00002405 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2406 // @protected
Steve Naroff4e743962009-07-16 00:25:06 +00002407 Diag(MemberLoc, diag::error_protected_ivar_access)
2408 << IV->getDeclName();
Steve Narofff9606572009-03-04 18:34:24 +00002409 }
Steve Naroff4e743962009-07-16 00:25:06 +00002410
2411 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2412 MemberLoc, BaseExpr,
2413 OpKind == tok::arrow));
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002414 }
Steve Naroff4e743962009-07-16 00:25:06 +00002415 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2416 << IDecl->getDeclName() << &Member
2417 << BaseExpr->getSourceRange());
Fariborz Jahanian09772392008-12-13 22:20:28 +00002418 }
Chris Lattnera57cf472008-07-21 04:28:12 +00002419 }
Steve Naroff7bffd372009-07-15 18:40:39 +00002420 // Handle properties on 'id' and qualified "id".
2421 if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2422 BaseType->isObjCQualifiedIdType())) {
2423 const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
2424
Steve Naroff329ec222009-07-10 23:34:53 +00002425 // Check protocols on qualified interfaces.
2426 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2427 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2428 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2429 // Check the use of this declaration
2430 if (DiagnoseUseOfDecl(PD, MemberLoc))
2431 return ExprError();
2432
2433 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2434 MemberLoc, BaseExpr));
2435 }
2436 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2437 // Check the use of this method.
2438 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2439 return ExprError();
2440
2441 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2442 OMD->getResultType(),
2443 OMD, OpLoc, MemberLoc,
2444 NULL, 0));
2445 }
2446 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002447
Steve Naroff329ec222009-07-10 23:34:53 +00002448 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2449 << &Member << BaseType);
2450 }
Chris Lattnere9d71612008-07-21 04:59:05 +00002451 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2452 // pointer to a (potentially qualified) interface type.
Steve Naroff329ec222009-07-10 23:34:53 +00002453 const ObjCObjectPointerType *OPT;
2454 if (OpKind == tok::period &&
2455 (OPT = BaseType->getAsObjCInterfacePointerType())) {
2456 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2457 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
2458
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002459 // Search for a declared property first.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002460 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002461 // Check whether we can reference this property.
2462 if (DiagnoseUseOfDecl(PD, MemberLoc))
2463 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002464 QualType ResTy = PD->getType();
2465 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002466 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002467 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2468 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002469 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002470 MemberLoc, BaseExpr));
2471 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002472 // Check protocols on qualified interfaces.
Steve Naroff8194a542009-07-20 17:56:53 +00002473 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2474 E = OPT->qual_end(); I != E; ++I)
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002475 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002476 // Check whether we can reference this property.
2477 if (DiagnoseUseOfDecl(PD, MemberLoc))
2478 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002479
Steve Naroff774e4152009-01-21 00:14:39 +00002480 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002481 MemberLoc, BaseExpr));
2482 }
Steve Naroff329ec222009-07-10 23:34:53 +00002483 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2484 E = OPT->qual_end(); I != E; ++I)
2485 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
2486 // Check whether we can reference this property.
2487 if (DiagnoseUseOfDecl(PD, MemberLoc))
2488 return ExprError();
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002489
Steve Naroff329ec222009-07-10 23:34:53 +00002490 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2491 MemberLoc, BaseExpr));
2492 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002493 // If that failed, look for an "implicit" property by seeing if the nullary
2494 // selector is implemented.
2495
2496 // FIXME: The logic for looking up nullary and unary selectors should be
2497 // shared with the code in ActOnInstanceMessage.
2498
2499 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002500 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002501
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002502 // If this reference is in an @implementation, check for 'private' methods.
2503 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002504 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002505
Steve Naroff04151f32008-10-22 19:16:27 +00002506 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002507 if (!Getter)
2508 Getter = IFace->getCategoryInstanceMethod(Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002509 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002510 // Check if we can reference this property.
2511 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2512 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002513 }
2514 // If we found a getter then this may be a valid dot-reference, we
2515 // will look for the matching setter, in case it is needed.
2516 Selector SetterSel =
2517 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2518 PP.getSelectorTable(), &Member);
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00002519 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002520 if (!Setter) {
2521 // If this reference is in an @implementation, also check for 'private'
2522 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002523 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002524 }
2525 // Look through local category implementations associated with the class.
Argiris Kirtzidis20096862009-07-21 00:06:20 +00002526 if (!Setter)
2527 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002528
Steve Naroffdede0c92009-03-11 13:48:17 +00002529 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2530 return ExprError();
2531
2532 if (Getter || Setter) {
2533 QualType PType;
2534
2535 if (Getter)
2536 PType = Getter->getResultType();
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002537 else
2538 // Get the expression type from Setter's incoming parameter.
2539 PType = (*(Setter->param_end() -1))->getType();
Steve Naroffdede0c92009-03-11 13:48:17 +00002540 // FIXME: we must check that the setter has property type.
Fariborz Jahanian1c4da452009-08-18 20:50:23 +00002541 return Owned(new (Context) ObjCImplctSetterGetterRefExpr(Getter, PType,
Steve Naroffdede0c92009-03-11 13:48:17 +00002542 Setter, MemberLoc, BaseExpr));
2543 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002544 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2545 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002546 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002547
Steve Naroff29d293b2009-07-24 17:54:45 +00002548 // Handle the following exceptional case (*Obj).isa.
2549 if (OpKind == tok::period &&
2550 BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
Steve Naroffbbe4f962009-07-29 14:06:03 +00002551 Member.isStr("isa"))
Steve Naroff29d293b2009-07-24 17:54:45 +00002552 return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2553 Context.getObjCIdType()));
2554
Chris Lattnera57cf472008-07-21 04:28:12 +00002555 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002556 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00002557 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2558 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002559 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002560 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002561 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002562 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002563
Douglas Gregor762da552009-03-27 06:00:30 +00002564 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2565 << BaseType << BaseExpr->getSourceRange();
2566
2567 // If the user is trying to apply -> or . to a function or function
2568 // pointer, it's probably because they forgot parentheses to call
2569 // the function. Suggest the addition of those parentheses.
2570 if (BaseType == Context.OverloadTy ||
2571 BaseType->isFunctionType() ||
2572 (BaseType->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002573 BaseType->getAs<PointerType>()->isFunctionType())) {
Douglas Gregor762da552009-03-27 06:00:30 +00002574 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2575 Diag(Loc, diag::note_member_reference_needs_call)
2576 << CodeModificationHint::CreateInsertion(Loc, "()");
2577 }
2578
2579 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002580}
2581
Douglas Gregor3257fb52008-12-22 05:46:06 +00002582/// ConvertArgumentsForCall - Converts the arguments specified in
2583/// Args/NumArgs to the parameter types of the function FDecl with
2584/// function prototype Proto. Call is the call expression itself, and
2585/// Fn is the function expression. For a C++ member function, this
2586/// routine does not attempt to convert the object argument. Returns
2587/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002588bool
2589Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002590 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002591 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002592 Expr **Args, unsigned NumArgs,
2593 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002594 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002595 // assignment, to the types of the corresponding parameter, ...
2596 unsigned NumArgsInProto = Proto->getNumArgs();
2597 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002598 bool Invalid = false;
2599
Douglas Gregor3257fb52008-12-22 05:46:06 +00002600 // If too few arguments are available (and we don't have default
2601 // arguments for the remaining parameters), don't make the call.
2602 if (NumArgs < NumArgsInProto) {
2603 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2604 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2605 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2606 // Use default arguments for missing arguments
2607 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002608 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002609 }
2610
2611 // If too many are passed and not variadic, error on the extras and drop
2612 // them.
2613 if (NumArgs > NumArgsInProto) {
2614 if (!Proto->isVariadic()) {
2615 Diag(Args[NumArgsInProto]->getLocStart(),
2616 diag::err_typecheck_call_too_many_args)
2617 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2618 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2619 Args[NumArgs-1]->getLocEnd());
2620 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002621 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002622 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002623 }
2624 NumArgsToCheck = NumArgsInProto;
2625 }
Mike Stump9afab102009-02-19 03:04:26 +00002626
Douglas Gregor3257fb52008-12-22 05:46:06 +00002627 // Continue to check argument types (even if we have too few/many args).
2628 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2629 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002630
Douglas Gregor3257fb52008-12-22 05:46:06 +00002631 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002632 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002633 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002634
Eli Friedman83dec9e2009-03-22 22:00:50 +00002635 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2636 ProtoArgType,
2637 diag::err_call_incomplete_argument,
2638 Arg->getSourceRange()))
2639 return true;
2640
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002641 // Pass the argument.
2642 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2643 return true;
Anders Carlssona116e6e2009-06-12 16:51:40 +00002644 } else {
2645 if (FDecl->getParamDecl(i)->hasUnparsedDefaultArg()) {
2646 Diag (Call->getSourceRange().getBegin(),
2647 diag::err_use_of_default_argument_to_function_declared_later) <<
2648 FDecl << cast<CXXRecordDecl>(FDecl->getDeclContext())->getDeclName();
2649 Diag(UnparsedDefaultArgLocs[FDecl->getParamDecl(i)],
2650 diag::note_default_argument_declared_here);
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00002651 } else {
2652 Expr *DefaultExpr = FDecl->getParamDecl(i)->getDefaultArg();
2653
2654 // If the default expression creates temporaries, we need to
2655 // push them to the current stack of expression temporaries so they'll
2656 // be properly destroyed.
2657 if (CXXExprWithTemporaries *E
2658 = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2659 assert(!E->shouldDestroyTemporaries() &&
2660 "Can't destroy temporaries in a default argument expr!");
2661 for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2662 ExprTemporaries.push_back(E->getTemporary(I));
2663 }
Anders Carlssona116e6e2009-06-12 16:51:40 +00002664 }
Anders Carlsson37bb2bd2009-06-16 03:37:31 +00002665
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002666 // We already type-checked the argument, so we know it works.
Anders Carlsson3d752db2009-08-14 18:30:22 +00002667 Arg = CXXDefaultArgExpr::Create(Context, FDecl->getParamDecl(i));
Anders Carlssona116e6e2009-06-12 16:51:40 +00002668 }
2669
Douglas Gregor3257fb52008-12-22 05:46:06 +00002670 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002671
Douglas Gregor3257fb52008-12-22 05:46:06 +00002672 Call->setArg(i, Arg);
2673 }
Mike Stump9afab102009-02-19 03:04:26 +00002674
Douglas Gregor3257fb52008-12-22 05:46:06 +00002675 // If this is a variadic call, handle args passed through "...".
2676 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002677 VariadicCallType CallType = VariadicFunction;
2678 if (Fn->getType()->isBlockPointerType())
2679 CallType = VariadicBlock; // Block
2680 else if (isa<MemberExpr>(Fn))
2681 CallType = VariadicMethod;
2682
Douglas Gregor3257fb52008-12-22 05:46:06 +00002683 // Promote the arguments (C99 6.5.2.2p7).
2684 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2685 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002686 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002687 Call->setArg(i, Arg);
2688 }
2689 }
2690
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002691 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002692}
2693
Steve Naroff87d58b42007-09-16 03:34:24 +00002694/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002695/// This provides the location of the left/right parens and a list of comma
2696/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002697Action::OwningExprResult
2698Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2699 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002700 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002701 unsigned NumArgs = args.size();
Nate Begemane85f43d2009-08-10 23:49:36 +00002702
2703 // Since this might be a postfix expression, get rid of ParenListExprs.
2704 fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2705
Anders Carlssonc154a722009-05-01 19:30:39 +00002706 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002707 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002708 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002709 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002710 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002711 DeclarationName UnqualifiedName;
Nate Begemane85f43d2009-08-10 23:49:36 +00002712
Douglas Gregor3257fb52008-12-22 05:46:06 +00002713 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002714 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002715 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002716 // FIXME: Will need to cache the results of name lookup (including ADL) in
2717 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002718 bool Dependent = false;
2719 if (Fn->isTypeDependent())
2720 Dependent = true;
2721 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2722 Dependent = true;
2723
2724 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002725 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002726 Context.DependentTy, RParenLoc));
2727
2728 // Determine whether this is a call to an object (C++ [over.call.object]).
2729 if (Fn->getType()->isRecordType())
2730 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2731 CommaLocs, RParenLoc));
2732
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002733 // Determine whether this is a call to a member function.
Douglas Gregorb60eb752009-06-25 22:08:12 +00002734 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2735 NamedDecl *MemDecl = MemExpr->getMemberDecl();
2736 if (isa<OverloadedFunctionDecl>(MemDecl) ||
2737 isa<CXXMethodDecl>(MemDecl) ||
2738 (isa<FunctionTemplateDecl>(MemDecl) &&
2739 isa<CXXMethodDecl>(
2740 cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
Sebastian Redl8b769972009-01-19 00:08:26 +00002741 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2742 CommaLocs, RParenLoc));
Douglas Gregorb60eb752009-06-25 22:08:12 +00002743 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00002744 }
2745
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002746 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002747 // Also, in C++, keep track of whether we should perform argument-dependent
2748 // lookup and whether there were any explicitly-specified template arguments.
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002749 Expr *FnExpr = Fn;
2750 bool ADL = true;
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002751 bool HasExplicitTemplateArgs = 0;
2752 const TemplateArgument *ExplicitTemplateArgs = 0;
2753 unsigned NumExplicitTemplateArgs = 0;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002754 while (true) {
2755 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2756 FnExpr = IcExpr->getSubExpr();
2757 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002758 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002759 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002760 ADL = false;
2761 FnExpr = PExpr->getSubExpr();
2762 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002763 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002764 == UnaryOperator::AddrOf) {
2765 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Douglas Gregor28857752009-06-30 22:34:41 +00002766 } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002767 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2768 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
Douglas Gregor28857752009-06-30 22:34:41 +00002769 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002770 break;
Mike Stump9afab102009-02-19 03:04:26 +00002771 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002772 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2773 UnqualifiedName = DepName->getName();
2774 break;
Douglas Gregor28857752009-06-30 22:34:41 +00002775 } else if (TemplateIdRefExpr *TemplateIdRef
2776 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2777 NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
Douglas Gregor6631cb42009-07-29 18:26:50 +00002778 if (!NDecl)
2779 NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002780 HasExplicitTemplateArgs = true;
2781 ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2782 NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2783
2784 // C++ [temp.arg.explicit]p6:
2785 // [Note: For simple function names, argument dependent lookup (3.4.2)
2786 // applies even when the function name is not visible within the
2787 // scope of the call. This is because the call still has the syntactic
2788 // form of a function call (3.4.1). But when a function template with
2789 // explicit template arguments is used, the call does not have the
2790 // correct syntactic form unless there is a function template with
2791 // that name visible at the point of the call. If no such name is
2792 // visible, the call is not syntactically well-formed and
2793 // argument-dependent lookup does not apply. If some such name is
2794 // visible, argument dependent lookup applies and additional function
2795 // templates may be found in other namespaces.
2796 //
2797 // The summary of this paragraph is that, if we get to this point and the
2798 // template-id was not a qualified name, then argument-dependent lookup
2799 // is still possible.
2800 if (TemplateIdRef->getQualifier())
2801 ADL = false;
Douglas Gregor28857752009-06-30 22:34:41 +00002802 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002803 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002804 // Any kind of name that does not refer to a declaration (or
2805 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2806 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002807 break;
2808 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002809 }
Mike Stump9afab102009-02-19 03:04:26 +00002810
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002811 OverloadedFunctionDecl *Ovl = 0;
Douglas Gregorb60eb752009-06-25 22:08:12 +00002812 FunctionTemplateDecl *FunctionTemplate = 0;
Douglas Gregor28857752009-06-30 22:34:41 +00002813 if (NDecl) {
2814 FDecl = dyn_cast<FunctionDecl>(NDecl);
2815 if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
Douglas Gregorb60eb752009-06-25 22:08:12 +00002816 FDecl = FunctionTemplate->getTemplatedDecl();
2817 else
Douglas Gregor28857752009-06-30 22:34:41 +00002818 FDecl = dyn_cast<FunctionDecl>(NDecl);
2819 Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002820 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002821
Douglas Gregorb60eb752009-06-25 22:08:12 +00002822 if (Ovl || FunctionTemplate ||
2823 (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002824 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002825 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002826 ADL = false;
2827
Douglas Gregorfcb19192009-02-11 23:02:49 +00002828 // We don't perform ADL in C.
2829 if (!getLangOptions().CPlusPlus)
2830 ADL = false;
2831
Douglas Gregorb60eb752009-06-25 22:08:12 +00002832 if (Ovl || FunctionTemplate || ADL) {
Douglas Gregorc9a03b72009-06-30 23:57:56 +00002833 FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2834 HasExplicitTemplateArgs,
2835 ExplicitTemplateArgs,
2836 NumExplicitTemplateArgs,
2837 LParenLoc, Args, NumArgs, CommaLocs,
2838 RParenLoc, ADL);
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002839 if (!FDecl)
2840 return ExprError();
2841
2842 // Update Fn to refer to the actual function selected.
2843 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002844 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor28857752009-06-30 22:34:41 +00002845 = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002846 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2847 QDRExpr->getLocation(),
2848 false, false,
2849 QDRExpr->getQualifierRange(),
2850 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002851 else
Mike Stump9afab102009-02-19 03:04:26 +00002852 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002853 Fn->getSourceRange().getBegin());
2854 Fn->Destroy(Context);
2855 Fn = NewFn;
2856 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002857 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002858
2859 // Promote the function operand.
2860 UsualUnaryConversions(Fn);
2861
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002862 // Make the call expr early, before semantic checks. This guarantees cleanup
2863 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002864 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2865 Args, NumArgs,
2866 Context.BoolTy,
2867 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002868
Steve Naroffd6163f32008-09-05 22:11:13 +00002869 const FunctionType *FuncT;
2870 if (!Fn->getType()->isBlockPointerType()) {
2871 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2872 // have type pointer to function".
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002873 const PointerType *PT = Fn->getType()->getAs<PointerType>();
Steve Naroffd6163f32008-09-05 22:11:13 +00002874 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002875 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2876 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002877 FuncT = PT->getPointeeType()->getAsFunctionType();
2878 } else { // This is a block call.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00002879 FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
Steve Naroffd6163f32008-09-05 22:11:13 +00002880 getAsFunctionType();
2881 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002882 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002883 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2884 << Fn->getType() << Fn->getSourceRange());
2885
Eli Friedman83dec9e2009-03-22 22:00:50 +00002886 // Check for a valid return type
2887 if (!FuncT->getResultType()->isVoidType() &&
2888 RequireCompleteType(Fn->getSourceRange().getBegin(),
2889 FuncT->getResultType(),
2890 diag::err_call_incomplete_return,
2891 TheCall->getSourceRange()))
2892 return ExprError();
2893
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002894 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002895 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002896
Douglas Gregor4fa58902009-02-26 23:50:07 +00002897 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002898 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002899 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002900 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002901 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002902 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002903
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002904 if (FDecl) {
2905 // Check if we have too few/too many template arguments, based
2906 // on our knowledge of the function definition.
2907 const FunctionDecl *Def = 0;
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00002908 if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002909 const FunctionProtoType *Proto =
2910 Def->getType()->getAsFunctionProtoType();
2911 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2912 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2913 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2914 }
2915 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002916 }
2917
Steve Naroffdb65e052007-08-28 23:30:39 +00002918 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002919 for (unsigned i = 0; i != NumArgs; i++) {
2920 Expr *Arg = Args[i];
2921 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002922 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2923 Arg->getType(),
2924 diag::err_call_incomplete_argument,
2925 Arg->getSourceRange()))
2926 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002927 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002928 }
Chris Lattner4b009652007-07-25 00:24:17 +00002929 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002930
Douglas Gregor3257fb52008-12-22 05:46:06 +00002931 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2932 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002933 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2934 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002935
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002936 // Check for sentinels
2937 if (NDecl)
2938 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Anders Carlsson7fb13802009-08-16 01:56:34 +00002939
Chris Lattner2e64c072007-08-10 20:18:51 +00002940 // Do special checking on direct calls to functions.
Anders Carlsson7fb13802009-08-16 01:56:34 +00002941 if (FDecl) {
2942 if (CheckFunctionCall(FDecl, TheCall.get()))
2943 return ExprError();
2944
2945 if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2946 return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2947 } else if (NDecl) {
2948 if (CheckBlockCall(NDecl, TheCall.get()))
2949 return ExprError();
2950 }
Chris Lattner2e64c072007-08-10 20:18:51 +00002951
Anders Carlsson54ad8a02009-08-16 03:06:32 +00002952 return MaybeBindToTemporary(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002953}
2954
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002955Action::OwningExprResult
2956Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2957 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002958 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00002959 //FIXME: Preserve type source info.
2960 QualType literalType = GetTypeFromParser(Ty);
Chris Lattner4b009652007-07-25 00:24:17 +00002961 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002962 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002963 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002964
Eli Friedman8c2173d2008-05-20 05:22:08 +00002965 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002966 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002967 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2968 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00002969 } else if (!literalType->isDependentType() &&
2970 RequireCompleteType(LParenLoc, literalType,
2971 diag::err_typecheck_decl_incomplete_type,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002972 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002973 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002974
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002975 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002976 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002977 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002978
Chris Lattnere5cb5862008-12-04 23:50:19 +00002979 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002980 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002981 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002982 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002983 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002984 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002985 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002986 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002987}
2988
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002989Action::OwningExprResult
2990Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002991 SourceLocation RBraceLoc) {
2992 unsigned NumInit = initlist.size();
2993 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002994
Steve Naroff0acc9c92007-09-15 18:49:24 +00002995 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002996 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002997
Mike Stump9afab102009-02-19 03:04:26 +00002998 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002999 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00003000 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003001 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00003002}
3003
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003004/// CheckCastTypes - Check type constraints for casting between types.
Sebastian Redlc358b622009-07-29 13:50:23 +00003005bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
Anders Carlsson9583fa72009-08-07 22:21:05 +00003006 CastExpr::CastKind& Kind, bool FunctionalStyle) {
Sebastian Redl0e35d042009-07-25 15:41:38 +00003007 if (getLangOptions().CPlusPlus)
Anders Carlsson9583fa72009-08-07 22:21:05 +00003008 return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle);
Sebastian Redl0e35d042009-07-25 15:41:38 +00003009
Eli Friedman01e0f652009-08-15 19:02:19 +00003010 DefaultFunctionArrayConversion(castExpr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003011
3012 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3013 // type needs to be scalar.
3014 if (castType->isVoidType()) {
3015 // Cast to void allows any expr type.
3016 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003017 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3018 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3019 (castType->isStructureType() || castType->isUnionType())) {
3020 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00003021 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003022 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3023 << castType << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00003024 Kind = CastExpr::CK_NoOp;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003025 } else if (castType->isUnionType()) {
3026 // GCC cast to union extension
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003027 RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003028 RecordDecl::field_iterator Field, FieldEnd;
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003029 for (Field = RD->field_begin(), FieldEnd = RD->field_end();
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003030 Field != FieldEnd; ++Field) {
3031 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3032 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3033 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3034 << castExpr->getSourceRange();
3035 break;
3036 }
3037 }
3038 if (Field == FieldEnd)
3039 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3040 << castExpr->getType() << castExpr->getSourceRange();
Anders Carlssonb4671fa2009-08-07 23:22:37 +00003041 Kind = CastExpr::CK_ToUnion;
Seo Sanghyeon27b33952009-01-15 04:51:39 +00003042 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003043 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00003044 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003045 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003046 }
Mike Stump9afab102009-02-19 03:04:26 +00003047 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003048 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00003049 return Diag(castExpr->getLocStart(),
3050 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003051 << castExpr->getType() << castExpr->getSourceRange();
Nate Begemanbd42e022009-06-26 00:50:28 +00003052 } else if (castType->isExtVectorType()) {
3053 if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003054 return true;
3055 } else if (castType->isVectorType()) {
3056 if (CheckVectorCast(TyR, castType, castExpr->getType()))
3057 return true;
Nate Begemanbd42e022009-06-26 00:50:28 +00003058 } else if (castExpr->getType()->isVectorType()) {
3059 if (CheckVectorCast(TyR, castExpr->getType(), castType))
3060 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00003061 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00003062 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00003063 } else if (!castType->isArithmeticType()) {
3064 QualType castExprType = castExpr->getType();
3065 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3066 return Diag(castExpr->getLocStart(),
3067 diag::err_cast_pointer_from_non_pointer_int)
3068 << castExprType << castExpr->getSourceRange();
3069 } else if (!castExpr->getType()->isArithmeticType()) {
3070 if (!castType->isIntegralType() && castType->isArithmeticType())
3071 return Diag(castExpr->getLocStart(),
3072 diag::err_cast_pointer_to_non_pointer_int)
3073 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003074 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00003075 if (isa<ObjCSelectorExpr>(castExpr))
3076 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00003077 return false;
3078}
3079
Chris Lattnerd1f26b32007-12-20 00:44:32 +00003080bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003081 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00003082
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003083 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003084 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003085 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00003086 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003087 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00003088 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003089 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003090 } else
3091 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00003092 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003093 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00003094
Anders Carlssonf257b4c2007-11-27 05:51:55 +00003095 return false;
3096}
3097
Nate Begemanbd42e022009-06-26 00:50:28 +00003098bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3099 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3100
Nate Begeman9e063702009-06-27 22:05:55 +00003101 // If SrcTy is a VectorType, the total size must match to explicitly cast to
3102 // an ExtVectorType.
Nate Begemanbd42e022009-06-26 00:50:28 +00003103 if (SrcTy->isVectorType()) {
3104 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3105 return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3106 << DestTy << SrcTy << R;
3107 return false;
3108 }
3109
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003110 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanbd42e022009-06-26 00:50:28 +00003111 // conversion will take place first from scalar to elt type, and then
3112 // splat from elt type to vector.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003113 if (SrcTy->isPointerType())
3114 return Diag(R.getBegin(),
3115 diag::err_invalid_conversion_between_vector_and_scalar)
3116 << DestTy << SrcTy << R;
Nate Begemanbd42e022009-06-26 00:50:28 +00003117 return false;
3118}
3119
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003120Action::OwningExprResult
Nate Begemane85f43d2009-08-10 23:49:36 +00003121Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003122 SourceLocation RParenLoc, ExprArg Op) {
Anders Carlsson9583fa72009-08-07 22:21:05 +00003123 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3124
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003125 assert((Ty != 0) && (Op.get() != 0) &&
3126 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00003127
Nate Begemane85f43d2009-08-10 23:49:36 +00003128 Expr *castExpr = (Expr *)Op.get();
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00003129 //FIXME: Preserve type source info.
3130 QualType castType = GetTypeFromParser(Ty);
Nate Begemane85f43d2009-08-10 23:49:36 +00003131
3132 // If the Expr being casted is a ParenListExpr, handle it specially.
3133 if (isa<ParenListExpr>(castExpr))
3134 return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
Chris Lattner4b009652007-07-25 00:24:17 +00003135
Anders Carlsson9583fa72009-08-07 22:21:05 +00003136 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
3137 Kind))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003138 return ExprError();
Nate Begemane85f43d2009-08-10 23:49:36 +00003139
3140 Op.release();
Sebastian Redl0e35d042009-07-25 15:41:38 +00003141 return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
Anders Carlsson9583fa72009-08-07 22:21:05 +00003142 Kind, castExpr, castType,
3143 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00003144}
3145
Nate Begemane85f43d2009-08-10 23:49:36 +00003146/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3147/// of comma binary operators.
3148Action::OwningExprResult
3149Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3150 Expr *expr = EA.takeAs<Expr>();
3151 ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3152 if (!E)
3153 return Owned(expr);
3154
3155 OwningExprResult Result(*this, E->getExpr(0));
3156
3157 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3158 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3159 Owned(E->getExpr(i)));
3160
3161 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3162}
3163
3164Action::OwningExprResult
3165Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3166 SourceLocation RParenLoc, ExprArg Op,
3167 QualType Ty) {
3168 ParenListExpr *PE = (ParenListExpr *)Op.get();
3169
3170 // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3171 // then handle it as such.
3172 if (getLangOptions().AltiVec && Ty->isVectorType()) {
3173 if (PE->getNumExprs() == 0) {
3174 Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3175 return ExprError();
3176 }
3177
3178 llvm::SmallVector<Expr *, 8> initExprs;
3179 for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3180 initExprs.push_back(PE->getExpr(i));
3181
3182 // FIXME: This means that pretty-printing the final AST will produce curly
3183 // braces instead of the original commas.
3184 Op.release();
3185 InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3186 initExprs.size(), RParenLoc);
3187 E->setType(Ty);
3188 return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3189 Owned(E));
3190 } else {
3191 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3192 // sequence of BinOp comma operators.
3193 Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3194 return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3195 }
3196}
3197
3198Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3199 SourceLocation R,
3200 MultiExprArg Val) {
3201 unsigned nexprs = Val.size();
3202 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3203 assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3204 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3205 return Owned(expr);
3206}
3207
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00003208/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3209/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00003210/// C99 6.5.15
3211QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3212 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00003213 // C++ is sufficiently different to merit its own checker.
3214 if (getLangOptions().CPlusPlus)
3215 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3216
Chris Lattnere2897262009-02-18 04:28:32 +00003217 UsualUnaryConversions(Cond);
3218 UsualUnaryConversions(LHS);
3219 UsualUnaryConversions(RHS);
3220 QualType CondTy = Cond->getType();
3221 QualType LHSTy = LHS->getType();
3222 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003223
3224 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00003225 if (!CondTy->isScalarType()) { // C99 6.5.15p2
3226 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3227 << CondTy;
3228 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003229 }
Mike Stump9afab102009-02-19 03:04:26 +00003230
Chris Lattner992ae932008-01-06 22:42:25 +00003231 // Now check the two expressions.
Nate Begemane85f43d2009-08-10 23:49:36 +00003232 if (LHSTy->isVectorType() || RHSTy->isVectorType())
3233 return CheckVectorOperands(QuestionLoc, LHS, RHS);
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00003234
Chris Lattner992ae932008-01-06 22:42:25 +00003235 // If both operands have arithmetic type, do the usual arithmetic conversions
3236 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00003237 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3238 UsualArithmeticConversions(LHS, RHS);
3239 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003240 }
Mike Stump9afab102009-02-19 03:04:26 +00003241
Chris Lattner992ae932008-01-06 22:42:25 +00003242 // If both operands are the same structure or union type, the result is that
3243 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003244 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
3245 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner98a425c2007-11-26 01:40:58 +00003246 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00003247 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00003248 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00003249 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00003250 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00003251 }
Mike Stump9afab102009-02-19 03:04:26 +00003252
Chris Lattner992ae932008-01-06 22:42:25 +00003253 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00003254 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00003255 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3256 if (!LHSTy->isVoidType())
3257 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3258 << RHS->getSourceRange();
3259 if (!RHSTy->isVoidType())
3260 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3261 << LHS->getSourceRange();
3262 ImpCastExprToType(LHS, Context.VoidTy);
3263 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00003264 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00003265 }
Steve Naroff12ebf272008-01-08 01:11:38 +00003266 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3267 // the type of the other operand."
Steve Naroff79ae19a2009-07-14 18:25:06 +00003268 if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003269 RHS->isNullPointerConstant(Context)) {
3270 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3271 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003272 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00003273 if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
Chris Lattnere2897262009-02-18 04:28:32 +00003274 LHS->isNullPointerConstant(Context)) {
3275 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3276 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00003277 }
David Chisnall44663db2009-08-17 16:35:33 +00003278 // Handle things like Class and struct objc_class*. Here we case the result
3279 // to the pseudo-builtin, because that will be implicitly cast back to the
3280 // redefinition type if an attempt is made to access its fields.
3281 if (LHSTy->isObjCClassType() &&
3282 (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3283 ImpCastExprToType(RHS, LHSTy);
3284 return LHSTy;
3285 }
3286 if (RHSTy->isObjCClassType() &&
3287 (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3288 ImpCastExprToType(LHS, RHSTy);
3289 return RHSTy;
3290 }
3291 // And the same for struct objc_object* / id
3292 if (LHSTy->isObjCIdType() &&
3293 (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3294 ImpCastExprToType(RHS, LHSTy);
3295 return LHSTy;
3296 }
3297 if (RHSTy->isObjCIdType() &&
3298 (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3299 ImpCastExprToType(LHS, RHSTy);
3300 return RHSTy;
3301 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003302 // Handle block pointer types.
3303 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3304 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3305 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3306 QualType destType = Context.getPointerType(Context.VoidTy);
3307 ImpCastExprToType(LHS, destType);
3308 ImpCastExprToType(RHS, destType);
3309 return destType;
3310 }
3311 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3312 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3313 return QualType();
Mike Stumpe97a8542009-05-07 03:14:14 +00003314 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003315 // We have 2 block pointer types.
3316 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3317 // Two identical block pointer types are always compatible.
Mike Stumpe97a8542009-05-07 03:14:14 +00003318 return LHSTy;
3319 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003320 // The block pointer types aren't identical, continue checking.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003321 QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3322 QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003323
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003324 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3325 rhptee.getUnqualifiedType())) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003326 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3327 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3328 // In this situation, we assume void* type. No especially good
3329 // reason, but this is what gcc does, and we do have to pick
3330 // to get a consistent AST.
3331 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3332 ImpCastExprToType(LHS, incompatTy);
3333 ImpCastExprToType(RHS, incompatTy);
3334 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003335 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003336 // The block pointer types are compatible.
3337 ImpCastExprToType(LHS, LHSTy);
3338 ImpCastExprToType(RHS, LHSTy);
Steve Naroff6ba22682009-04-08 17:05:15 +00003339 return LHSTy;
3340 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003341 // Check constraints for Objective-C object pointers types.
Steve Naroff329ec222009-07-10 23:34:53 +00003342 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003343
3344 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3345 // Two identical object pointer types are always compatible.
3346 return LHSTy;
3347 }
Steve Naroff329ec222009-07-10 23:34:53 +00003348 const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3349 const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003350 QualType compositeType = LHSTy;
3351
3352 // If both operands are interfaces and either operand can be
3353 // assigned to the other, use that type as the composite
3354 // type. This allows
3355 // xxx ? (A*) a : (B*) b
3356 // where B is a subclass of A.
3357 //
3358 // Additionally, as for assignment, if either type is 'id'
3359 // allow silent coercion. Finally, if the types are
3360 // incompatible then make sure to use 'id' as the composite
3361 // type so the result is acceptable for sending messages to.
3362
3363 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3364 // It could return the composite type.
Steve Naroff329ec222009-07-10 23:34:53 +00003365 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003366 compositeType = LHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003367 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003368 compositeType = RHSTy;
Steve Naroff329ec222009-07-10 23:34:53 +00003369 } else if ((LHSTy->isObjCQualifiedIdType() ||
3370 RHSTy->isObjCQualifiedIdType()) &&
Steve Naroff99eb86b2009-07-23 01:01:38 +00003371 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
Steve Naroff329ec222009-07-10 23:34:53 +00003372 // Need to handle "id<xx>" explicitly.
3373 // GCC allows qualified id and any Objective-C type to devolve to
3374 // id. Currently localizing to here until clear this should be
3375 // part of ObjCQualifiedIdTypesAreCompatible.
3376 compositeType = Context.getObjCIdType();
3377 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003378 compositeType = Context.getObjCIdType();
3379 } else {
3380 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3381 << LHSTy << RHSTy
3382 << LHS->getSourceRange() << RHS->getSourceRange();
3383 QualType incompatTy = Context.getObjCIdType();
3384 ImpCastExprToType(LHS, incompatTy);
3385 ImpCastExprToType(RHS, incompatTy);
3386 return incompatTy;
3387 }
3388 // The object pointer types are compatible.
3389 ImpCastExprToType(LHS, compositeType);
3390 ImpCastExprToType(RHS, compositeType);
3391 return compositeType;
3392 }
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003393 // Check Objective-C object pointer types and 'void *'
3394 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003395 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003396 QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3397 QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3398 QualType destType = Context.getPointerType(destPointee);
3399 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3400 ImpCastExprToType(RHS, destType); // promote to void*
3401 return destType;
3402 }
3403 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3404 QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003405 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff4ace8ac2009-07-29 15:09:39 +00003406 QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3407 QualType destType = Context.getPointerType(destPointee);
3408 ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3409 ImpCastExprToType(LHS, destType); // promote to void*
3410 return destType;
3411 }
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003412 // Check constraints for C object pointers types (C99 6.5.15p3,6).
3413 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3414 // get the "pointed to" types
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003415 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3416 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroff5ca84bc2009-07-01 14:36:47 +00003417
3418 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3419 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3420 // Figure out necessary qualifiers (C99 6.5.15p6)
3421 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3422 QualType destType = Context.getPointerType(destPointee);
3423 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3424 ImpCastExprToType(RHS, destType); // promote to void*
3425 return destType;
3426 }
3427 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3428 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3429 QualType destType = Context.getPointerType(destPointee);
3430 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3431 ImpCastExprToType(RHS, destType); // promote to void*
3432 return destType;
3433 }
3434
3435 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3436 // Two identical pointer types are always compatible.
3437 return LHSTy;
3438 }
3439 if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3440 rhptee.getUnqualifiedType())) {
3441 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3442 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3443 // In this situation, we assume void* type. No especially good
3444 // reason, but this is what gcc does, and we do have to pick
3445 // to get a consistent AST.
3446 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3447 ImpCastExprToType(LHS, incompatTy);
3448 ImpCastExprToType(RHS, incompatTy);
3449 return incompatTy;
3450 }
3451 // The pointer types are compatible.
3452 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3453 // differently qualified versions of compatible types, the result type is
3454 // a pointer to an appropriately qualified version of the *composite*
3455 // type.
3456 // FIXME: Need to calculate the composite type.
3457 // FIXME: Need to add qualifiers
3458 ImpCastExprToType(LHS, LHSTy);
3459 ImpCastExprToType(RHS, LHSTy);
3460 return LHSTy;
3461 }
3462
3463 // GCC compatibility: soften pointer/integer mismatch.
3464 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3465 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3466 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3467 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3468 return RHSTy;
3469 }
3470 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3471 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3472 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3473 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3474 return LHSTy;
3475 }
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003476
Chris Lattner992ae932008-01-06 22:42:25 +00003477 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003478 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3479 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003480 return QualType();
3481}
3482
Steve Naroff87d58b42007-09-16 03:34:24 +00003483/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003484/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003485Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3486 SourceLocation ColonLoc,
3487 ExprArg Cond, ExprArg LHS,
3488 ExprArg RHS) {
3489 Expr *CondExpr = (Expr *) Cond.get();
3490 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003491
3492 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3493 // was the condition.
3494 bool isLHSNull = LHSExpr == 0;
3495 if (isLHSNull)
3496 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003497
3498 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003499 RHSExpr, QuestionLoc);
3500 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003501 return ExprError();
3502
3503 Cond.release();
3504 LHS.release();
3505 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00003506 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00003507 isLHSNull ? 0 : LHSExpr,
3508 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003509}
3510
Chris Lattner4b009652007-07-25 00:24:17 +00003511// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003512// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003513// routine is it effectively iqnores the qualifiers on the top level pointee.
3514// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3515// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003516Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003517Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3518 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003519
David Chisnall44663db2009-08-17 16:35:33 +00003520 if ((lhsType->isObjCClassType() &&
3521 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3522 (rhsType->isObjCClassType() &&
3523 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3524 return Compatible;
3525 }
3526
Chris Lattner4b009652007-07-25 00:24:17 +00003527 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003528 lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3529 rhptee = rhsType->getAs<PointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003530
Chris Lattner4b009652007-07-25 00:24:17 +00003531 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003532 lhptee = Context.getCanonicalType(lhptee);
3533 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003534
Chris Lattner005ed752008-01-04 18:04:52 +00003535 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003536
3537 // C99 6.5.16.1p1: This following citation is common to constraints
3538 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3539 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003540 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003541 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003542 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003543
Mike Stump9afab102009-02-19 03:04:26 +00003544 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3545 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003546 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003547 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003548 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003549 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003550
Chris Lattner4ca3d772008-01-03 22:56:36 +00003551 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003552 assert(rhptee->isFunctionType());
3553 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003554 }
Mike Stump9afab102009-02-19 03:04:26 +00003555
Chris Lattner4ca3d772008-01-03 22:56:36 +00003556 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003557 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003558 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003559
3560 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003561 assert(lhptee->isFunctionType());
3562 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003563 }
Mike Stump9afab102009-02-19 03:04:26 +00003564 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003565 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003566 lhptee = lhptee.getUnqualifiedType();
3567 rhptee = rhptee.getUnqualifiedType();
3568 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3569 // Check if the pointee types are compatible ignoring the sign.
3570 // We explicitly check for char so that we catch "char" vs
3571 // "unsigned char" on systems where "char" is unsigned.
3572 if (lhptee->isCharType()) {
3573 lhptee = Context.UnsignedCharTy;
3574 } else if (lhptee->isSignedIntegerType()) {
3575 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3576 }
3577 if (rhptee->isCharType()) {
3578 rhptee = Context.UnsignedCharTy;
3579 } else if (rhptee->isSignedIntegerType()) {
3580 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3581 }
3582 if (lhptee == rhptee) {
3583 // Types are compatible ignoring the sign. Qualifier incompatibility
3584 // takes priority over sign incompatibility because the sign
3585 // warning can be disabled.
3586 if (ConvTy != Compatible)
3587 return ConvTy;
3588 return IncompatiblePointerSign;
3589 }
3590 // General pointer incompatibility takes priority over qualifiers.
3591 return IncompatiblePointer;
3592 }
Chris Lattner005ed752008-01-04 18:04:52 +00003593 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003594}
3595
Steve Naroff3454b6c2008-09-04 15:10:53 +00003596/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3597/// block pointer types are compatible or whether a block and normal pointer
3598/// are compatible. It is more restrict than comparing two function pointer
3599// types.
Mike Stump9afab102009-02-19 03:04:26 +00003600Sema::AssignConvertType
3601Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003602 QualType rhsType) {
3603 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003604
Steve Naroff3454b6c2008-09-04 15:10:53 +00003605 // get the "pointed to" type (ignoring qualifiers at the top level)
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003606 lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3607 rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003608
Steve Naroff3454b6c2008-09-04 15:10:53 +00003609 // make sure we operate on the canonical type
3610 lhptee = Context.getCanonicalType(lhptee);
3611 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003612
Steve Naroff3454b6c2008-09-04 15:10:53 +00003613 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003614
Steve Naroff3454b6c2008-09-04 15:10:53 +00003615 // For blocks we enforce that qualifiers are identical.
3616 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3617 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003618
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00003619 if (!Context.typesAreCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003620 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003621 return ConvTy;
3622}
3623
Mike Stump9afab102009-02-19 03:04:26 +00003624/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3625/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003626/// pointers. Here are some objectionable examples that GCC considers warnings:
3627///
3628/// int a, *pint;
3629/// short *pshort;
3630/// struct foo *pfoo;
3631///
3632/// pint = pshort; // warning: assignment from incompatible pointer type
3633/// a = pint; // warning: assignment makes integer from pointer without a cast
3634/// pint = a; // warning: assignment makes pointer from integer without a cast
3635/// pint = pfoo; // warning: assignment from incompatible pointer type
3636///
3637/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003638/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003639///
Chris Lattner005ed752008-01-04 18:04:52 +00003640Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003641Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003642 // Get canonical types. We're not formatting these types, just comparing
3643 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003644 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3645 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003646
3647 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003648 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003649
David Chisnall44663db2009-08-17 16:35:33 +00003650 if ((lhsType->isObjCClassType() &&
3651 (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3652 (rhsType->isObjCClassType() &&
3653 (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3654 return Compatible;
3655 }
3656
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003657 // If the left-hand side is a reference type, then we are in a
3658 // (rare!) case where we've allowed the use of references in C,
3659 // e.g., as a parameter type in a built-in function. In this case,
3660 // just make sure that the type referenced is compatible with the
3661 // right-hand side type. The caller is responsible for adjusting
3662 // lhsType so that the resulting expression does not have reference
3663 // type.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003664 if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003665 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003666 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003667 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003668 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003669 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3670 // to the same ExtVector type.
3671 if (lhsType->isExtVectorType()) {
3672 if (rhsType->isExtVectorType())
3673 return lhsType == rhsType ? Compatible : Incompatible;
3674 if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3675 return Compatible;
3676 }
3677
Nate Begemanc5f0f652008-07-14 18:02:46 +00003678 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003679 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003680 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003681 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003682 if (getLangOptions().LaxVectorConversions &&
3683 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003684 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003685 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003686 }
3687 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003688 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003689
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003690 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003691 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003692
Chris Lattner390564e2008-04-07 06:49:41 +00003693 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003694 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003695 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003696
Chris Lattner390564e2008-04-07 06:49:41 +00003697 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003698 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003699
Steve Naroff8194a542009-07-20 17:56:53 +00003700 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003701 if (isa<ObjCObjectPointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003702 if (lhsType->isVoidPointerType()) // an exception to the rule.
3703 return Compatible;
3704 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003705 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003706 if (rhsType->getAs<BlockPointerType>()) {
3707 if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003708 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003709
3710 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003711 if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003712 return Compatible;
3713 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003714 return Incompatible;
3715 }
3716
3717 if (isa<BlockPointerType>(lhsType)) {
3718 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003719 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003720
Steve Naroffa982c712008-09-29 18:10:17 +00003721 // Treat block pointers as objects.
Steve Naroff329ec222009-07-10 23:34:53 +00003722 if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
Steve Naroffa982c712008-09-29 18:10:17 +00003723 return Compatible;
3724
Steve Naroff3454b6c2008-09-04 15:10:53 +00003725 if (rhsType->isBlockPointerType())
3726 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003727
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003728 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003729 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003730 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003731 }
Chris Lattner1853da22008-01-04 23:18:45 +00003732 return Incompatible;
3733 }
3734
Steve Naroff329ec222009-07-10 23:34:53 +00003735 if (isa<ObjCObjectPointerType>(lhsType)) {
3736 if (rhsType->isIntegerType())
3737 return IntToPointer;
Steve Naroff8194a542009-07-20 17:56:53 +00003738
3739 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003740 if (isa<PointerType>(rhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003741 if (rhsType->isVoidPointerType()) // an exception to the rule.
3742 return Compatible;
3743 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003744 }
3745 if (rhsType->isObjCObjectPointerType()) {
Steve Naroff7bffd372009-07-15 18:40:39 +00003746 if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3747 return Compatible;
Steve Naroff8194a542009-07-20 17:56:53 +00003748 if (Context.typesAreCompatible(lhsType, rhsType))
3749 return Compatible;
Steve Naroff99eb86b2009-07-23 01:01:38 +00003750 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3751 return IncompatibleObjCQualifiedId;
Steve Naroff8194a542009-07-20 17:56:53 +00003752 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003753 }
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003754 if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
Steve Naroff329ec222009-07-10 23:34:53 +00003755 if (RHSPT->getPointeeType()->isVoidType())
3756 return Compatible;
3757 }
3758 // Treat block pointers as objects.
3759 if (rhsType->isBlockPointerType())
3760 return Compatible;
3761 return Incompatible;
3762 }
Chris Lattner390564e2008-04-07 06:49:41 +00003763 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003764 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003765 if (lhsType == Context.BoolTy)
3766 return Compatible;
3767
3768 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003769 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003770
Mike Stump9afab102009-02-19 03:04:26 +00003771 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003772 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003773
3774 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003775 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003776 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003777 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003778 }
Steve Naroff329ec222009-07-10 23:34:53 +00003779 if (isa<ObjCObjectPointerType>(rhsType)) {
3780 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3781 if (lhsType == Context.BoolTy)
3782 return Compatible;
3783
3784 if (lhsType->isIntegerType())
3785 return PointerToInt;
3786
Steve Naroff8194a542009-07-20 17:56:53 +00003787 // In general, C pointers are not compatible with ObjC object pointers.
Steve Naroff329ec222009-07-10 23:34:53 +00003788 if (isa<PointerType>(lhsType)) {
Steve Naroff8194a542009-07-20 17:56:53 +00003789 if (lhsType->isVoidPointerType()) // an exception to the rule.
3790 return Compatible;
3791 return IncompatiblePointer;
Steve Naroff329ec222009-07-10 23:34:53 +00003792 }
3793 if (isa<BlockPointerType>(lhsType) &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003794 rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
Steve Naroff329ec222009-07-10 23:34:53 +00003795 return Compatible;
3796 return Incompatible;
3797 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003798
Chris Lattner1853da22008-01-04 23:18:45 +00003799 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003800 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003801 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003802 }
3803 return Incompatible;
3804}
3805
Douglas Gregor144b06c2009-04-29 22:16:16 +00003806/// \brief Constructs a transparent union from an expression that is
3807/// used to initialize the transparent union.
3808static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3809 QualType UnionType, FieldDecl *Field) {
3810 // Build an initializer list that designates the appropriate member
3811 // of the transparent union.
3812 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3813 &E, 1,
3814 SourceLocation());
3815 Initializer->setType(UnionType);
3816 Initializer->setInitializedFieldInUnion(Field);
3817
3818 // Build a compound literal constructing a value of the transparent
3819 // union type from this initializer list.
3820 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3821 false);
3822}
3823
3824Sema::AssignConvertType
3825Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3826 QualType FromType = rExpr->getType();
3827
3828 // If the ArgType is a Union type, we want to handle a potential
3829 // transparent_union GCC extension.
3830 const RecordType *UT = ArgType->getAsUnionType();
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00003831 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor144b06c2009-04-29 22:16:16 +00003832 return Incompatible;
3833
3834 // The field to initialize within the transparent union.
3835 RecordDecl *UD = UT->getDecl();
3836 FieldDecl *InitField = 0;
3837 // It's compatible if the expression matches any of the fields.
Argiris Kirtzidisab6e38a2009-06-30 02:36:12 +00003838 for (RecordDecl::field_iterator it = UD->field_begin(),
3839 itend = UD->field_end();
Douglas Gregor144b06c2009-04-29 22:16:16 +00003840 it != itend; ++it) {
3841 if (it->getType()->isPointerType()) {
3842 // If the transparent union contains a pointer type, we allow:
3843 // 1) void pointer
3844 // 2) null pointer constant
3845 if (FromType->isPointerType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00003846 if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor144b06c2009-04-29 22:16:16 +00003847 ImpCastExprToType(rExpr, it->getType());
3848 InitField = *it;
3849 break;
3850 }
3851
3852 if (rExpr->isNullPointerConstant(Context)) {
3853 ImpCastExprToType(rExpr, it->getType());
3854 InitField = *it;
3855 break;
3856 }
3857 }
3858
3859 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3860 == Compatible) {
3861 InitField = *it;
3862 break;
3863 }
3864 }
3865
3866 if (!InitField)
3867 return Incompatible;
3868
3869 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3870 return Compatible;
3871}
3872
Chris Lattner005ed752008-01-04 18:04:52 +00003873Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003874Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003875 if (getLangOptions().CPlusPlus) {
3876 if (!lhsType->isRecordType()) {
3877 // C++ 5.17p3: If the left operand is not of class type, the
3878 // expression is implicitly converted (C++ 4) to the
3879 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003880 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3881 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003882 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003883 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003884 }
3885
3886 // FIXME: Currently, we fall through and treat C++ classes like C
3887 // structures.
3888 }
3889
Steve Naroffcdee22d2007-11-27 17:58:44 +00003890 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3891 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003892 if ((lhsType->isPointerType() ||
Steve Naroff329ec222009-07-10 23:34:53 +00003893 lhsType->isObjCObjectPointerType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003894 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003895 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003896 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003897 return Compatible;
3898 }
Mike Stump9afab102009-02-19 03:04:26 +00003899
Chris Lattner5f505bf2007-10-16 02:55:40 +00003900 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003901 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003902 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003903 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003904 //
Mike Stump9afab102009-02-19 03:04:26 +00003905 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003906 if (!lhsType->isReferenceType())
3907 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003908
Chris Lattner005ed752008-01-04 18:04:52 +00003909 Sema::AssignConvertType result =
3910 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003911
Steve Naroff0f32f432007-08-24 22:33:52 +00003912 // C99 6.5.16.1p2: The value of the right operand is converted to the
3913 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003914 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3915 // so that we can use references in built-in functions even in C.
3916 // The getNonReferenceType() call makes sure that the resulting expression
3917 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003918 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003919 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003920 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003921}
3922
Chris Lattner1eafdea2008-11-18 01:30:42 +00003923QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003924 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003925 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003926 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003927 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003928}
3929
Mike Stump9afab102009-02-19 03:04:26 +00003930inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003931 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003932 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003933 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003934 QualType lhsType =
3935 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3936 QualType rhsType =
3937 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003938
Nate Begemanc5f0f652008-07-14 18:02:46 +00003939 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003940 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003941 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003942
Nate Begemanc5f0f652008-07-14 18:02:46 +00003943 // Handle the case of a vector & extvector type of the same size and element
3944 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003945 if (getLangOptions().LaxVectorConversions) {
3946 // FIXME: Should we warn here?
3947 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003948 if (const VectorType *RV = rhsType->getAsVectorType())
3949 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003950 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003951 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003952 }
3953 }
3954 }
Mike Stump9afab102009-02-19 03:04:26 +00003955
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003956 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3957 // swap back (so that we don't reverse the inputs to a subtract, for instance.
3958 bool swapped = false;
3959 if (rhsType->isExtVectorType()) {
3960 swapped = true;
3961 std::swap(rex, lex);
3962 std::swap(rhsType, lhsType);
3963 }
3964
Nate Begemanf1695892009-06-28 19:12:57 +00003965 // Handle the case of an ext vector and scalar.
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003966 if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3967 QualType EltTy = LV->getElementType();
3968 if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3969 if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003970 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003971 if (swapped) std::swap(rex, lex);
3972 return lhsType;
3973 }
3974 }
3975 if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3976 rhsType->isRealFloatingType()) {
3977 if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
Nate Begemanf1695892009-06-28 19:12:57 +00003978 ImpCastExprToType(rex, lhsType);
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003979 if (swapped) std::swap(rex, lex);
3980 return lhsType;
3981 }
Nate Begemanec2d1062007-12-30 02:59:45 +00003982 }
3983 }
Nate Begeman0e0eadd2009-06-28 02:36:38 +00003984
Nate Begemanf1695892009-06-28 19:12:57 +00003985 // Vectors of different size or scalar and non-ext-vector are errors.
Chris Lattner70b93d82008-11-18 22:52:51 +00003986 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003987 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003988 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003989 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003990}
3991
Chris Lattner4b009652007-07-25 00:24:17 +00003992inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003993 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003994{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003995 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003996 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003997
Steve Naroff8f708362007-08-24 19:07:16 +00003998 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003999
Chris Lattner4b009652007-07-25 00:24:17 +00004000 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00004001 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004002 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004003}
4004
4005inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004006 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004007{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00004008 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4009 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4010 return CheckVectorOperands(Loc, lex, rex);
4011 return InvalidOperands(Loc, lex, rex);
4012 }
Chris Lattner4b009652007-07-25 00:24:17 +00004013
Steve Naroff8f708362007-08-24 19:07:16 +00004014 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004015
Chris Lattner4b009652007-07-25 00:24:17 +00004016 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004017 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004018 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004019}
4020
4021inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00004022 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00004023{
Eli Friedman3cd92882009-03-28 01:22:36 +00004024 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4025 QualType compType = CheckVectorOperands(Loc, lex, rex);
4026 if (CompLHSTy) *CompLHSTy = compType;
4027 return compType;
4028 }
Chris Lattner4b009652007-07-25 00:24:17 +00004029
Eli Friedman3cd92882009-03-28 01:22:36 +00004030 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004031
Chris Lattner4b009652007-07-25 00:24:17 +00004032 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00004033 if (lex->getType()->isArithmeticType() &&
4034 rex->getType()->isArithmeticType()) {
4035 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004036 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004037 }
Chris Lattner4b009652007-07-25 00:24:17 +00004038
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004039 // Put any potential pointer into PExp
4040 Expr* PExp = lex, *IExp = rex;
Steve Naroff79ae19a2009-07-14 18:25:06 +00004041 if (IExp->getType()->isAnyPointerType())
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004042 std::swap(PExp, IExp);
4043
Steve Naroff79ae19a2009-07-14 18:25:06 +00004044 if (PExp->getType()->isAnyPointerType()) {
Steve Naroff329ec222009-07-10 23:34:53 +00004045
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004046 if (IExp->getType()->isIntegerType()) {
Steve Naroff18b38122009-07-13 21:20:41 +00004047 QualType PointeeTy = PExp->getType()->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004048
Chris Lattner184f92d2009-04-24 23:50:08 +00004049 // Check for arithmetic on pointers to incomplete types.
4050 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004051 if (getLangOptions().CPlusPlus) {
4052 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00004053 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004054 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004055 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004056
4057 // GNU extension: arithmetic on pointer to void
4058 Diag(Loc, diag::ext_gnu_void_ptr)
4059 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00004060 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00004061 if (getLangOptions().CPlusPlus) {
4062 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4063 << lex->getType() << lex->getSourceRange();
4064 return QualType();
4065 }
4066
4067 // GNU extension: arithmetic on pointer to function
4068 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4069 << lex->getType() << lex->getSourceRange();
Steve Naroff3fc227b2009-07-13 21:32:29 +00004070 } else {
Steve Naroff18b38122009-07-13 21:20:41 +00004071 // Check if we require a complete type.
4072 if (((PExp->getType()->isPointerType() &&
Steve Naroff3fc227b2009-07-13 21:32:29 +00004073 !PExp->getType()->isDependentType()) ||
Steve Naroff18b38122009-07-13 21:20:41 +00004074 PExp->getType()->isObjCObjectPointerType()) &&
4075 RequireCompleteType(Loc, PointeeTy,
4076 diag::err_typecheck_arithmetic_incomplete_type,
4077 PExp->getSourceRange(), SourceRange(),
4078 PExp->getType()))
4079 return QualType();
4080 }
Chris Lattner184f92d2009-04-24 23:50:08 +00004081 // Diagnose bad cases where we step over interface counts.
4082 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4083 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4084 << PointeeTy << PExp->getSourceRange();
4085 return QualType();
4086 }
4087
Eli Friedman3cd92882009-03-28 01:22:36 +00004088 if (CompLHSTy) {
4089 QualType LHSTy = lex->getType();
4090 if (LHSTy->isPromotableIntegerType())
4091 LHSTy = Context.IntTy;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004092 else {
4093 QualType T = isPromotableBitField(lex, Context);
4094 if (!T.isNull())
4095 LHSTy = T;
4096 }
4097
Eli Friedman3cd92882009-03-28 01:22:36 +00004098 *CompLHSTy = LHSTy;
4099 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00004100 return PExp->getType();
4101 }
4102 }
4103
Chris Lattner1eafdea2008-11-18 01:30:42 +00004104 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004105}
4106
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004107// C99 6.5.6
4108QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00004109 SourceLocation Loc, QualType* CompLHSTy) {
4110 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4111 QualType compType = CheckVectorOperands(Loc, lex, rex);
4112 if (CompLHSTy) *CompLHSTy = compType;
4113 return compType;
4114 }
Mike Stump9afab102009-02-19 03:04:26 +00004115
Eli Friedman3cd92882009-03-28 01:22:36 +00004116 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00004117
Chris Lattnerf6da2912007-12-09 21:53:25 +00004118 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00004119
Chris Lattnerf6da2912007-12-09 21:53:25 +00004120 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00004121 if (lex->getType()->isArithmeticType()
4122 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004123 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00004124 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00004125 }
Steve Naroff329ec222009-07-10 23:34:53 +00004126
Chris Lattnerf6da2912007-12-09 21:53:25 +00004127 // Either ptr - int or ptr - ptr.
Steve Naroff79ae19a2009-07-14 18:25:06 +00004128 if (lex->getType()->isAnyPointerType()) {
Steve Naroff7982a642009-07-13 17:19:15 +00004129 QualType lpointee = lex->getType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004130
Douglas Gregor05e28f62009-03-24 19:52:54 +00004131 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00004132
Douglas Gregor05e28f62009-03-24 19:52:54 +00004133 bool ComplainAboutVoid = false;
4134 Expr *ComplainAboutFunc = 0;
4135 if (lpointee->isVoidType()) {
4136 if (getLangOptions().CPlusPlus) {
4137 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4138 << lex->getSourceRange() << rex->getSourceRange();
4139 return QualType();
4140 }
4141
4142 // GNU C extension: arithmetic on pointer to void
4143 ComplainAboutVoid = true;
4144 } else if (lpointee->isFunctionType()) {
4145 if (getLangOptions().CPlusPlus) {
4146 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004147 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004148 return QualType();
4149 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004150
4151 // GNU C extension: arithmetic on pointer to function
4152 ComplainAboutFunc = lex;
4153 } else if (!lpointee->isDependentType() &&
4154 RequireCompleteType(Loc, lpointee,
4155 diag::err_typecheck_sub_ptr_object,
4156 lex->getSourceRange(),
4157 SourceRange(),
4158 lex->getType()))
4159 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004160
Chris Lattner184f92d2009-04-24 23:50:08 +00004161 // Diagnose bad cases where we step over interface counts.
4162 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4163 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4164 << lpointee << lex->getSourceRange();
4165 return QualType();
4166 }
4167
Chris Lattnerf6da2912007-12-09 21:53:25 +00004168 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00004169 if (rex->getType()->isIntegerType()) {
4170 if (ComplainAboutVoid)
4171 Diag(Loc, diag::ext_gnu_void_ptr)
4172 << lex->getSourceRange() << rex->getSourceRange();
4173 if (ComplainAboutFunc)
4174 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4175 << ComplainAboutFunc->getType()
4176 << ComplainAboutFunc->getSourceRange();
4177
Eli Friedman3cd92882009-03-28 01:22:36 +00004178 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004179 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00004180 }
Mike Stump9afab102009-02-19 03:04:26 +00004181
Chris Lattnerf6da2912007-12-09 21:53:25 +00004182 // Handle pointer-pointer subtractions.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004183 if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
Eli Friedman50727042008-02-08 01:19:44 +00004184 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004185
Douglas Gregor05e28f62009-03-24 19:52:54 +00004186 // RHS must be a completely-type object type.
4187 // Handle the GNU void* extension.
4188 if (rpointee->isVoidType()) {
4189 if (getLangOptions().CPlusPlus) {
4190 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4191 << lex->getSourceRange() << rex->getSourceRange();
4192 return QualType();
4193 }
Mike Stump9afab102009-02-19 03:04:26 +00004194
Douglas Gregor05e28f62009-03-24 19:52:54 +00004195 ComplainAboutVoid = true;
4196 } else if (rpointee->isFunctionType()) {
4197 if (getLangOptions().CPlusPlus) {
4198 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004199 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004200 return QualType();
4201 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00004202
4203 // GNU extension: arithmetic on pointer to function
4204 if (!ComplainAboutFunc)
4205 ComplainAboutFunc = rex;
4206 } else if (!rpointee->isDependentType() &&
4207 RequireCompleteType(Loc, rpointee,
4208 diag::err_typecheck_sub_ptr_object,
4209 rex->getSourceRange(),
4210 SourceRange(),
4211 rex->getType()))
4212 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004213
Eli Friedman143ddc92009-05-16 13:54:38 +00004214 if (getLangOptions().CPlusPlus) {
4215 // Pointee types must be the same: C++ [expr.add]
4216 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4217 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4218 << lex->getType() << rex->getType()
4219 << lex->getSourceRange() << rex->getSourceRange();
4220 return QualType();
4221 }
4222 } else {
4223 // Pointee types must be compatible C99 6.5.6p3
4224 if (!Context.typesAreCompatible(
4225 Context.getCanonicalType(lpointee).getUnqualifiedType(),
4226 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4227 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4228 << lex->getType() << rex->getType()
4229 << lex->getSourceRange() << rex->getSourceRange();
4230 return QualType();
4231 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00004232 }
Mike Stump9afab102009-02-19 03:04:26 +00004233
Douglas Gregor05e28f62009-03-24 19:52:54 +00004234 if (ComplainAboutVoid)
4235 Diag(Loc, diag::ext_gnu_void_ptr)
4236 << lex->getSourceRange() << rex->getSourceRange();
4237 if (ComplainAboutFunc)
4238 Diag(Loc, diag::ext_gnu_ptr_func_arith)
4239 << ComplainAboutFunc->getType()
4240 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00004241
4242 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00004243 return Context.getPointerDiffType();
4244 }
4245 }
Mike Stump9afab102009-02-19 03:04:26 +00004246
Chris Lattner1eafdea2008-11-18 01:30:42 +00004247 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004248}
4249
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004250// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00004251QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00004252 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00004253 // C99 6.5.7p2: Each of the operands shall have integer type.
4254 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004255 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00004256
Chris Lattner2c8bff72007-12-12 05:47:28 +00004257 // Shifts don't perform usual arithmetic conversions, they just do integer
4258 // promotions on each operand. C99 6.5.7p3
Eli Friedman3cd92882009-03-28 01:22:36 +00004259 QualType LHSTy;
4260 if (lex->getType()->isPromotableIntegerType())
4261 LHSTy = Context.IntTy;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004262 else {
4263 LHSTy = isPromotableBitField(lex, Context);
4264 if (LHSTy.isNull())
4265 LHSTy = lex->getType();
4266 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00004267 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00004268 ImpCastExprToType(lex, LHSTy);
4269
Chris Lattner2c8bff72007-12-12 05:47:28 +00004270 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004271
Ryan Flynnf109fff2009-08-07 16:20:20 +00004272 // Sanity-check shift operands
4273 llvm::APSInt Right;
4274 // Check right/shifter operand
4275 if (rex->isIntegerConstantExpr(Right, Context)) {
Ryan Flynna5e76932009-08-08 19:18:23 +00004276 if (Right.isNegative())
Ryan Flynnf109fff2009-08-07 16:20:20 +00004277 Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4278 else {
4279 llvm::APInt LeftBits(Right.getBitWidth(),
4280 Context.getTypeSize(lex->getType()));
4281 if (Right.uge(LeftBits))
4282 Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4283 }
4284 }
4285
Chris Lattner2c8bff72007-12-12 05:47:28 +00004286 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00004287 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004288}
4289
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004290// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00004291QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00004292 unsigned OpaqueOpc, bool isRelational) {
4293 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4294
Nate Begemanc5f0f652008-07-14 18:02:46 +00004295 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004296 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00004297
Chris Lattner254f3bc2007-08-26 01:18:55 +00004298 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00004299 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4300 UsualArithmeticConversions(lex, rex);
4301 else {
4302 UsualUnaryConversions(lex);
4303 UsualUnaryConversions(rex);
4304 }
Chris Lattner4b009652007-07-25 00:24:17 +00004305 QualType lType = lex->getType();
4306 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004307
Mike Stumpea3d74e2009-05-07 18:43:07 +00004308 if (!lType->isFloatingType()
4309 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004310 // For non-floating point types, check for self-comparisons of the form
4311 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4312 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00004313 // NOTE: Don't warn about comparisons of enum constants. These can arise
4314 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00004315 Expr *LHSStripped = lex->IgnoreParens();
4316 Expr *RHSStripped = rex->IgnoreParens();
4317 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4318 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00004319 if (DRL->getDecl() == DRR->getDecl() &&
4320 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00004321 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00004322
4323 if (isa<CastExpr>(LHSStripped))
4324 LHSStripped = LHSStripped->IgnoreParenCasts();
4325 if (isa<CastExpr>(RHSStripped))
4326 RHSStripped = RHSStripped->IgnoreParenCasts();
4327
4328 // Warn about comparisons against a string constant (unless the other
4329 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00004330 Expr *literalString = 0;
4331 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00004332 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00004333 !RHSStripped->isNullPointerConstant(Context)) {
4334 literalString = lex;
4335 literalStringStripped = LHSStripped;
Mike Stump90fc78e2009-08-04 21:02:39 +00004336 } else if ((isa<StringLiteral>(RHSStripped) ||
4337 isa<ObjCEncodeExpr>(RHSStripped)) &&
4338 !LHSStripped->isNullPointerConstant(Context)) {
Douglas Gregor1f12c352009-04-06 18:45:53 +00004339 literalString = rex;
4340 literalStringStripped = RHSStripped;
4341 }
4342
4343 if (literalString) {
4344 std::string resultComparison;
4345 switch (Opc) {
4346 case BinaryOperator::LT: resultComparison = ") < 0"; break;
4347 case BinaryOperator::GT: resultComparison = ") > 0"; break;
4348 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4349 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4350 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4351 case BinaryOperator::NE: resultComparison = ") != 0"; break;
4352 default: assert(false && "Invalid comparison operator");
4353 }
4354 Diag(Loc, diag::warn_stringcompare)
4355 << isa<ObjCEncodeExpr>(literalStringStripped)
4356 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00004357 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4358 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4359 "strcmp(")
4360 << CodeModificationHint::CreateInsertion(
4361 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00004362 resultComparison);
4363 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00004364 }
Mike Stump9afab102009-02-19 03:04:26 +00004365
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004366 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00004367 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004368
Chris Lattner254f3bc2007-08-26 01:18:55 +00004369 if (isRelational) {
4370 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004371 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004372 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00004373 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00004374 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00004375 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004376 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00004377 }
Mike Stump9afab102009-02-19 03:04:26 +00004378
Chris Lattner254f3bc2007-08-26 01:18:55 +00004379 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004380 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00004381 }
Mike Stump9afab102009-02-19 03:04:26 +00004382
Chris Lattner22be8422007-08-26 01:10:14 +00004383 bool LHSIsNull = lex->isNullPointerConstant(Context);
4384 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00004385
Chris Lattner254f3bc2007-08-26 01:18:55 +00004386 // All of the following pointer related warnings are GCC extensions, except
4387 // when handling null pointer constants. One day, we can consider making them
4388 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00004389 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004390 QualType LCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004391 Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00004392 QualType RCanPointeeTy =
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004393 Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00004394
Douglas Gregor4da47382009-07-06 20:14:23 +00004395 if (isRelational) {
4396 if (lType->isFunctionPointerType() || rType->isFunctionPointerType()) {
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004397 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4398 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4399 }
Douglas Gregor4da47382009-07-06 20:14:23 +00004400 if (LCanPointeeTy->isVoidType() != RCanPointeeTy->isVoidType()) {
4401 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4402 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4403 }
4404 } else {
4405 if (lType->isFunctionPointerType() != rType->isFunctionPointerType()) {
4406 if (!LHSIsNull && !RHSIsNull)
4407 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4408 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4409 }
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004410 }
Douglas Gregor4da47382009-07-06 20:14:23 +00004411
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004412 // Simple check: if the pointee types are identical, we're done.
4413 if (LCanPointeeTy == RCanPointeeTy)
4414 return ResultTy;
4415
4416 if (getLangOptions().CPlusPlus) {
4417 // C++ [expr.rel]p2:
4418 // [...] Pointer conversions (4.10) and qualification
4419 // conversions (4.4) are performed on pointer operands (or on
4420 // a pointer operand and a null pointer constant) to bring
4421 // them to their composite pointer type. [...]
4422 //
4423 // C++ [expr.eq]p2 uses the same notion for (in)equality
4424 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00004425 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00004426 if (T.isNull()) {
4427 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4428 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4429 return QualType();
4430 }
4431
4432 ImpCastExprToType(lex, T);
4433 ImpCastExprToType(rex, T);
4434 return ResultTy;
4435 }
4436
Steve Naroff3b435622007-11-13 14:57:38 +00004437 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00004438 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
4439 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Steve Naroff329ec222009-07-10 23:34:53 +00004440 RCanPointeeTy.getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004441 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004442 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004443 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00004444 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004445 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004446 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00004447 // C++ allows comparison of pointers with null pointer constants.
4448 if (getLangOptions().CPlusPlus) {
4449 if (lType->isPointerType() && RHSIsNull) {
4450 ImpCastExprToType(rex, lType);
4451 return ResultTy;
4452 }
4453 if (rType->isPointerType() && LHSIsNull) {
4454 ImpCastExprToType(lex, rType);
4455 return ResultTy;
4456 }
4457 // And comparison of nullptr_t with itself.
4458 if (lType->isNullPtrType() && rType->isNullPtrType())
4459 return ResultTy;
4460 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004461 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00004462 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004463 QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4464 QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004465
Steve Naroff3454b6c2008-09-04 15:10:53 +00004466 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmanb6eed6e2009-06-08 05:08:54 +00004467 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004468 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004469 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00004470 }
4471 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004472 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00004473 }
Steve Narofff85d66c2008-09-28 01:11:11 +00004474 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00004475 if (!isRelational
4476 && ((lType->isBlockPointerType() && rType->isPointerType())
4477 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00004478 if (!LHSIsNull && !RHSIsNull) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004479 if (!((rType->isPointerType() && rType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004480 ->getPointeeType()->isVoidType())
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004481 || (lType->isPointerType() && lType->getAs<PointerType>()
Mike Stumpe97a8542009-05-07 03:14:14 +00004482 ->getPointeeType()->isVoidType())))
4483 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4484 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00004485 }
4486 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004487 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004488 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004489
Steve Naroff329ec222009-07-10 23:34:53 +00004490 if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004491 if (lType->isPointerType() || rType->isPointerType()) {
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00004492 const PointerType *LPT = lType->getAs<PointerType>();
4493 const PointerType *RPT = rType->getAs<PointerType>();
Mike Stump9afab102009-02-19 03:04:26 +00004494 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004495 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004496 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004497 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004498
Steve Naroff030fcda2008-11-17 19:49:16 +00004499 if (!LPtrToVoid && !RPtrToVoid &&
4500 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004501 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004502 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004503 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004504 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004505 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004506 }
Steve Naroff329ec222009-07-10 23:34:53 +00004507 if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
4508 if (!Context.areComparableObjCPointerTypes(lType, rType)) {
4509 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4510 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4511 }
Steve Naroff936c4362008-06-03 14:04:54 +00004512 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004513 return ResultTy;
Steve Naroff936c4362008-06-03 14:04:54 +00004514 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004515 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004516 if (lType->isAnyPointerType() && rType->isIntegerType()) {
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004517 if (isRelational)
4518 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_pointer_integer)
4519 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4520 else if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00004521 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004522 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00004523 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004524 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004525 }
Steve Naroff79ae19a2009-07-14 18:25:06 +00004526 if (lType->isIntegerType() && rType->isAnyPointerType()) {
Chris Lattnerf350c6e2009-06-30 06:24:05 +00004527 if (isRelational)
4528 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_pointer_integer)
4529 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4530 else if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00004531 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004532 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00004533 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004534 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004535 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004536 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004537 if (!isRelational && RHSIsNull
4538 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004539 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004540 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004541 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004542 if (!isRelational && LHSIsNull
4543 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004544 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004545 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004546 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004547 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004548}
4549
Nate Begemanc5f0f652008-07-14 18:02:46 +00004550/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004551/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004552/// like a scalar comparison, a vector comparison produces a vector of integer
4553/// types.
4554QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004555 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004556 bool isRelational) {
4557 // Check to make sure we're operating on vectors of the same type and width,
4558 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004559 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004560 if (vType.isNull())
4561 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004562
Nate Begemanc5f0f652008-07-14 18:02:46 +00004563 QualType lType = lex->getType();
4564 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004565
Nate Begemanc5f0f652008-07-14 18:02:46 +00004566 // For non-floating point types, check for self-comparisons of the form
4567 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4568 // often indicate logic errors in the program.
4569 if (!lType->isFloatingType()) {
4570 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4571 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4572 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004573 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004574 }
Mike Stump9afab102009-02-19 03:04:26 +00004575
Nate Begemanc5f0f652008-07-14 18:02:46 +00004576 // Check for comparisons of floating point operands using != and ==.
4577 if (!isRelational && lType->isFloatingType()) {
4578 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004579 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004580 }
Mike Stump9afab102009-02-19 03:04:26 +00004581
Nate Begemanc5f0f652008-07-14 18:02:46 +00004582 // Return the type for the comparison, which is the same as vector type for
4583 // integer vectors, or an integer type of identical size and number of
4584 // elements for floating point vectors.
4585 if (lType->isIntegerType())
4586 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004587
Nate Begemanc5f0f652008-07-14 18:02:46 +00004588 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004589 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004590 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004591 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004592 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004593 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4594
Mike Stump9afab102009-02-19 03:04:26 +00004595 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004596 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004597 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4598}
4599
Chris Lattner4b009652007-07-25 00:24:17 +00004600inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004601 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004602{
4603 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004604 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004605
Steve Naroff8f708362007-08-24 19:07:16 +00004606 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004607
Chris Lattner4b009652007-07-25 00:24:17 +00004608 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004609 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004610 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004611}
4612
4613inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004614 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004615{
4616 UsualUnaryConversions(lex);
4617 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004618
Eli Friedmanbea3f842008-05-13 20:16:47 +00004619 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004620 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004621 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004622}
4623
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004624/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4625/// is a read-only property; return true if so. A readonly property expression
4626/// depends on various declarations and thus must be treated specially.
4627///
Mike Stump9afab102009-02-19 03:04:26 +00004628static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004629{
4630 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4631 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4632 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4633 QualType BaseType = PropExpr->getBase()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00004634 if (const ObjCObjectPointerType *OPT =
4635 BaseType->getAsObjCInterfacePointerType())
4636 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4637 if (S.isPropertyReadonly(PDecl, IFace))
4638 return true;
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004639 }
4640 }
4641 return false;
4642}
4643
Chris Lattner4c2642c2008-11-18 01:22:49 +00004644/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4645/// emit an error and return true. If so, return false.
4646static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004647 SourceLocation OrigLoc = Loc;
4648 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4649 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004650 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4651 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004652 if (IsLV == Expr::MLV_Valid)
4653 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004654
Chris Lattner4c2642c2008-11-18 01:22:49 +00004655 unsigned Diag = 0;
4656 bool NeedType = false;
4657 switch (IsLV) { // C99 6.5.16p2
4658 default: assert(0 && "Unknown result from isModifiableLvalue!");
4659 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004660 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004661 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4662 NeedType = true;
4663 break;
Mike Stump9afab102009-02-19 03:04:26 +00004664 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004665 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4666 NeedType = true;
4667 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004668 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004669 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4670 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004671 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004672 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4673 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004674 case Expr::MLV_IncompleteType:
4675 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004676 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004677 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
4678 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004679 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004680 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4681 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004682 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004683 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4684 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004685 case Expr::MLV_ReadonlyProperty:
4686 Diag = diag::error_readonly_property_assignment;
4687 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004688 case Expr::MLV_NoSetterProperty:
4689 Diag = diag::error_nosetter_property_assignment;
4690 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004691 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004692
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004693 SourceRange Assign;
4694 if (Loc != OrigLoc)
4695 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004696 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004697 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004698 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004699 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004700 return true;
4701}
4702
4703
4704
4705// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004706QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4707 SourceLocation Loc,
4708 QualType CompoundType) {
4709 // Verify that LHS is a modifiable lvalue, and emit error if not.
4710 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004711 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004712
4713 QualType LHSType = LHS->getType();
4714 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004715
Chris Lattner005ed752008-01-04 18:04:52 +00004716 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004717 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004718 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004719 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004720 // Special case of NSObject attributes on c-style pointer types.
4721 if (ConvTy == IncompatiblePointer &&
4722 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004723 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004724 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroffad75bd22009-07-16 15:41:00 +00004725 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004726 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004727
Chris Lattner34c85082008-08-21 18:04:13 +00004728 // If the RHS is a unary plus or minus, check to see if they = and + are
4729 // right next to each other. If so, the user may have typo'd "x =+ 4"
4730 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004731 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004732 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4733 RHSCheck = ICE->getSubExpr();
4734 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4735 if ((UO->getOpcode() == UnaryOperator::Plus ||
4736 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004737 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004738 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004739 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4740 // And there is a space or other character before the subexpr of the
4741 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004742 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4743 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004744 Diag(Loc, diag::warn_not_compound_assign)
4745 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4746 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004747 }
Chris Lattner34c85082008-08-21 18:04:13 +00004748 }
4749 } else {
4750 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004751 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004752 }
Chris Lattner005ed752008-01-04 18:04:52 +00004753
Chris Lattner1eafdea2008-11-18 01:30:42 +00004754 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4755 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004756 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004757
Chris Lattner4b009652007-07-25 00:24:17 +00004758 // C99 6.5.16p3: The type of an assignment expression is the type of the
4759 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004760 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004761 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4762 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004763 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004764 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004765 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004766}
4767
Chris Lattner1eafdea2008-11-18 01:30:42 +00004768// C99 6.5.17
4769QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004770 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004771 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004772
4773 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4774 // incomplete in C++).
4775
Chris Lattner1eafdea2008-11-18 01:30:42 +00004776 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004777}
4778
4779/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4780/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004781QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4782 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004783 if (Op->isTypeDependent())
4784 return Context.DependentTy;
4785
Chris Lattnere65182c2008-11-21 07:05:48 +00004786 QualType ResType = Op->getType();
4787 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004788
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004789 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4790 // Decrement of bool is not allowed.
4791 if (!isInc) {
4792 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4793 return QualType();
4794 }
4795 // Increment of bool sets it to true, but is deprecated.
4796 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4797 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004798 // OK!
Steve Naroff79ae19a2009-07-14 18:25:06 +00004799 } else if (ResType->isAnyPointerType()) {
4800 QualType PointeeTy = ResType->getPointeeType();
Steve Naroff329ec222009-07-10 23:34:53 +00004801
Chris Lattnere65182c2008-11-21 07:05:48 +00004802 // C99 6.5.2.4p2, 6.5.6p2
Steve Naroff329ec222009-07-10 23:34:53 +00004803 if (PointeeTy->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004804 if (getLangOptions().CPlusPlus) {
4805 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4806 << Op->getSourceRange();
4807 return QualType();
4808 }
4809
4810 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004811 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004812 } else if (PointeeTy->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004813 if (getLangOptions().CPlusPlus) {
4814 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4815 << Op->getType() << Op->getSourceRange();
4816 return QualType();
4817 }
4818
4819 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004820 << ResType << Op->getSourceRange();
Steve Naroff329ec222009-07-10 23:34:53 +00004821 } else if (RequireCompleteType(OpLoc, PointeeTy,
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004822 diag::err_typecheck_arithmetic_incomplete_type,
4823 Op->getSourceRange(), SourceRange(),
4824 ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004825 return QualType();
Fariborz Jahanian4738ac52009-07-16 17:59:14 +00004826 // Diagnose bad cases where we step over interface counts.
4827 else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4828 Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4829 << PointeeTy << Op->getSourceRange();
4830 return QualType();
4831 }
Chris Lattnere65182c2008-11-21 07:05:48 +00004832 } else if (ResType->isComplexType()) {
4833 // C99 does not support ++/-- on complex types, we allow as an extension.
4834 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004835 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004836 } else {
4837 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004838 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004839 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004840 }
Mike Stump9afab102009-02-19 03:04:26 +00004841 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004842 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004843 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004844 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004845 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004846}
4847
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004848/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004849/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004850/// where the declaration is needed for type checking. We only need to
4851/// handle cases when the expression references a function designator
4852/// or is an lvalue. Here are some examples:
4853/// - &(x) => x
4854/// - &*****f => f for f a function designator.
4855/// - &s.xx => s
4856/// - &s.zz[1].yy -> s, if zz is an array
4857/// - *(x + 1) -> x, if x is an array
4858/// - &"123"[2] -> 0
4859/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004860static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004861 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004862 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004863 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004864 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004865 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004866 // If this is an arrow operator, the address is an offset from
4867 // the base's value, so the object the base refers to is
4868 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004869 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004870 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004871 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004872 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004873 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004874 // FIXME: This code shouldn't be necessary! We should catch the implicit
4875 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004876 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4877 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4878 if (ICE->getSubExpr()->getType()->isArrayType())
4879 return getPrimaryDecl(ICE->getSubExpr());
4880 }
4881 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004882 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004883 case Stmt::UnaryOperatorClass: {
4884 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004885
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004886 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004887 case UnaryOperator::Real:
4888 case UnaryOperator::Imag:
4889 case UnaryOperator::Extension:
4890 return getPrimaryDecl(UO->getSubExpr());
4891 default:
4892 return 0;
4893 }
4894 }
Chris Lattner4b009652007-07-25 00:24:17 +00004895 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004896 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004897 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004898 // If the result of an implicit cast is an l-value, we care about
4899 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004900 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004901 default:
4902 return 0;
4903 }
4904}
4905
4906/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004907/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004908/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004909/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004910/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004911/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004912/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004913QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004914 // Make sure to ignore parentheses in subsequent checks
4915 op = op->IgnoreParens();
4916
Douglas Gregore6be68a2008-12-17 22:52:20 +00004917 if (op->isTypeDependent())
4918 return Context.DependentTy;
4919
Steve Naroff9c6c3592008-01-13 17:10:08 +00004920 if (getLangOptions().C99) {
4921 // Implement C99-only parts of addressof rules.
4922 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4923 if (uOp->getOpcode() == UnaryOperator::Deref)
4924 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4925 // (assuming the deref expression is valid).
4926 return uOp->getSubExpr()->getType();
4927 }
4928 // Technically, there should be a check for array subscript
4929 // expressions here, but the result of one is always an lvalue anyway.
4930 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004931 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004932 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004933
Eli Friedman14ab4c42009-05-16 23:27:50 +00004934 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4935 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004936 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00004937 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004938 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004939 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4940 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004941 return QualType();
4942 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004943 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004944 // The operand cannot be a bit-field
4945 Diag(OpLoc, diag::err_typecheck_address_of)
4946 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004947 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004948 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4949 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004950 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004951 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004952 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004953 return QualType();
Fariborz Jahanianb35984a2009-07-07 18:50:52 +00004954 } else if (isa<ObjCPropertyRefExpr>(op)) {
4955 // cannot take address of a property expression.
4956 Diag(OpLoc, diag::err_typecheck_address_of)
4957 << "property expression" << op->getSourceRange();
4958 return QualType();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004959 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004960 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004961 // with the register storage-class specifier.
4962 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4963 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004964 Diag(OpLoc, diag::err_typecheck_address_of)
4965 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004966 return QualType();
4967 }
Douglas Gregor62f78762009-07-08 20:55:45 +00004968 } else if (isa<OverloadedFunctionDecl>(dcl) ||
4969 isa<FunctionTemplateDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004970 return Context.OverloadTy;
Anders Carlsson64371472009-07-08 21:45:58 +00004971 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
Douglas Gregor5b82d612008-12-10 21:26:49 +00004972 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004973 // Could be a pointer to member, though, if there is an explicit
4974 // scope qualifier for the class.
4975 if (isa<QualifiedDeclRefExpr>(op)) {
4976 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson64371472009-07-08 21:45:58 +00004977 if (Ctx && Ctx->isRecord()) {
4978 if (FD->getType()->isReferenceType()) {
4979 Diag(OpLoc,
4980 diag::err_cannot_form_pointer_to_member_of_reference_type)
4981 << FD->getDeclName() << FD->getType();
4982 return QualType();
4983 }
4984
Sebastian Redl0c9da212009-02-03 20:19:35 +00004985 return Context.getMemberPointerType(op->getType(),
4986 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson64371472009-07-08 21:45:58 +00004987 }
Sebastian Redl0c9da212009-02-03 20:19:35 +00004988 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004989 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00004990 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004991 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004992 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4993 return Context.getMemberPointerType(op->getType(),
4994 Context.getTypeDeclType(MD->getParent()).getTypePtr());
4995 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00004996 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004997 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004998
Eli Friedman14ab4c42009-05-16 23:27:50 +00004999 if (lval == Expr::LV_IncompleteVoidType) {
5000 // Taking the address of a void variable is technically illegal, but we
5001 // allow it in cases which are otherwise valid.
5002 // Example: "extern void x; void* y = &x;".
5003 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5004 }
5005
Chris Lattner4b009652007-07-25 00:24:17 +00005006 // If the operand has type "type", the result has type "pointer to type".
5007 return Context.getPointerType(op->getType());
5008}
5009
Chris Lattnerda5c0872008-11-23 09:13:29 +00005010QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005011 if (Op->isTypeDependent())
5012 return Context.DependentTy;
5013
Chris Lattnerda5c0872008-11-23 09:13:29 +00005014 UsualUnaryConversions(Op);
5015 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00005016
Chris Lattnerda5c0872008-11-23 09:13:29 +00005017 // Note that per both C89 and C99, this is always legal, even if ptype is an
5018 // incomplete type or void. It would be possible to warn about dereferencing
5019 // a void pointer, but it's completely well-defined, and such a warning is
5020 // unlikely to catch any mistakes.
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005021 if (const PointerType *PT = Ty->getAs<PointerType>())
Steve Naroff9c6c3592008-01-13 17:10:08 +00005022 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00005023
Steve Naroff329ec222009-07-10 23:34:53 +00005024 if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
5025 return OPT->getPointeeType();
5026
Chris Lattner77d52da2008-11-20 06:06:08 +00005027 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00005028 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00005029 return QualType();
5030}
5031
5032static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5033 tok::TokenKind Kind) {
5034 BinaryOperator::Opcode Opc;
5035 switch (Kind) {
5036 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00005037 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
5038 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005039 case tok::star: Opc = BinaryOperator::Mul; break;
5040 case tok::slash: Opc = BinaryOperator::Div; break;
5041 case tok::percent: Opc = BinaryOperator::Rem; break;
5042 case tok::plus: Opc = BinaryOperator::Add; break;
5043 case tok::minus: Opc = BinaryOperator::Sub; break;
5044 case tok::lessless: Opc = BinaryOperator::Shl; break;
5045 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
5046 case tok::lessequal: Opc = BinaryOperator::LE; break;
5047 case tok::less: Opc = BinaryOperator::LT; break;
5048 case tok::greaterequal: Opc = BinaryOperator::GE; break;
5049 case tok::greater: Opc = BinaryOperator::GT; break;
5050 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
5051 case tok::equalequal: Opc = BinaryOperator::EQ; break;
5052 case tok::amp: Opc = BinaryOperator::And; break;
5053 case tok::caret: Opc = BinaryOperator::Xor; break;
5054 case tok::pipe: Opc = BinaryOperator::Or; break;
5055 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
5056 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
5057 case tok::equal: Opc = BinaryOperator::Assign; break;
5058 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
5059 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
5060 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
5061 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
5062 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
5063 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
5064 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
5065 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
5066 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
5067 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
5068 case tok::comma: Opc = BinaryOperator::Comma; break;
5069 }
5070 return Opc;
5071}
5072
5073static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5074 tok::TokenKind Kind) {
5075 UnaryOperator::Opcode Opc;
5076 switch (Kind) {
5077 default: assert(0 && "Unknown unary op!");
5078 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
5079 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
5080 case tok::amp: Opc = UnaryOperator::AddrOf; break;
5081 case tok::star: Opc = UnaryOperator::Deref; break;
5082 case tok::plus: Opc = UnaryOperator::Plus; break;
5083 case tok::minus: Opc = UnaryOperator::Minus; break;
5084 case tok::tilde: Opc = UnaryOperator::Not; break;
5085 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00005086 case tok::kw___real: Opc = UnaryOperator::Real; break;
5087 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
5088 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5089 }
5090 return Opc;
5091}
5092
Douglas Gregord7f915e2008-11-06 23:29:22 +00005093/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5094/// operator @p Opc at location @c TokLoc. This routine only supports
5095/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005096Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5097 unsigned Op,
5098 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00005099 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00005100 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00005101 // The following two variables are used for compound assignment operators
5102 QualType CompLHSTy; // Type of LHS after promotions for computation
5103 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00005104
5105 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00005106 case BinaryOperator::Assign:
5107 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5108 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005109 case BinaryOperator::PtrMemD:
5110 case BinaryOperator::PtrMemI:
5111 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5112 Opc == BinaryOperator::PtrMemI);
5113 break;
5114 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005115 case BinaryOperator::Div:
5116 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5117 break;
5118 case BinaryOperator::Rem:
5119 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5120 break;
5121 case BinaryOperator::Add:
5122 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5123 break;
5124 case BinaryOperator::Sub:
5125 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5126 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00005127 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00005128 case BinaryOperator::Shr:
5129 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5130 break;
5131 case BinaryOperator::LE:
5132 case BinaryOperator::LT:
5133 case BinaryOperator::GE:
5134 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005135 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005136 break;
5137 case BinaryOperator::EQ:
5138 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00005139 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005140 break;
5141 case BinaryOperator::And:
5142 case BinaryOperator::Xor:
5143 case BinaryOperator::Or:
5144 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5145 break;
5146 case BinaryOperator::LAnd:
5147 case BinaryOperator::LOr:
5148 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5149 break;
5150 case BinaryOperator::MulAssign:
5151 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005152 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5153 CompLHSTy = CompResultTy;
5154 if (!CompResultTy.isNull())
5155 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005156 break;
5157 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005158 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5159 CompLHSTy = CompResultTy;
5160 if (!CompResultTy.isNull())
5161 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005162 break;
5163 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005164 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5165 if (!CompResultTy.isNull())
5166 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005167 break;
5168 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005169 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5170 if (!CompResultTy.isNull())
5171 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005172 break;
5173 case BinaryOperator::ShlAssign:
5174 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005175 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5176 CompLHSTy = CompResultTy;
5177 if (!CompResultTy.isNull())
5178 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005179 break;
5180 case BinaryOperator::AndAssign:
5181 case BinaryOperator::XorAssign:
5182 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00005183 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5184 CompLHSTy = CompResultTy;
5185 if (!CompResultTy.isNull())
5186 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00005187 break;
5188 case BinaryOperator::Comma:
5189 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5190 break;
5191 }
5192 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005193 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00005194 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00005195 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5196 else
5197 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00005198 CompLHSTy, CompResultTy,
5199 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00005200}
5201
Chris Lattner4b009652007-07-25 00:24:17 +00005202// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005203Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5204 tok::TokenKind Kind,
5205 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00005206 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005207 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00005208
Steve Naroff87d58b42007-09-16 03:34:24 +00005209 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5210 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00005211
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005212 if (getLangOptions().CPlusPlus &&
5213 (lhs->getType()->isOverloadableType() ||
5214 rhs->getType()->isOverloadableType())) {
5215 // Find all of the overloaded operators visible from this
5216 // point. We perform both an operator-name lookup from the local
5217 // scope and an argument-dependent lookup based on the types of
5218 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00005219 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005220 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5221 if (OverOp != OO_None) {
5222 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5223 Functions);
5224 Expr *Args[2] = { lhs, rhs };
5225 DeclarationName OpName
5226 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5227 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00005228 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005229
Douglas Gregor00fe3f62009-03-13 18:40:31 +00005230 // Build the (potentially-overloaded, potentially-dependent)
5231 // binary operation.
5232 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00005233 }
5234
Douglas Gregord7f915e2008-11-06 23:29:22 +00005235 // Build a built-in binary operation.
5236 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00005237}
5238
Douglas Gregorc78182d2009-03-13 23:49:33 +00005239Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5240 unsigned OpcIn,
5241 ExprArg InputArg) {
5242 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005243
Mike Stumpe127ae32009-05-16 07:39:55 +00005244 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00005245 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00005246 QualType resultType;
5247 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00005248 case UnaryOperator::OffsetOf:
5249 assert(false && "Invalid unary operator");
5250 break;
5251
Chris Lattner4b009652007-07-25 00:24:17 +00005252 case UnaryOperator::PreInc:
5253 case UnaryOperator::PreDec:
Eli Friedman79341142009-07-22 22:25:00 +00005254 case UnaryOperator::PostInc:
5255 case UnaryOperator::PostDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00005256 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
Eli Friedman79341142009-07-22 22:25:00 +00005257 Opc == UnaryOperator::PreInc ||
5258 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00005259 break;
Mike Stump9afab102009-02-19 03:04:26 +00005260 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00005261 resultType = CheckAddressOfOperand(Input, OpLoc);
5262 break;
Mike Stump9afab102009-02-19 03:04:26 +00005263 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00005264 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00005265 resultType = CheckIndirectionOperand(Input, OpLoc);
5266 break;
5267 case UnaryOperator::Plus:
5268 case UnaryOperator::Minus:
5269 UsualUnaryConversions(Input);
5270 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005271 if (resultType->isDependentType())
5272 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00005273 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5274 break;
5275 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5276 resultType->isEnumeralType())
5277 break;
5278 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5279 Opc == UnaryOperator::Plus &&
5280 resultType->isPointerType())
5281 break;
5282
Sebastian Redl8b769972009-01-19 00:08:26 +00005283 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5284 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005285 case UnaryOperator::Not: // bitwise complement
5286 UsualUnaryConversions(Input);
5287 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005288 if (resultType->isDependentType())
5289 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00005290 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5291 if (resultType->isComplexType() || resultType->isComplexIntegerType())
5292 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00005293 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00005294 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00005295 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00005296 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5297 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005298 break;
5299 case UnaryOperator::LNot: // logical negation
5300 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5301 DefaultFunctionArrayConversion(Input);
5302 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005303 if (resultType->isDependentType())
5304 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005305 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00005306 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5307 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00005308 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00005309 // In C++, it's bool. C++ 5.3.1p8
5310 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00005311 break;
Chris Lattner03931a72007-08-24 21:16:53 +00005312 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00005313 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00005314 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00005315 break;
Chris Lattner4b009652007-07-25 00:24:17 +00005316 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00005317 resultType = Input->getType();
5318 break;
5319 }
5320 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00005321 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00005322
5323 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00005324 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005325}
5326
Douglas Gregorc78182d2009-03-13 23:49:33 +00005327// Unary Operators. 'Tok' is the token for the operator.
5328Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5329 tok::TokenKind Op, ExprArg input) {
5330 Expr *Input = (Expr*)input.get();
5331 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5332
5333 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5334 // Find all of the overloaded operators visible from this
5335 // point. We perform both an operator-name lookup from the local
5336 // scope and an argument-dependent lookup based on the types of
5337 // the arguments.
5338 FunctionSet Functions;
5339 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5340 if (OverOp != OO_None) {
5341 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5342 Functions);
5343 DeclarationName OpName
5344 = Context.DeclarationNames.getCXXOperatorName(OverOp);
5345 ArgumentDependentLookup(OpName, &Input, 1, Functions);
5346 }
5347
5348 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5349 }
5350
5351 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5352}
5353
Steve Naroff5cbb02f2007-09-16 14:56:35 +00005354/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005355Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5356 SourceLocation LabLoc,
5357 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00005358 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00005359 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00005360
Daniel Dunbar879788d2008-08-04 16:51:22 +00005361 // If we haven't seen this label yet, create a forward reference. It
5362 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00005363 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00005364 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005365
Chris Lattner4b009652007-07-25 00:24:17 +00005366 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005367 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5368 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00005369}
5370
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005371Sema::OwningExprResult
5372Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5373 SourceLocation RPLoc) { // "({..})"
5374 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00005375 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5376 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5377
Eli Friedmanbc941e12009-01-24 23:09:00 +00005378 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00005379 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005380 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00005381
Chris Lattner4b009652007-07-25 00:24:17 +00005382 // FIXME: there are a variety of strange constraints to enforce here, for
5383 // example, it is not possible to goto into a stmt expression apparently.
5384 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00005385
Chris Lattner4b009652007-07-25 00:24:17 +00005386 // If there are sub stmts in the compound stmt, take the type of the last one
5387 // as the type of the stmtexpr.
5388 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00005389
Chris Lattner200964f2008-07-26 19:51:01 +00005390 if (!Compound->body_empty()) {
5391 Stmt *LastStmt = Compound->body_back();
5392 // If LastStmt is a label, skip down through into the body.
5393 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5394 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00005395
Chris Lattner200964f2008-07-26 19:51:01 +00005396 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00005397 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00005398 }
Mike Stump9afab102009-02-19 03:04:26 +00005399
Eli Friedman2b128322009-03-23 00:24:07 +00005400 // FIXME: Check that expression type is complete/non-abstract; statement
5401 // expressions are not lvalues.
5402
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005403 substmt.release();
5404 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00005405}
Steve Naroff63bad2d2007-08-01 22:05:33 +00005406
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005407Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5408 SourceLocation BuiltinLoc,
5409 SourceLocation TypeLoc,
5410 TypeTy *argty,
5411 OffsetOfComponent *CompPtr,
5412 unsigned NumComponents,
5413 SourceLocation RPLoc) {
5414 // FIXME: This function leaks all expressions in the offset components on
5415 // error.
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005416 // FIXME: Preserve type source info.
5417 QualType ArgTy = GetTypeFromParser(argty);
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005418 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00005419
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005420 bool Dependent = ArgTy->isDependentType();
5421
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005422 // We must have at least one component that refers to the type, and the first
5423 // one is known to be a field designator. Verify that the ArgTy represents
5424 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005425 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005426 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00005427
Eli Friedman2b128322009-03-23 00:24:07 +00005428 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5429 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00005430
Eli Friedman342d9432009-02-27 06:44:11 +00005431 // Otherwise, create a null pointer as the base, and iteratively process
5432 // the offsetof designators.
5433 QualType ArgTyPtr = Context.getPointerType(ArgTy);
5434 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005435 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00005436 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00005437
Chris Lattnerb37522e2007-08-31 21:49:13 +00005438 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5439 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00005440 // FIXME: This diagnostic isn't actually visible because the location is in
5441 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00005442 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00005443 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5444 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00005445
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005446 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00005447 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00005448
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005449 // FIXME: Dependent case loses a lot of information here. And probably
5450 // leaks like a sieve.
5451 for (unsigned i = 0; i != NumComponents; ++i) {
5452 const OffsetOfComponent &OC = CompPtr[i];
5453 if (OC.isBrackets) {
5454 // Offset of an array sub-field. TODO: Should we allow vector elements?
5455 const ArrayType *AT = Context.getAsArrayType(Res->getType());
5456 if (!AT) {
5457 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005458 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5459 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005460 }
5461
5462 // FIXME: C++: Verify that operator[] isn't overloaded.
5463
Eli Friedman342d9432009-02-27 06:44:11 +00005464 // Promote the array so it looks more like a normal array subscript
5465 // expression.
5466 DefaultFunctionArrayConversion(Res);
5467
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005468 // C99 6.5.2.1p1
5469 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005470 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005471 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005472 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00005473 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005474 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005475
5476 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5477 OC.LocEnd);
5478 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005479 }
Mike Stump9afab102009-02-19 03:04:26 +00005480
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00005481 const RecordType *RC = Res->getType()->getAs<RecordType>();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005482 if (!RC) {
5483 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005484 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5485 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005486 }
Chris Lattner2af6a802007-08-30 17:59:59 +00005487
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005488 // Get the decl corresponding to this.
5489 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00005490 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00005491 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00005492 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5493 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5494 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00005495 DidWarnAboutNonPOD = true;
5496 }
Anders Carlsson356946e2009-05-01 23:20:30 +00005497 }
5498
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005499 FieldDecl *MemberDecl
5500 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5501 LookupMemberName)
5502 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005503 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005504 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005505 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
5506 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005507
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005508 // FIXME: C++: Verify that MemberDecl isn't a static field.
5509 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005510 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005511 Res = BuildAnonymousStructUnionMemberReference(
5512 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005513 } else {
5514 // MemberDecl->getType() doesn't get the right qualifiers, but it
5515 // doesn't matter here.
5516 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5517 MemberDecl->getType().getNonReferenceType());
5518 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005519 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005520 }
Mike Stump9afab102009-02-19 03:04:26 +00005521
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005522 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5523 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005524}
5525
5526
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005527Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5528 TypeTy *arg1,TypeTy *arg2,
5529 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005530 // FIXME: Preserve type source info.
5531 QualType argT1 = GetTypeFromParser(arg1);
5532 QualType argT2 = GetTypeFromParser(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005533
Steve Naroff63bad2d2007-08-01 22:05:33 +00005534 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005535
Douglas Gregore6211502009-05-19 22:28:02 +00005536 if (getLangOptions().CPlusPlus) {
5537 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5538 << SourceRange(BuiltinLoc, RPLoc);
5539 return ExprError();
5540 }
5541
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005542 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5543 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005544}
5545
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005546Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5547 ExprArg cond,
5548 ExprArg expr1, ExprArg expr2,
5549 SourceLocation RPLoc) {
5550 Expr *CondExpr = static_cast<Expr*>(cond.get());
5551 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5552 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005553
Steve Naroff93c53012007-08-03 21:21:27 +00005554 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5555
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005556 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005557 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005558 resType = Context.DependentTy;
5559 } else {
5560 // The conditional expression is required to be a constant expression.
5561 llvm::APSInt condEval(32);
5562 SourceLocation ExpLoc;
5563 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005564 return ExprError(Diag(ExpLoc,
5565 diag::err_typecheck_choose_expr_requires_constant)
5566 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005567
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005568 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5569 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5570 }
5571
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005572 cond.release(); expr1.release(); expr2.release();
5573 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5574 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005575}
5576
Steve Naroff52a81c02008-09-03 18:15:37 +00005577//===----------------------------------------------------------------------===//
5578// Clang Extensions.
5579//===----------------------------------------------------------------------===//
5580
5581/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005582void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005583 // Analyze block parameters.
5584 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005585
Steve Naroff52a81c02008-09-03 18:15:37 +00005586 // Add BSI to CurBlock.
5587 BSI->PrevBlockInfo = CurBlock;
5588 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005589
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005590 BSI->ReturnType = QualType();
Steve Naroff52a81c02008-09-03 18:15:37 +00005591 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005592 BSI->hasBlockDeclRefExprs = false;
Daniel Dunbarc7ef2b92009-07-29 01:59:17 +00005593 BSI->hasPrototype = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005594 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5595 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005596
Steve Naroff52059382008-10-10 01:28:17 +00005597 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005598 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005599}
5600
Mike Stumpc1fddff2009-02-04 22:31:32 +00005601void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005602 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005603
5604 if (ParamInfo.getNumTypeObjects() == 0
5605 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005606 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005607 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5608
Mike Stump458287d2009-04-28 01:10:27 +00005609 if (T->isArrayType()) {
5610 Diag(ParamInfo.getSourceRange().getBegin(),
5611 diag::err_block_returns_array);
5612 return;
5613 }
5614
Mike Stumpc1fddff2009-02-04 22:31:32 +00005615 // The parameter list is optional, if there was none, assume ().
5616 if (!T->isFunctionType())
5617 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5618
5619 CurBlock->hasPrototype = true;
5620 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005621 // Check for a valid sentinel attribute on this block.
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005622 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005623 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005624 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005625 // FIXME: remove the attribute.
5626 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005627 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5628
5629 // Do not allow returning a objc interface by-value.
5630 if (RetTy->isObjCInterfaceType()) {
5631 Diag(ParamInfo.getSourceRange().getBegin(),
5632 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5633 return;
5634 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005635 return;
5636 }
5637
Steve Naroff52a81c02008-09-03 18:15:37 +00005638 // Analyze arguments to block.
5639 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5640 "Not a function declarator!");
5641 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005642
Steve Naroff52059382008-10-10 01:28:17 +00005643 CurBlock->hasPrototype = FTI.hasPrototype;
5644 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005645
Steve Naroff52a81c02008-09-03 18:15:37 +00005646 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5647 // no arguments, not a function that takes a single void argument.
5648 if (FTI.hasPrototype &&
5649 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005650 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5651 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005652 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005653 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005654 } else if (FTI.hasPrototype) {
5655 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005656 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005657 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005658 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005659 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005660 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005661 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Douglas Gregor2a2e0402009-06-17 21:51:59 +00005662 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005663 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5664 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5665 // If this has an identifier, add it to the scope stack.
5666 if ((*AI)->getIdentifier())
5667 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005668
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005669 // Check for a valid sentinel attribute on this block.
Douglas Gregor98da6ae2009-06-18 16:11:24 +00005670 if (!CurBlock->isVariadic &&
Argiris Kirtzidisfe5f9732009-06-30 02:34:44 +00005671 CurBlock->TheDecl->getAttr<SentinelAttr>()) {
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005672 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005673 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005674 // FIXME: remove the attribute.
5675 }
5676
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005677 // Analyze the return type.
5678 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5679 QualType RetTy = T->getAsFunctionType()->getResultType();
5680
5681 // Do not allow returning a objc interface by-value.
5682 if (RetTy->isObjCInterfaceType()) {
5683 Diag(ParamInfo.getSourceRange().getBegin(),
5684 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5685 } else if (!RetTy->isDependentType())
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005686 CurBlock->ReturnType = RetTy;
Steve Naroff52a81c02008-09-03 18:15:37 +00005687}
5688
5689/// ActOnBlockError - If there is an error parsing a block, this callback
5690/// is invoked to pop the information about the block from the action impl.
5691void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5692 // Ensure that CurBlock is deleted.
5693 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005694
Chris Lattnere7765e12009-04-19 05:28:12 +00005695 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5696
Steve Naroff52a81c02008-09-03 18:15:37 +00005697 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005698 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005699 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005700 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005701}
5702
5703/// ActOnBlockStmtExpr - This is called when the body of a block statement
5704/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005705Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5706 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005707 // If blocks are disabled, emit an error.
5708 if (!LangOpts.Blocks)
5709 Diag(CaretLoc, diag::err_blocks_disable);
5710
Steve Naroff52a81c02008-09-03 18:15:37 +00005711 // Ensure that CurBlock is deleted.
5712 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005713
Steve Naroff52059382008-10-10 01:28:17 +00005714 PopDeclContext();
5715
Steve Naroff52a81c02008-09-03 18:15:37 +00005716 // Pop off CurBlock, handle nested blocks.
5717 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005718
Steve Naroff52a81c02008-09-03 18:15:37 +00005719 QualType RetTy = Context.VoidTy;
Fariborz Jahanian89942a02009-06-19 23:37:08 +00005720 if (!BSI->ReturnType.isNull())
5721 RetTy = BSI->ReturnType;
Mike Stump9afab102009-02-19 03:04:26 +00005722
Steve Naroff52a81c02008-09-03 18:15:37 +00005723 llvm::SmallVector<QualType, 8> ArgTypes;
5724 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5725 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005726
Mike Stump8e288f42009-07-28 22:04:01 +00005727 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroff52a81c02008-09-03 18:15:37 +00005728 QualType BlockTy;
5729 if (!BSI->hasPrototype)
Mike Stump8e288f42009-07-28 22:04:01 +00005730 BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5731 NoReturn);
Steve Naroff52a81c02008-09-03 18:15:37 +00005732 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005733 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Mike Stump8e288f42009-07-28 22:04:01 +00005734 BSI->isVariadic, 0, false, false, 0, 0,
5735 NoReturn);
Mike Stump9afab102009-02-19 03:04:26 +00005736
Eli Friedman2b128322009-03-23 00:24:07 +00005737 // FIXME: Check that return/parameter types are complete/non-abstract
Douglas Gregor98189262009-06-19 23:52:42 +00005738 DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
Steve Naroff52a81c02008-09-03 18:15:37 +00005739 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005740
Chris Lattnere7765e12009-04-19 05:28:12 +00005741 // If needed, diagnose invalid gotos and switches in the block.
5742 if (CurFunctionNeedsScopeChecking)
5743 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5744 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5745
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005746 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Mike Stump8e288f42009-07-28 22:04:01 +00005747 CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005748 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5749 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005750}
5751
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005752Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5753 ExprArg expr, TypeTy *type,
5754 SourceLocation RPLoc) {
Argiris Kirtzidisd6802ba2009-08-19 01:28:28 +00005755 QualType T = GetTypeFromParser(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005756 Expr *E = static_cast<Expr*>(expr.get());
5757 Expr *OrigExpr = E;
5758
Anders Carlsson36760332007-10-15 20:28:48 +00005759 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005760
5761 // Get the va_list type
5762 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005763 if (VaListType->isArrayType()) {
5764 // Deal with implicit array decay; for example, on x86-64,
5765 // va_list is an array, but it's supposed to decay to
5766 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005767 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005768 // Make sure the input expression also decays appropriately.
5769 UsualUnaryConversions(E);
5770 } else {
5771 // Otherwise, the va_list argument must be an l-value because
5772 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005773 if (!E->isTypeDependent() &&
5774 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005775 return ExprError();
5776 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005777
Douglas Gregor25990972009-05-19 23:10:31 +00005778 if (!E->isTypeDependent() &&
5779 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005780 return ExprError(Diag(E->getLocStart(),
5781 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005782 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005783 }
Mike Stump9afab102009-02-19 03:04:26 +00005784
Eli Friedman2b128322009-03-23 00:24:07 +00005785 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005786 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005787
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005788 expr.release();
5789 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5790 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005791}
5792
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005793Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005794 // The type of __null will be int or long, depending on the size of
5795 // pointers on the target.
5796 QualType Ty;
5797 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5798 Ty = Context.IntTy;
5799 else
5800 Ty = Context.LongTy;
5801
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005802 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005803}
5804
Chris Lattner005ed752008-01-04 18:04:52 +00005805bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5806 SourceLocation Loc,
5807 QualType DstType, QualType SrcType,
5808 Expr *SrcExpr, const char *Flavor) {
5809 // Decode the result (notice that AST's are still created for extensions).
5810 bool isInvalid = false;
5811 unsigned DiagKind;
5812 switch (ConvTy) {
5813 default: assert(0 && "Unknown conversion type");
5814 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005815 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005816 DiagKind = diag::ext_typecheck_convert_pointer_int;
5817 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005818 case IntToPointer:
5819 DiagKind = diag::ext_typecheck_convert_int_pointer;
5820 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005821 case IncompatiblePointer:
5822 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5823 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005824 case IncompatiblePointerSign:
5825 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5826 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005827 case FunctionVoidPointer:
5828 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5829 break;
5830 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005831 // If the qualifiers lost were because we were applying the
5832 // (deprecated) C++ conversion from a string literal to a char*
5833 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5834 // Ideally, this check would be performed in
5835 // CheckPointerTypesForAssignment. However, that would require a
5836 // bit of refactoring (so that the second argument is an
5837 // expression, rather than a type), which should be done as part
5838 // of a larger effort to fix CheckPointerTypesForAssignment for
5839 // C++ semantics.
5840 if (getLangOptions().CPlusPlus &&
5841 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5842 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005843 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5844 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005845 case IntToBlockPointer:
5846 DiagKind = diag::err_int_to_block_pointer;
5847 break;
5848 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005849 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005850 break;
Steve Naroff19608432008-10-14 22:18:38 +00005851 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005852 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005853 // it can give a more specific diagnostic.
5854 DiagKind = diag::warn_incompatible_qualified_id;
5855 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005856 case IncompatibleVectors:
5857 DiagKind = diag::warn_incompatible_vectors;
5858 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005859 case Incompatible:
5860 DiagKind = diag::err_typecheck_convert_incompatible;
5861 isInvalid = true;
5862 break;
5863 }
Mike Stump9afab102009-02-19 03:04:26 +00005864
Chris Lattner271d4c22008-11-24 05:29:24 +00005865 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5866 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005867 return isInvalid;
5868}
Anders Carlssond5201b92008-11-30 19:50:32 +00005869
Chris Lattnereec8ae22009-04-25 21:59:05 +00005870bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005871 llvm::APSInt ICEResult;
5872 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5873 if (Result)
5874 *Result = ICEResult;
5875 return false;
5876 }
5877
Anders Carlssond5201b92008-11-30 19:50:32 +00005878 Expr::EvalResult EvalResult;
5879
Mike Stump9afab102009-02-19 03:04:26 +00005880 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005881 EvalResult.HasSideEffects) {
5882 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5883
5884 if (EvalResult.Diag) {
5885 // We only show the note if it's not the usual "invalid subexpression"
5886 // or if it's actually in a subexpression.
5887 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5888 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5889 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5890 }
Mike Stump9afab102009-02-19 03:04:26 +00005891
Anders Carlssond5201b92008-11-30 19:50:32 +00005892 return true;
5893 }
5894
Eli Friedmance329412009-04-25 22:26:58 +00005895 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5896 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005897
Eli Friedmance329412009-04-25 22:26:58 +00005898 if (EvalResult.Diag &&
5899 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5900 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005901
Anders Carlssond5201b92008-11-30 19:50:32 +00005902 if (Result)
5903 *Result = EvalResult.Val.getInt();
5904 return false;
5905}
Douglas Gregor98189262009-06-19 23:52:42 +00005906
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005907Sema::ExpressionEvaluationContext
5908Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5909 // Introduce a new set of potentially referenced declarations to the stack.
5910 if (NewContext == PotentiallyPotentiallyEvaluated)
5911 PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5912
5913 std::swap(ExprEvalContext, NewContext);
5914 return NewContext;
5915}
5916
5917void
5918Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5919 ExpressionEvaluationContext NewContext) {
5920 ExprEvalContext = NewContext;
5921
5922 if (OldContext == PotentiallyPotentiallyEvaluated) {
5923 // Mark any remaining declarations in the current position of the stack
5924 // as "referenced". If they were not meant to be referenced, semantic
5925 // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5926 PotentiallyReferencedDecls RemainingDecls;
5927 RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5928 PotentiallyReferencedDeclStack.pop_back();
5929
5930 for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5931 IEnd = RemainingDecls.end();
5932 I != IEnd; ++I)
5933 MarkDeclarationReferenced(I->first, I->second);
5934 }
5935}
Douglas Gregor98189262009-06-19 23:52:42 +00005936
5937/// \brief Note that the given declaration was referenced in the source code.
5938///
5939/// This routine should be invoke whenever a given declaration is referenced
5940/// in the source code, and where that reference occurred. If this declaration
5941/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5942/// C99 6.9p3), then the declaration will be marked as used.
5943///
5944/// \param Loc the location where the declaration was referenced.
5945///
5946/// \param D the declaration that has been referenced by the source code.
5947void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5948 assert(D && "No declaration?");
5949
Douglas Gregorcad27f62009-06-22 23:06:13 +00005950 if (D->isUsed())
5951 return;
5952
Douglas Gregor98189262009-06-19 23:52:42 +00005953 // Mark a parameter declaration "used", regardless of whether we're in a
5954 // template or not.
5955 if (isa<ParmVarDecl>(D))
5956 D->setUsed(true);
5957
5958 // Do not mark anything as "used" within a dependent context; wait for
5959 // an instantiation.
5960 if (CurContext->isDependentContext())
5961 return;
5962
Douglas Gregora8b2fbf2009-06-22 20:57:11 +00005963 switch (ExprEvalContext) {
5964 case Unevaluated:
5965 // We are in an expression that is not potentially evaluated; do nothing.
5966 return;
5967
5968 case PotentiallyEvaluated:
5969 // We are in a potentially-evaluated expression, so this declaration is
5970 // "used"; handle this below.
5971 break;
5972
5973 case PotentiallyPotentiallyEvaluated:
5974 // We are in an expression that may be potentially evaluated; queue this
5975 // declaration reference until we know whether the expression is
5976 // potentially evaluated.
5977 PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5978 return;
5979 }
5980
Douglas Gregor98189262009-06-19 23:52:42 +00005981 // Note that this declaration has been used.
Fariborz Jahanian8915a3d2009-06-22 17:30:33 +00005982 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005983 unsigned TypeQuals;
Fariborz Jahanian2f5a0a32009-06-22 20:37:23 +00005984 if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5985 if (!Constructor->isUsed())
5986 DefineImplicitDefaultConstructor(Loc, Constructor);
Mike Stump90fc78e2009-08-04 21:02:39 +00005987 } else if (Constructor->isImplicit() &&
5988 Constructor->isCopyConstructor(Context, TypeQuals)) {
Fariborz Jahanian599778e2009-06-22 23:34:40 +00005989 if (!Constructor->isUsed())
5990 DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5991 }
Fariborz Jahanian368cc6c2009-06-26 23:49:16 +00005992 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5993 if (Destructor->isImplicit() && !Destructor->isUsed())
5994 DefineImplicitDestructor(Loc, Destructor);
5995
Fariborz Jahaniand67364c2009-06-25 21:45:19 +00005996 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5997 if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
5998 MethodDecl->getOverloadedOperator() == OO_Equal) {
5999 if (!MethodDecl->isUsed())
6000 DefineImplicitOverloadedAssign(Loc, MethodDecl);
6001 }
6002 }
Fariborz Jahanianb12bd432009-06-24 22:09:44 +00006003 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006004 // Implicit instantiation of function templates and member functions of
6005 // class templates.
Argiris Kirtzidisccb9efe2009-06-30 02:35:26 +00006006 if (!Function->getBody()) {
Douglas Gregor6f5e0542009-06-26 00:10:03 +00006007 // FIXME: distinguish between implicit instantiations of function
6008 // templates and explicit specializations (the latter don't get
6009 // instantiated, naturally).
6010 if (Function->getInstantiatedFromMemberFunction() ||
6011 Function->getPrimaryTemplate())
Douglas Gregordcdb3842009-06-30 17:20:14 +00006012 PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
Douglas Gregorcad27f62009-06-22 23:06:13 +00006013 }
6014
6015
Douglas Gregor98189262009-06-19 23:52:42 +00006016 // FIXME: keep track of references to static functions
Douglas Gregor98189262009-06-19 23:52:42 +00006017 Function->setUsed(true);
6018 return;
Douglas Gregorcad27f62009-06-22 23:06:13 +00006019 }
Douglas Gregor98189262009-06-19 23:52:42 +00006020
6021 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
Douglas Gregor181fe792009-07-24 20:34:43 +00006022 // Implicit instantiation of static data members of class templates.
6023 // FIXME: distinguish between implicit instantiations (which we need to
6024 // actually instantiate) and explicit specializations.
6025 if (Var->isStaticDataMember() &&
6026 Var->getInstantiatedFromStaticDataMember())
6027 PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6028
Douglas Gregor98189262009-06-19 23:52:42 +00006029 // FIXME: keep track of references to static data?
Douglas Gregor181fe792009-07-24 20:34:43 +00006030
Douglas Gregor98189262009-06-19 23:52:42 +00006031 D->setUsed(true);
Douglas Gregor181fe792009-07-24 20:34:43 +00006032 return;
6033}
Douglas Gregor98189262009-06-19 23:52:42 +00006034}
6035