blob: ee5132a7d8e00da6da0c0f1d3bce4c4164c8b573 [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
Douglas Gregoraa57e862009-02-18 21:56:37 +000029/// \brief Determine whether the use of this declaration is valid, and
30/// emit any corresponding diagnostics.
31///
32/// This routine diagnoses various problems with referencing
33/// declarations that can occur when using a declaration. For example,
34/// it might warn if a deprecated or unavailable declaration is being
35/// used, or produce an error (and return true) if a C++0x deleted
36/// function is being used.
37///
38/// \returns true if there was an error (this declaration cannot be
39/// referenced), false otherwise.
40bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
Chris Lattner2cb744b2009-02-15 22:43:40 +000041 // See if the decl is deprecated.
42 if (D->getAttr<DeprecatedAttr>()) {
Douglas Gregoraa57e862009-02-18 21:56:37 +000043 // Implementing deprecated stuff requires referencing deprecated
44 // stuff. Don't warn if we are implementing a deprecated
45 // construct.
Chris Lattnerfb1bb822009-02-16 19:35:30 +000046 bool isSilenced = false;
47
48 if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
49 // If this reference happens *in* a deprecated function or method, don't
50 // warn.
51 isSilenced = ND->getAttr<DeprecatedAttr>();
52
53 // If this is an Objective-C method implementation, check to see if the
54 // method was deprecated on the declaration, not the definition.
55 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
56 // The semantic decl context of a ObjCMethodDecl is the
57 // ObjCImplementationDecl.
58 if (ObjCImplementationDecl *Impl
59 = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
60
Douglas Gregorc55b0b02009-04-09 21:40:53 +000061 MD = Impl->getClassInterface()->getMethod(Context,
62 MD->getSelector(),
Chris Lattnerfb1bb822009-02-16 19:35:30 +000063 MD->isInstanceMethod());
64 isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
65 }
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
83 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{
Fariborz Jahanian79d29e72009-05-13 23:20:50 +000098 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
99 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;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000120 }
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000121 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
122 // skip over named parameters.
123 ObjCMethodDecl::param_iterator P, E = FD->param_end();
124 for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
125 if (nullPos)
126 --nullPos;
127 else
128 ++i;
129 }
130 warnNotEnoughArgs = (P != E || i >= NumArgs);
131 }
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000132 else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
133 // block or function pointer call.
134 QualType Ty = V->getType();
135 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
136 const FunctionType *FT = Ty->isFunctionPointerType()
137 ? Ty->getAsPointerType()->getPointeeType()->getAsFunctionType()
138 : Ty->getAsBlockPointerType()->getPointeeType()->getAsFunctionType();
139 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
140 unsigned NumArgsInProto = Proto->getNumArgs();
141 unsigned k;
142 for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
143 if (nullPos)
144 --nullPos;
145 else
146 ++i;
147 }
148 warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
149 }
150 if (Ty->isBlockPointerType())
151 isMethod = 2;
152 }
153 else
154 return;
155 }
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000156 else
157 return;
158
159 if (warnNotEnoughArgs) {
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000160 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000161 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000162 return;
163 }
164 int sentinel = i;
165 while (sentinelPos > 0 && i < NumArgs-1) {
166 --sentinelPos;
167 ++i;
168 }
169 if (sentinelPos > 0) {
170 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000171 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000172 return;
173 }
174 while (i < NumArgs-1) {
175 ++i;
176 ++sentinel;
177 }
178 Expr *sentinelExpr = Args[sentinel];
179 if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
180 !sentinelExpr->isNullPointerConstant(Context))) {
Fariborz Jahanianc10357d2009-05-15 20:33:25 +0000181 Diag(Loc, diag::warn_missing_sentinel) << isMethod;
Fariborz Jahanian09f2e3f2009-05-14 18:00:00 +0000182 Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
Fariborz Jahanian79d29e72009-05-13 23:20:50 +0000183 }
184 return;
Fariborz Jahanian180f3412009-05-13 18:09:35 +0000185}
186
Douglas Gregor3bb30002009-02-26 21:00:50 +0000187SourceRange Sema::getExprRange(ExprTy *E) const {
188 Expr *Ex = (Expr *)E;
189 return Ex? Ex->getSourceRange() : SourceRange();
190}
191
Chris Lattner299b8842008-07-25 21:10:04 +0000192//===----------------------------------------------------------------------===//
193// Standard Promotions and Conversions
194//===----------------------------------------------------------------------===//
195
Chris Lattner299b8842008-07-25 21:10:04 +0000196/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
197void Sema::DefaultFunctionArrayConversion(Expr *&E) {
198 QualType Ty = E->getType();
199 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
200
Chris Lattner299b8842008-07-25 21:10:04 +0000201 if (Ty->isFunctionType())
202 ImpCastExprToType(E, Context.getPointerType(Ty));
Chris Lattner2aa68822008-07-25 21:33:13 +0000203 else if (Ty->isArrayType()) {
204 // In C90 mode, arrays only promote to pointers if the array expression is
205 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
206 // type 'array of type' is converted to an expression that has type 'pointer
207 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
208 // that has type 'array of type' ...". The relevant change is "an lvalue"
209 // (C90) to "an expression" (C99).
Argiris Kirtzidisf580b4d2008-09-11 04:25:59 +0000210 //
211 // C++ 4.2p1:
212 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
213 // T" can be converted to an rvalue of type "pointer to T".
214 //
215 if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
216 E->isLvalue(Context) == Expr::LV_Valid)
Chris Lattner2aa68822008-07-25 21:33:13 +0000217 ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
218 }
Chris Lattner299b8842008-07-25 21:10:04 +0000219}
220
Douglas Gregor70b307e2009-05-01 20:41:21 +0000221/// \brief Whether this is a promotable bitfield reference according
222/// to C99 6.3.1.1p2, bullet 2.
223///
224/// \returns the type this bit-field will promote to, or NULL if no
225/// promotion occurs.
226static QualType isPromotableBitField(Expr *E, ASTContext &Context) {
Douglas Gregor531434b2009-05-02 02:18:30 +0000227 FieldDecl *Field = E->getBitField();
228 if (!Field)
Douglas Gregor70b307e2009-05-01 20:41:21 +0000229 return QualType();
230
231 const BuiltinType *BT = Field->getType()->getAsBuiltinType();
232 if (!BT)
233 return QualType();
234
235 if (BT->getKind() != BuiltinType::Bool &&
236 BT->getKind() != BuiltinType::Int &&
237 BT->getKind() != BuiltinType::UInt)
238 return QualType();
239
240 llvm::APSInt BitWidthAP;
241 if (!Field->getBitWidth()->isIntegerConstantExpr(BitWidthAP, Context))
242 return QualType();
243
244 uint64_t BitWidth = BitWidthAP.getZExtValue();
245 uint64_t IntSize = Context.getTypeSize(Context.IntTy);
246 if (BitWidth < IntSize ||
247 (Field->getType()->isSignedIntegerType() && BitWidth == IntSize))
248 return Context.IntTy;
249
250 if (BitWidth == IntSize && Field->getType()->isUnsignedIntegerType())
251 return Context.UnsignedIntTy;
252
253 return QualType();
254}
255
Chris Lattner299b8842008-07-25 21:10:04 +0000256/// UsualUnaryConversions - Performs various conversions that are common to most
257/// operators (C99 6.3). The conversions of array and function types are
258/// sometimes surpressed. For example, the array->pointer conversion doesn't
259/// apply if the array is an argument to the sizeof or address (&) operators.
260/// In these instances, this routine should *not* be called.
261Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
262 QualType Ty = Expr->getType();
263 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
264
Douglas Gregor70b307e2009-05-01 20:41:21 +0000265 // C99 6.3.1.1p2:
266 //
267 // The following may be used in an expression wherever an int or
268 // unsigned int may be used:
269 // - an object or expression with an integer type whose integer
270 // conversion rank is less than or equal to the rank of int
271 // and unsigned int.
272 // - A bit-field of type _Bool, int, signed int, or unsigned int.
273 //
274 // If an int can represent all values of the original type, the
275 // value is converted to an int; otherwise, it is converted to an
276 // unsigned int. These are called the integer promotions. All
277 // other types are unchanged by the integer promotions.
278 if (Ty->isPromotableIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000279 ImpCastExprToType(Expr, Context.IntTy);
Douglas Gregor70b307e2009-05-01 20:41:21 +0000280 return Expr;
281 } else {
282 QualType T = isPromotableBitField(Expr, Context);
283 if (!T.isNull()) {
284 ImpCastExprToType(Expr, T);
285 return Expr;
286 }
287 }
288
289 DefaultFunctionArrayConversion(Expr);
Chris Lattner299b8842008-07-25 21:10:04 +0000290 return Expr;
291}
292
Chris Lattner9305c3d2008-07-25 22:25:12 +0000293/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
294/// do not have a prototype. Arguments that have type float are promoted to
295/// double. All other argument types are converted by UsualUnaryConversions().
296void Sema::DefaultArgumentPromotion(Expr *&Expr) {
297 QualType Ty = Expr->getType();
298 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
299
300 // If this is a 'float' (CVR qualified or typedef) promote to double.
301 if (const BuiltinType *BT = Ty->getAsBuiltinType())
302 if (BT->getKind() == BuiltinType::Float)
303 return ImpCastExprToType(Expr, Context.DoubleTy);
304
305 UsualUnaryConversions(Expr);
306}
307
Chris Lattner81f00ed2009-04-12 08:11:20 +0000308/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
309/// will warn if the resulting type is not a POD type, and rejects ObjC
310/// interfaces passed by value. This returns true if the argument type is
311/// completely illegal.
312bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000313 DefaultArgumentPromotion(Expr);
314
Chris Lattner81f00ed2009-04-12 08:11:20 +0000315 if (Expr->getType()->isObjCInterfaceType()) {
316 Diag(Expr->getLocStart(),
317 diag::err_cannot_pass_objc_interface_to_vararg)
318 << Expr->getType() << CT;
319 return true;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000320 }
Chris Lattner81f00ed2009-04-12 08:11:20 +0000321
322 if (!Expr->getType()->isPODType())
323 Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
324 << Expr->getType() << CT;
325
326 return false;
Anders Carlsson4b8e38c2009-01-16 16:48:51 +0000327}
328
329
Chris Lattner299b8842008-07-25 21:10:04 +0000330/// UsualArithmeticConversions - Performs various conversions that are common to
331/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
332/// routine returns the first non-arithmetic type found. The client is
333/// responsible for emitting appropriate error diagnostics.
334/// FIXME: verify the conversion rules for "complex int" are consistent with
335/// GCC.
336QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
337 bool isCompAssign) {
Eli Friedman3cd92882009-03-28 01:22:36 +0000338 if (!isCompAssign)
Chris Lattner299b8842008-07-25 21:10:04 +0000339 UsualUnaryConversions(lhsExpr);
Eli Friedman3cd92882009-03-28 01:22:36 +0000340
341 UsualUnaryConversions(rhsExpr);
Douglas Gregor70d26122008-11-12 17:17:38 +0000342
Chris Lattner299b8842008-07-25 21:10:04 +0000343 // For conversion purposes, we ignore any qualifiers.
344 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000345 QualType lhs =
346 Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
347 QualType rhs =
348 Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000349
350 // If both types are identical, no conversion is needed.
351 if (lhs == rhs)
352 return lhs;
353
354 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
355 // The caller can deal with this (e.g. pointer + int).
356 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
357 return lhs;
358
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +0000359 // Perform bitfield promotions.
360 QualType LHSBitfieldPromoteTy = isPromotableBitField(lhsExpr, Context);
361 if (!LHSBitfieldPromoteTy.isNull())
362 lhs = LHSBitfieldPromoteTy;
363 QualType RHSBitfieldPromoteTy = isPromotableBitField(rhsExpr, Context);
364 if (!RHSBitfieldPromoteTy.isNull())
365 rhs = RHSBitfieldPromoteTy;
366
Douglas Gregor70d26122008-11-12 17:17:38 +0000367 QualType destType = UsualArithmeticConversionsType(lhs, rhs);
Eli Friedman3cd92882009-03-28 01:22:36 +0000368 if (!isCompAssign)
Douglas Gregor70d26122008-11-12 17:17:38 +0000369 ImpCastExprToType(lhsExpr, destType);
Eli Friedman3cd92882009-03-28 01:22:36 +0000370 ImpCastExprToType(rhsExpr, destType);
Douglas Gregor70d26122008-11-12 17:17:38 +0000371 return destType;
372}
373
374QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
375 // Perform the usual unary conversions. We do this early so that
376 // integral promotions to "int" can allow us to exit early, in the
377 // lhs == rhs check. Also, for conversion purposes, we ignore any
378 // qualifiers. For example, "const float" and "float" are
379 // equivalent.
Chris Lattner2cb744b2009-02-15 22:43:40 +0000380 if (lhs->isPromotableIntegerType())
381 lhs = Context.IntTy;
382 else
383 lhs = lhs.getUnqualifiedType();
384 if (rhs->isPromotableIntegerType())
385 rhs = Context.IntTy;
386 else
387 rhs = rhs.getUnqualifiedType();
Douglas Gregor70d26122008-11-12 17:17:38 +0000388
Chris Lattner299b8842008-07-25 21:10:04 +0000389 // If both types are identical, no conversion is needed.
390 if (lhs == rhs)
391 return lhs;
392
393 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
394 // The caller can deal with this (e.g. pointer + int).
395 if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
396 return lhs;
397
398 // At this point, we have two different arithmetic types.
399
400 // Handle complex types first (C99 6.3.1.8p1).
401 if (lhs->isComplexType() || rhs->isComplexType()) {
402 // if we have an integer operand, the result is the complex type.
403 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
404 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000405 return lhs;
406 }
407 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
408 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000409 return rhs;
410 }
411 // This handles complex/complex, complex/float, or float/complex.
412 // When both operands are complex, the shorter operand is converted to the
413 // type of the longer, and that is the type of the result. This corresponds
414 // to what is done when combining two real floating-point operands.
415 // The fun begins when size promotion occur across type domains.
416 // From H&S 6.3.4: When one operand is complex and the other is a real
417 // floating-point type, the less precise type is converted, within it's
418 // real or complex domain, to the precision of the other type. For example,
419 // when combining a "long double" with a "double _Complex", the
420 // "double _Complex" is promoted to "long double _Complex".
421 int result = Context.getFloatingTypeOrder(lhs, rhs);
422
423 if (result > 0) { // The left side is bigger, convert rhs.
424 rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000425 } else if (result < 0) { // The right side is bigger, convert lhs.
426 lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
Chris Lattner299b8842008-07-25 21:10:04 +0000427 }
428 // At this point, lhs and rhs have the same rank/size. Now, make sure the
429 // domains match. This is a requirement for our implementation, C99
430 // does not require this promotion.
431 if (lhs != rhs) { // Domains don't match, we have complex/float mix.
432 if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
Chris Lattner299b8842008-07-25 21:10:04 +0000433 return rhs;
434 } else { // handle "_Complex double, double".
Chris Lattner299b8842008-07-25 21:10:04 +0000435 return lhs;
436 }
437 }
438 return lhs; // The domain/size match exactly.
439 }
440 // Now handle "real" floating types (i.e. float, double, long double).
441 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
442 // if we have an integer operand, the result is the real floating type.
Anders Carlsson488a0792008-12-10 23:30:05 +0000443 if (rhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000444 // convert rhs to the lhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000445 return lhs;
446 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000447 if (rhs->isComplexIntegerType()) {
448 // convert rhs to the complex floating point type.
449 return Context.getComplexType(lhs);
450 }
451 if (lhs->isIntegerType()) {
Chris Lattner299b8842008-07-25 21:10:04 +0000452 // convert lhs to the rhs floating point type.
Chris Lattner299b8842008-07-25 21:10:04 +0000453 return rhs;
454 }
Anders Carlsson488a0792008-12-10 23:30:05 +0000455 if (lhs->isComplexIntegerType()) {
456 // convert lhs to the complex floating point type.
457 return Context.getComplexType(rhs);
458 }
Chris Lattner299b8842008-07-25 21:10:04 +0000459 // We have two real floating types, float/complex combos were handled above.
460 // Convert the smaller operand to the bigger result.
461 int result = Context.getFloatingTypeOrder(lhs, rhs);
Chris Lattner2cb744b2009-02-15 22:43:40 +0000462 if (result > 0) // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000463 return lhs;
Chris Lattner2cb744b2009-02-15 22:43:40 +0000464 assert(result < 0 && "illegal float comparison");
465 return rhs; // convert the lhs
Chris Lattner299b8842008-07-25 21:10:04 +0000466 }
467 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
468 // Handle GCC complex int extension.
469 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
470 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
471
472 if (lhsComplexInt && rhsComplexInt) {
473 if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
Chris Lattner2cb744b2009-02-15 22:43:40 +0000474 rhsComplexInt->getElementType()) >= 0)
475 return lhs; // convert the rhs
Chris Lattner299b8842008-07-25 21:10:04 +0000476 return rhs;
477 } else if (lhsComplexInt && rhs->isIntegerType()) {
478 // convert the rhs to the lhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000479 return lhs;
480 } else if (rhsComplexInt && lhs->isIntegerType()) {
481 // convert the lhs to the rhs complex type.
Chris Lattner299b8842008-07-25 21:10:04 +0000482 return rhs;
483 }
484 }
485 // Finally, we have two differing integer types.
486 // The rules for this case are in C99 6.3.1.8
487 int compare = Context.getIntegerTypeOrder(lhs, rhs);
488 bool lhsSigned = lhs->isSignedIntegerType(),
489 rhsSigned = rhs->isSignedIntegerType();
490 QualType destType;
491 if (lhsSigned == rhsSigned) {
492 // Same signedness; use the higher-ranked type
493 destType = compare >= 0 ? lhs : rhs;
494 } else if (compare != (lhsSigned ? 1 : -1)) {
495 // The unsigned type has greater than or equal rank to the
496 // signed type, so use the unsigned type
497 destType = lhsSigned ? rhs : lhs;
498 } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
499 // The two types are different widths; if we are here, that
500 // means the signed type is larger than the unsigned type, so
501 // use the signed type.
502 destType = lhsSigned ? lhs : rhs;
503 } else {
504 // The signed type is higher-ranked than the unsigned type,
505 // but isn't actually any bigger (like unsigned int and long
506 // on most 32-bit systems). Use the unsigned type corresponding
507 // to the signed type.
508 destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
509 }
Chris Lattner299b8842008-07-25 21:10:04 +0000510 return destType;
511}
512
513//===----------------------------------------------------------------------===//
514// Semantic Analysis for various Expression Types
515//===----------------------------------------------------------------------===//
516
517
Steve Naroff87d58b42007-09-16 03:34:24 +0000518/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner4b009652007-07-25 00:24:17 +0000519/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
520/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
521/// multiple tokens. However, the common case is that StringToks points to one
522/// string.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000523///
524Action::OwningExprResult
Steve Naroff87d58b42007-09-16 03:34:24 +0000525Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner4b009652007-07-25 00:24:17 +0000526 assert(NumStringToks && "Must have at least one string!");
527
Chris Lattner9eaf2b72009-01-16 18:51:42 +0000528 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Chris Lattner4b009652007-07-25 00:24:17 +0000529 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000530 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +0000531
532 llvm::SmallVector<SourceLocation, 4> StringTokLocs;
533 for (unsigned i = 0; i != NumStringToks; ++i)
534 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattnera6dcce32008-02-11 00:02:17 +0000535
Chris Lattnera6dcce32008-02-11 00:02:17 +0000536 QualType StrTy = Context.CharTy;
Argiris Kirtzidis2a4e1162008-08-09 17:20:01 +0000537 if (Literal.AnyWide) StrTy = Context.getWCharType();
Chris Lattnera6dcce32008-02-11 00:02:17 +0000538 if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
Douglas Gregor1815b3b2008-09-12 00:47:35 +0000539
540 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
541 if (getLangOptions().CPlusPlus)
542 StrTy.addConst();
Sebastian Redlcd883f72009-01-18 18:53:16 +0000543
Chris Lattnera6dcce32008-02-11 00:02:17 +0000544 // Get an array type for the string, according to C99 6.4.5. This includes
545 // the nul terminator character as well as the string length for pascal
546 // strings.
547 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattner14032222009-02-26 23:01:51 +0000548 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattnera6dcce32008-02-11 00:02:17 +0000549 ArrayType::Normal, 0);
Chris Lattnerc3144742009-02-18 05:49:11 +0000550
Chris Lattner4b009652007-07-25 00:24:17 +0000551 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Chris Lattneraa491192009-02-18 06:40:38 +0000552 return Owned(StringLiteral::Create(Context, Literal.GetString(),
553 Literal.GetStringLength(),
554 Literal.AnyWide, StrTy,
555 &StringTokLocs[0],
556 StringTokLocs.size()));
Chris Lattner4b009652007-07-25 00:24:17 +0000557}
558
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000559/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
560/// CurBlock to VD should cause it to be snapshotted (as we do for auto
561/// variables defined outside the block) or false if this is not needed (e.g.
562/// for values inside the block or for globals).
563///
Chris Lattner0b464252009-04-21 22:26:47 +0000564/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
565/// up-to-date.
566///
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000567static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
568 ValueDecl *VD) {
569 // If the value is defined inside the block, we couldn't snapshot it even if
570 // we wanted to.
571 if (CurBlock->TheDecl == VD->getDeclContext())
572 return false;
573
574 // If this is an enum constant or function, it is constant, don't snapshot.
575 if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
576 return false;
577
578 // If this is a reference to an extern, static, or global variable, no need to
579 // snapshot it.
580 // FIXME: What about 'const' variables in C++?
581 if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
Chris Lattner0b464252009-04-21 22:26:47 +0000582 if (!Var->hasLocalStorage())
583 return false;
584
585 // Blocks that have these can't be constant.
586 CurBlock->hasBlockDeclRefExprs = true;
587
588 // If we have nested blocks, the decl may be declared in an outer block (in
589 // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
590 // be defined outside all of the current blocks (in which case the blocks do
591 // all get the bit). Walk the nesting chain.
592 for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
593 NextBlock = NextBlock->PrevBlockInfo) {
594 // If we found the defining block for the variable, don't mark the block as
595 // having a reference outside it.
596 if (NextBlock->TheDecl == VD->getDeclContext())
597 break;
598
599 // Otherwise, the DeclRef from the inner block causes the outer one to need
600 // a snapshot as well.
601 NextBlock->hasBlockDeclRefExprs = true;
602 }
Chris Lattnerb2ebd482008-10-20 05:16:36 +0000603
604 return true;
605}
606
607
608
Steve Naroff0acc9c92007-09-15 18:49:24 +0000609/// ActOnIdentifierExpr - The parser read an identifier in expression context,
Chris Lattner4b009652007-07-25 00:24:17 +0000610/// validate it per-C99 6.5.1. HasTrailingLParen indicates whether this
Steve Naroffe50e14c2008-03-19 23:46:26 +0000611/// identifier is used in a function call context.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000612/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000613/// class or namespace that the identifier must be a member of.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000614Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
615 IdentifierInfo &II,
616 bool HasTrailingLParen,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000617 const CXXScopeSpec *SS,
618 bool isAddressOfOperand) {
619 return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000620 isAddressOfOperand);
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000621}
622
Douglas Gregor566782a2009-01-06 05:10:23 +0000623/// BuildDeclRefExpr - Build either a DeclRefExpr or a
624/// QualifiedDeclRefExpr based on whether or not SS is a
625/// nested-name-specifier.
Sebastian Redl0c9da212009-02-03 20:19:35 +0000626DeclRefExpr *
627Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
628 bool TypeDependent, bool ValueDependent,
629 const CXXScopeSpec *SS) {
Douglas Gregor7e508262009-03-19 03:51:16 +0000630 if (SS && !SS->isEmpty()) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000631 return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
632 ValueDependent, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000633 static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
Douglas Gregor7e508262009-03-19 03:51:16 +0000634 } else
Steve Naroff774e4152009-01-21 00:14:39 +0000635 return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
Douglas Gregor566782a2009-01-06 05:10:23 +0000636}
637
Douglas Gregor723d3332009-01-07 00:43:41 +0000638/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
639/// variable corresponding to the anonymous union or struct whose type
640/// is Record.
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000641static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
642 RecordDecl *Record) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000643 assert(Record->isAnonymousStructOrUnion() &&
644 "Record must be an anonymous struct or union!");
645
Mike Stumpe127ae32009-05-16 07:39:55 +0000646 // FIXME: Once Decls are directly linked together, this will be an O(1)
647 // operation rather than a slow walk through DeclContext's vector (which
648 // itself will be eliminated). DeclGroups might make this even better.
Douglas Gregor723d3332009-01-07 00:43:41 +0000649 DeclContext *Ctx = Record->getDeclContext();
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000650 for (DeclContext::decl_iterator D = Ctx->decls_begin(Context),
651 DEnd = Ctx->decls_end(Context);
Douglas Gregor723d3332009-01-07 00:43:41 +0000652 D != DEnd; ++D) {
653 if (*D == Record) {
654 // The object for the anonymous struct/union directly
655 // follows its type in the list of declarations.
656 ++D;
657 assert(D != DEnd && "Missing object for anonymous record");
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000658 assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
Douglas Gregor723d3332009-01-07 00:43:41 +0000659 return *D;
660 }
661 }
662
663 assert(false && "Missing object for anonymous record");
664 return 0;
665}
666
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000667/// \brief Given a field that represents a member of an anonymous
668/// struct/union, build the path from that field's context to the
669/// actual member.
670///
671/// Construct the sequence of field member references we'll have to
672/// perform to get to the field in the anonymous union/struct. The
673/// list of members is built from the field outward, so traverse it
674/// backwards to go from an object in the current context to the field
675/// we found.
676///
677/// \returns The variable from which the field access should begin,
678/// for an anonymous struct/union that is not a member of another
679/// class. Otherwise, returns NULL.
680VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
681 llvm::SmallVectorImpl<FieldDecl *> &Path) {
Douglas Gregor723d3332009-01-07 00:43:41 +0000682 assert(Field->getDeclContext()->isRecord() &&
683 cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
684 && "Field must be stored inside an anonymous struct or union");
685
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000686 Path.push_back(Field);
Douglas Gregor723d3332009-01-07 00:43:41 +0000687 VarDecl *BaseObject = 0;
688 DeclContext *Ctx = Field->getDeclContext();
689 do {
690 RecordDecl *Record = cast<RecordDecl>(Ctx);
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000691 Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
Douglas Gregor723d3332009-01-07 00:43:41 +0000692 if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000693 Path.push_back(AnonField);
Douglas Gregor723d3332009-01-07 00:43:41 +0000694 else {
695 BaseObject = cast<VarDecl>(AnonObject);
696 break;
697 }
698 Ctx = Ctx->getParent();
699 } while (Ctx->isRecord() &&
700 cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
Douglas Gregorcc94ab72009-04-15 06:41:24 +0000701
702 return BaseObject;
703}
704
705Sema::OwningExprResult
706Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
707 FieldDecl *Field,
708 Expr *BaseObjectExpr,
709 SourceLocation OpLoc) {
710 llvm::SmallVector<FieldDecl *, 4> AnonFields;
711 VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
712 AnonFields);
713
Douglas Gregor723d3332009-01-07 00:43:41 +0000714 // Build the expression that refers to the base object, from
715 // which we will build a sequence of member references to each
716 // of the anonymous union objects and, eventually, the field we
717 // found via name lookup.
718 bool BaseObjectIsPointer = false;
719 unsigned ExtraQuals = 0;
720 if (BaseObject) {
721 // BaseObject is an anonymous struct/union variable (and is,
722 // therefore, not part of another non-anonymous record).
Ted Kremenek0c97e042009-02-07 01:47:29 +0000723 if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
Steve Naroff774e4152009-01-21 00:14:39 +0000724 BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
Mike Stump9afab102009-02-19 03:04:26 +0000725 SourceLocation());
Douglas Gregor723d3332009-01-07 00:43:41 +0000726 ExtraQuals
727 = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
728 } else if (BaseObjectExpr) {
729 // The caller provided the base object expression. Determine
730 // whether its a pointer and whether it adds any qualifiers to the
731 // anonymous struct/union fields we're looking into.
732 QualType ObjectType = BaseObjectExpr->getType();
733 if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
734 BaseObjectIsPointer = true;
735 ObjectType = ObjectPtr->getPointeeType();
736 }
737 ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
738 } else {
739 // We've found a member of an anonymous struct/union that is
740 // inside a non-anonymous struct/union, so in a well-formed
741 // program our base object expression is "this".
742 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
743 if (!MD->isStatic()) {
744 QualType AnonFieldType
745 = Context.getTagDeclType(
746 cast<RecordDecl>(AnonFields.back()->getDeclContext()));
747 QualType ThisType = Context.getTagDeclType(MD->getParent());
748 if ((Context.getCanonicalType(AnonFieldType)
749 == Context.getCanonicalType(ThisType)) ||
750 IsDerivedFrom(ThisType, AnonFieldType)) {
751 // Our base object expression is "this".
Steve Naroff774e4152009-01-21 00:14:39 +0000752 BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +0000753 MD->getThisType(Context));
Douglas Gregor723d3332009-01-07 00:43:41 +0000754 BaseObjectIsPointer = true;
755 }
756 } else {
Sebastian Redlcd883f72009-01-18 18:53:16 +0000757 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
758 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000759 }
760 ExtraQuals = MD->getTypeQualifiers();
761 }
762
763 if (!BaseObjectExpr)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000764 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
765 << Field->getDeclName());
Douglas Gregor723d3332009-01-07 00:43:41 +0000766 }
767
768 // Build the implicit member references to the field of the
769 // anonymous struct/union.
770 Expr *Result = BaseObjectExpr;
771 for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
772 FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
773 FI != FIEnd; ++FI) {
774 QualType MemberType = (*FI)->getType();
775 if (!(*FI)->isMutable()) {
776 unsigned combinedQualifiers
777 = MemberType.getCVRQualifiers() | ExtraQuals;
778 MemberType = MemberType.getQualifiedType(combinedQualifiers);
779 }
Steve Naroff774e4152009-01-21 00:14:39 +0000780 Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
781 OpLoc, MemberType);
Douglas Gregor723d3332009-01-07 00:43:41 +0000782 BaseObjectIsPointer = false;
783 ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
Douglas Gregor723d3332009-01-07 00:43:41 +0000784 }
785
Sebastian Redlcd883f72009-01-18 18:53:16 +0000786 return Owned(Result);
Douglas Gregor723d3332009-01-07 00:43:41 +0000787}
788
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000789/// ActOnDeclarationNameExpr - The parser has read some kind of name
790/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
791/// performs lookup on that name and returns an expression that refers
792/// to that name. This routine isn't directly called from the parser,
793/// because the parser doesn't know about DeclarationName. Rather,
794/// this routine is called by ActOnIdentifierExpr,
795/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
796/// which form the DeclarationName from the corresponding syntactic
797/// forms.
798///
799/// HasTrailingLParen indicates whether this identifier is used in a
800/// function call context. LookupCtx is only used for a C++
801/// qualified-id (foo::bar) to indicate the class or namespace that
802/// the identifier must be a member of.
Douglas Gregora133e262008-12-06 00:22:45 +0000803///
Sebastian Redl0c9da212009-02-03 20:19:35 +0000804/// isAddressOfOperand means that this expression is the direct operand
805/// of an address-of operator. This matters because this is the only
806/// situation where a qualified name referencing a non-static member may
807/// appear outside a member function of this class.
Sebastian Redlcd883f72009-01-18 18:53:16 +0000808Sema::OwningExprResult
809Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
810 DeclarationName Name, bool HasTrailingLParen,
Douglas Gregor4646f9c2009-02-04 15:01:18 +0000811 const CXXScopeSpec *SS,
Sebastian Redl0c9da212009-02-03 20:19:35 +0000812 bool isAddressOfOperand) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000813 // Could be enum-constant, value decl, instance variable, etc.
Douglas Gregor52ae30c2009-01-30 01:04:22 +0000814 if (SS && SS->isInvalid())
815 return ExprError();
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000816
817 // C++ [temp.dep.expr]p3:
818 // An id-expression is type-dependent if it contains:
819 // -- a nested-name-specifier that contains a class-name that
820 // names a dependent type.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000821 // FIXME: Member of the current instantiation.
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000822 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000823 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
824 Loc, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000825 static_cast<NestedNameSpecifier *>(SS->getScopeRep())));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000826 }
827
Douglas Gregor411889e2009-02-13 23:20:09 +0000828 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
829 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000830
Sebastian Redlcd883f72009-01-18 18:53:16 +0000831 if (Lookup.isAmbiguous()) {
832 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
833 SS && SS->isSet() ? SS->getRange()
834 : SourceRange());
835 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000836 }
837
838 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000839
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000840 // If this reference is in an Objective-C method, then ivar lookup happens as
841 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000842 IdentifierInfo *II = Name.getAsIdentifierInfo();
843 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000844 // There are two cases to handle here. 1) scoped lookup could have failed,
845 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000846 // found a decl, but that decl is outside the current instance method (i.e.
847 // a global variable). In these two cases, we do a lookup for an ivar with
848 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000849 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000850 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000851 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000852 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II,
853 ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000854 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000855 if (DiagnoseUseOfDecl(IV, Loc))
856 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000857
858 // If we're referencing an invalid decl, just return this as a silent
859 // error node. The error diagnostic was already emitted on the decl.
860 if (IV->isInvalidDecl())
861 return ExprError();
862
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000863 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
864 // If a class method attemps to use a free standing ivar, this is
865 // an error.
866 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
867 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
868 << IV->getDeclName());
869 // If a class method uses a global variable, even if an ivar with
870 // same name exists, use the global.
871 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000872 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
873 ClassDeclared != IFace)
874 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stumpe127ae32009-05-16 07:39:55 +0000875 // FIXME: This should use a new expr for a direct reference, don't
876 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000877 IdentifierInfo &II = Context.Idents.get("self");
878 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000879 return Owned(new (Context)
880 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000881 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000882 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000883 }
884 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000885 else if (getCurMethodDecl()->isInstanceMethod()) {
886 // We should warn if a local variable hides an ivar.
887 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000888 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000889 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II,
890 ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000891 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
892 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000893 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000894 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000895 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000896 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000897 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000898 QualType T;
899
900 if (getCurMethodDecl()->isInstanceMethod())
901 T = Context.getPointerType(Context.getObjCInterfaceType(
902 getCurMethodDecl()->getClassInterface()));
903 else
904 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000905 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000906 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000907 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000908
Douglas Gregoraa57e862009-02-18 21:56:37 +0000909 // Determine whether this name might be a candidate for
910 // argument-dependent lookup.
911 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
912 HasTrailingLParen;
913
914 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000915 // We've seen something of the form
916 //
917 // identifier(
918 //
919 // and we did not find any entity by the name
920 // "identifier". However, this identifier is still subject to
921 // argument-dependent lookup, so keep track of the name.
922 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
923 Context.OverloadTy,
924 Loc));
925 }
926
Chris Lattner4b009652007-07-25 00:24:17 +0000927 if (D == 0) {
928 // Otherwise, this could be an implicitly declared function reference (legal
929 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000930 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000931 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000932 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000933 else {
934 // If this name wasn't predeclared and if this is not a function call,
935 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000936 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000937 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
938 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000939 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
940 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000941 return ExprError(Diag(Loc, diag::err_undeclared_use)
942 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000943 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000944 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000945 }
946 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000947
Sebastian Redl0c9da212009-02-03 20:19:35 +0000948 // If this is an expression of the form &Class::member, don't build an
949 // implicit member ref, because we want a pointer to the member in general,
950 // not any specific instance's member.
951 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000952 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000953 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000954 QualType DType;
955 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
956 DType = FD->getType().getNonReferenceType();
957 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
958 DType = Method->getType();
959 } else if (isa<OverloadedFunctionDecl>(D)) {
960 DType = Context.OverloadTy;
961 }
962 // Could be an inner type. That's diagnosed below, so ignore it here.
963 if (!DType.isNull()) {
964 // The pointer is type- and value-dependent if it points into something
965 // dependent.
Douglas Gregorf3a200f2009-05-29 14:49:33 +0000966 bool Dependent = DC->isDependentContext();
Douglas Gregor09be81b2009-02-04 17:27:36 +0000967 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000968 }
969 }
970 }
971
Douglas Gregor723d3332009-01-07 00:43:41 +0000972 // We may have found a field within an anonymous union or struct
973 // (C++ [class.union]).
974 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
975 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
976 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000977
Douglas Gregor3257fb52008-12-22 05:46:06 +0000978 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
979 if (!MD->isStatic()) {
980 // C++ [class.mfct.nonstatic]p2:
981 // [...] if name lookup (3.4.1) resolves the name in the
982 // id-expression to a nonstatic nontype member of class X or of
983 // a base class of X, the id-expression is transformed into a
984 // class member access expression (5.2.5) using (*this) (9.3.2)
985 // as the postfix-expression to the left of the '.' operator.
986 DeclContext *Ctx = 0;
987 QualType MemberType;
988 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
989 Ctx = FD->getDeclContext();
990 MemberType = FD->getType();
991
992 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
993 MemberType = RefType->getPointeeType();
994 else if (!FD->isMutable()) {
995 unsigned combinedQualifiers
996 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
997 MemberType = MemberType.getQualifiedType(combinedQualifiers);
998 }
999 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1000 if (!Method->isStatic()) {
1001 Ctx = Method->getParent();
1002 MemberType = Method->getType();
1003 }
1004 } else if (OverloadedFunctionDecl *Ovl
1005 = dyn_cast<OverloadedFunctionDecl>(D)) {
1006 for (OverloadedFunctionDecl::function_iterator
1007 Func = Ovl->function_begin(),
1008 FuncEnd = Ovl->function_end();
1009 Func != FuncEnd; ++Func) {
1010 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
1011 if (!DMethod->isStatic()) {
1012 Ctx = Ovl->getDeclContext();
1013 MemberType = Context.OverloadTy;
1014 break;
1015 }
1016 }
1017 }
Douglas Gregor723d3332009-01-07 00:43:41 +00001018
1019 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001020 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
1021 QualType ThisType = Context.getTagDeclType(MD->getParent());
1022 if ((Context.getCanonicalType(CtxType)
1023 == Context.getCanonicalType(ThisType)) ||
1024 IsDerivedFrom(ThisType, CtxType)) {
1025 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +00001026 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +00001027 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +00001028 return Owned(new (Context) MemberExpr(This, true, D,
Eli Friedman1653e232009-04-29 17:56:47 +00001029 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001030 }
1031 }
1032 }
1033 }
1034
Douglas Gregor8acb7272008-12-11 16:49:14 +00001035 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001036 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1037 if (MD->isStatic())
1038 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001039 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1040 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001041 }
1042
Douglas Gregor3257fb52008-12-22 05:46:06 +00001043 // Any other ways we could have found the field in a well-formed
1044 // program would have been turned into implicit member expressions
1045 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001046 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1047 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001048 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001049
Chris Lattner4b009652007-07-25 00:24:17 +00001050 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001051 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001052 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001053 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001054 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001055 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001056
Steve Naroffd6163f32008-09-05 22:11:13 +00001057 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001058 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001059 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1060 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001061 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
1062 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1063 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +00001064 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001065
Douglas Gregoraa57e862009-02-18 21:56:37 +00001066 // Check whether this declaration can be used. Note that we suppress
1067 // this check when we're going to perform argument-dependent lookup
1068 // on this function name, because this might not be the function
1069 // that overload resolution actually selects.
1070 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1071 return ExprError();
1072
Douglas Gregor48840c72008-12-10 23:01:14 +00001073 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +00001074 // Warn about constructs like:
1075 // if (void *X = foo()) { ... } else { X }.
1076 // In the else block, the pointer is always false.
Douglas Gregorf3a200f2009-05-29 14:49:33 +00001077
1078 // FIXME: In a template instantiation, we don't have scope
1079 // information to check this property.
Douglas Gregor48840c72008-12-10 23:01:14 +00001080 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1081 Scope *CheckS = S;
1082 while (CheckS) {
1083 if (CheckS->isWithinElse() &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00001084 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
Douglas Gregor48840c72008-12-10 23:01:14 +00001085 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001086 ExprError(Diag(Loc, diag::warn_value_always_false)
1087 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +00001088 else
Sebastian Redlcd883f72009-01-18 18:53:16 +00001089 ExprError(Diag(Loc, diag::warn_value_always_zero)
1090 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +00001091 break;
1092 }
1093
1094 // Move up one more control parent to check again.
1095 CheckS = CheckS->getControlParent();
1096 if (CheckS)
1097 CheckS = CheckS->getParent();
1098 }
1099 }
Douglas Gregor1f88aa72009-02-25 16:33:18 +00001100 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
1101 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1102 // C99 DR 316 says that, if a function type comes from a
1103 // function definition (without a prototype), that type is only
1104 // used for checking compatibility. Therefore, when referencing
1105 // the function, we pretend that we don't have the full function
1106 // type.
1107 QualType T = Func->getType();
1108 QualType NoProtoType = T;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001109 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
1110 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor1f88aa72009-02-25 16:33:18 +00001111 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
1112 }
Douglas Gregor48840c72008-12-10 23:01:14 +00001113 }
Steve Naroffd6163f32008-09-05 22:11:13 +00001114
1115 // Only create DeclRefExpr's for valid Decl's.
1116 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001117 return ExprError();
1118
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001119 // If the identifier reference is inside a block, and it refers to a value
1120 // that is outside the block, create a BlockDeclRefExpr instead of a
1121 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1122 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001123 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001124 // We do not do this for things like enum constants, global variables, etc,
1125 // as they do not get snapshotted.
1126 //
1127 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001128 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001129 // The BlocksAttr indicates the variable is bound by-reference.
1130 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001131 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001132
Steve Naroff52059382008-10-10 01:28:17 +00001133 // Variable will be bound by-copy, make it const within the closure.
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001134 ExprTy.addConst();
1135 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +00001136 }
1137 // If this reference is not in a block or if the referenced variable is
1138 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001139
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001140 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001141 bool ValueDependent = false;
1142 if (getLangOptions().CPlusPlus) {
1143 // C++ [temp.dep.expr]p3:
1144 // An id-expression is type-dependent if it contains:
1145 // - an identifier that was declared with a dependent type,
1146 if (VD->getType()->isDependentType())
1147 TypeDependent = true;
1148 // - FIXME: a template-id that is dependent,
1149 // - a conversion-function-id that specifies a dependent type,
1150 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1151 Name.getCXXNameType()->isDependentType())
1152 TypeDependent = true;
1153 // - a nested-name-specifier that contains a class-name that
1154 // names a dependent type.
1155 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001156 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001157 DC; DC = DC->getParent()) {
1158 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001159 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001160 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1161 if (Context.getTypeDeclType(Record)->isDependentType()) {
1162 TypeDependent = true;
1163 break;
1164 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001165 }
1166 }
1167 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001168
Douglas Gregora5d84612008-12-10 20:57:37 +00001169 // C++ [temp.dep.constexpr]p2:
1170 //
1171 // An identifier is value-dependent if it is:
1172 // - a name declared with a dependent type,
1173 if (TypeDependent)
1174 ValueDependent = true;
1175 // - the name of a non-type template parameter,
1176 else if (isa<NonTypeTemplateParmDecl>(VD))
1177 ValueDependent = true;
1178 // - a constant with integral or enumeration type and is
1179 // initialized with an expression that is value-dependent
1180 // (FIXME!).
1181 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001182
Sebastian Redlcd883f72009-01-18 18:53:16 +00001183 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1184 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +00001185}
1186
Sebastian Redlcd883f72009-01-18 18:53:16 +00001187Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1188 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001189 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001190
Chris Lattner4b009652007-07-25 00:24:17 +00001191 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001192 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001193 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1194 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1195 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001196 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001197
Chris Lattner7e637512008-01-12 08:14:25 +00001198 // Pre-defined identifiers are of type char[x], where x is the length of the
1199 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001200 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001201 if (FunctionDecl *FD = getCurFunctionDecl())
1202 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001203 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1204 Length = MD->getSynthesizedMethodSize();
1205 else {
1206 Diag(Loc, diag::ext_predef_outside_function);
1207 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1208 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1209 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001210
1211
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001212 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001213 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001214 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001215 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001216}
1217
Sebastian Redlcd883f72009-01-18 18:53:16 +00001218Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001219 llvm::SmallString<16> CharBuffer;
1220 CharBuffer.resize(Tok.getLength());
1221 const char *ThisTokBegin = &CharBuffer[0];
1222 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001223
Chris Lattner4b009652007-07-25 00:24:17 +00001224 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1225 Tok.getLocation(), PP);
1226 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001227 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001228
1229 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1230
Sebastian Redl75324932009-01-20 22:23:13 +00001231 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1232 Literal.isWide(),
1233 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001234}
1235
Sebastian Redlcd883f72009-01-18 18:53:16 +00001236Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1237 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001238 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1239 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001240 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001241 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001242 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001243 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001244 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001245
Chris Lattner4b009652007-07-25 00:24:17 +00001246 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001247 // Add padding so that NumericLiteralParser can overread by one character.
1248 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001249 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001250
Chris Lattner4b009652007-07-25 00:24:17 +00001251 // Get the spelling of the token, which eliminates trigraphs, etc.
1252 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001253
Chris Lattner4b009652007-07-25 00:24:17 +00001254 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1255 Tok.getLocation(), PP);
1256 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001257 return ExprError();
1258
Chris Lattner1de66eb2007-08-26 03:42:43 +00001259 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001260
Chris Lattner1de66eb2007-08-26 03:42:43 +00001261 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001262 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001263 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001264 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001265 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001266 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001267 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001268 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001269
1270 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1271
Ted Kremenekddedbe22007-11-29 00:56:49 +00001272 // isExact will be set by GetFloatValue().
1273 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001274 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1275 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001276
Chris Lattner1de66eb2007-08-26 03:42:43 +00001277 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001278 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001279 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001280 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001281
Neil Booth7421e9c2007-08-29 22:00:19 +00001282 // long long is a C99 feature.
1283 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001284 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001285 Diag(Tok.getLocation(), diag::ext_longlong);
1286
Chris Lattner4b009652007-07-25 00:24:17 +00001287 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001288 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001289
Chris Lattner4b009652007-07-25 00:24:17 +00001290 if (Literal.GetIntegerValue(ResultVal)) {
1291 // If this value didn't fit into uintmax_t, warn and force to ull.
1292 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001293 Ty = Context.UnsignedLongLongTy;
1294 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001295 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001296 } else {
1297 // If this value fits into a ULL, try to figure out what else it fits into
1298 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001299
Chris Lattner4b009652007-07-25 00:24:17 +00001300 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1301 // be an unsigned int.
1302 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1303
1304 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001305 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001306 if (!Literal.isLong && !Literal.isLongLong) {
1307 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001308 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001309
Chris Lattner4b009652007-07-25 00:24:17 +00001310 // Does it fit in a unsigned int?
1311 if (ResultVal.isIntN(IntSize)) {
1312 // Does it fit in a signed int?
1313 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001314 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001315 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001316 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001317 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001318 }
Chris Lattner4b009652007-07-25 00:24:17 +00001319 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001320
Chris Lattner4b009652007-07-25 00:24:17 +00001321 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001322 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001323 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001324
Chris Lattner4b009652007-07-25 00:24:17 +00001325 // Does it fit in a unsigned long?
1326 if (ResultVal.isIntN(LongSize)) {
1327 // Does it fit in a signed long?
1328 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001329 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001330 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001331 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001332 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001333 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001334 }
1335
Chris Lattner4b009652007-07-25 00:24:17 +00001336 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001337 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001338 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001339
Chris Lattner4b009652007-07-25 00:24:17 +00001340 // Does it fit in a unsigned long long?
1341 if (ResultVal.isIntN(LongLongSize)) {
1342 // Does it fit in a signed long long?
1343 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001344 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001345 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001346 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001347 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001348 }
1349 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001350
Chris Lattner4b009652007-07-25 00:24:17 +00001351 // If we still couldn't decide a type, we probably have something that
1352 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001353 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001354 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001355 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001356 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001357 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001358
Chris Lattnere4068872008-05-09 05:59:00 +00001359 if (ResultVal.getBitWidth() != Width)
1360 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001361 }
Sebastian Redl75324932009-01-20 22:23:13 +00001362 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001363 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001364
Chris Lattner1de66eb2007-08-26 03:42:43 +00001365 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1366 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001367 Res = new (Context) ImaginaryLiteral(Res,
1368 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001369
1370 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001371}
1372
Sebastian Redlcd883f72009-01-18 18:53:16 +00001373Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1374 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001375 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001376 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001377 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001378}
1379
1380/// The UsualUnaryConversions() function is *not* called by this routine.
1381/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001382bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001383 SourceLocation OpLoc,
1384 const SourceRange &ExprRange,
1385 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001386 if (exprType->isDependentType())
1387 return false;
1388
Chris Lattner4b009652007-07-25 00:24:17 +00001389 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001390 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001391 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001392 if (isSizeof)
1393 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1394 return false;
1395 }
1396
Chris Lattner95933c12009-04-24 00:30:45 +00001397 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001398 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001399 Diag(OpLoc, diag::ext_sizeof_void_type)
1400 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001401 return false;
1402 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001403
Chris Lattner95933c12009-04-24 00:30:45 +00001404 if (RequireCompleteType(OpLoc, exprType,
1405 isSizeof ? diag::err_sizeof_incomplete_type :
1406 diag::err_alignof_incomplete_type,
1407 ExprRange))
1408 return true;
1409
1410 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001411 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001412 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001413 << exprType << isSizeof << ExprRange;
1414 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001415 }
1416
Chris Lattner95933c12009-04-24 00:30:45 +00001417 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001418}
1419
Chris Lattner8d9f7962009-01-24 20:17:12 +00001420bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1421 const SourceRange &ExprRange) {
1422 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001423
Chris Lattner8d9f7962009-01-24 20:17:12 +00001424 // alignof decl is always ok.
1425 if (isa<DeclRefExpr>(E))
1426 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001427
1428 // Cannot know anything else if the expression is dependent.
1429 if (E->isTypeDependent())
1430 return false;
1431
Douglas Gregor531434b2009-05-02 02:18:30 +00001432 if (E->getBitField()) {
1433 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1434 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001435 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001436
1437 // Alignment of a field access is always okay, so long as it isn't a
1438 // bit-field.
1439 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1440 if (dyn_cast<FieldDecl>(ME->getMemberDecl()))
1441 return false;
1442
Chris Lattner8d9f7962009-01-24 20:17:12 +00001443 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1444}
1445
Douglas Gregor396f1142009-03-13 21:01:28 +00001446/// \brief Build a sizeof or alignof expression given a type operand.
1447Action::OwningExprResult
1448Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1449 bool isSizeOf, SourceRange R) {
1450 if (T.isNull())
1451 return ExprError();
1452
1453 if (!T->isDependentType() &&
1454 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1455 return ExprError();
1456
1457 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1458 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1459 Context.getSizeType(), OpLoc,
1460 R.getEnd()));
1461}
1462
1463/// \brief Build a sizeof or alignof expression given an expression
1464/// operand.
1465Action::OwningExprResult
1466Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1467 bool isSizeOf, SourceRange R) {
1468 // Verify that the operand is valid.
1469 bool isInvalid = false;
1470 if (E->isTypeDependent()) {
1471 // Delay type-checking for type-dependent expressions.
1472 } else if (!isSizeOf) {
1473 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001474 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001475 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1476 isInvalid = true;
1477 } else {
1478 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1479 }
1480
1481 if (isInvalid)
1482 return ExprError();
1483
1484 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1485 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1486 Context.getSizeType(), OpLoc,
1487 R.getEnd()));
1488}
1489
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001490/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1491/// the same for @c alignof and @c __alignof
1492/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001493Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001494Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1495 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001496 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001497 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001498
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001499 if (isType) {
Douglas Gregor396f1142009-03-13 21:01:28 +00001500 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1501 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1502 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001503
Douglas Gregor396f1142009-03-13 21:01:28 +00001504 // Get the end location.
1505 Expr *ArgEx = (Expr *)TyOrEx;
1506 Action::OwningExprResult Result
1507 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1508
1509 if (Result.isInvalid())
1510 DeleteExpr(ArgEx);
1511
1512 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001513}
1514
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001515QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001516 if (V->isTypeDependent())
1517 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001518
Chris Lattnera16e42d2007-08-26 05:39:26 +00001519 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001520 if (const ComplexType *CT = V->getType()->getAsComplexType())
1521 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001522
1523 // Otherwise they pass through real integer and floating point types here.
1524 if (V->getType()->isArithmeticType())
1525 return V->getType();
1526
1527 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001528 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1529 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001530 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001531}
1532
1533
Chris Lattner4b009652007-07-25 00:24:17 +00001534
Sebastian Redl8b769972009-01-19 00:08:26 +00001535Action::OwningExprResult
1536Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1537 tok::TokenKind Kind, ExprArg Input) {
1538 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001539
Chris Lattner4b009652007-07-25 00:24:17 +00001540 UnaryOperator::Opcode Opc;
1541 switch (Kind) {
1542 default: assert(0 && "Unknown unary op!");
1543 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1544 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1545 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001546
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001547 if (getLangOptions().CPlusPlus &&
1548 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1549 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001550 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001551 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1552
1553 // C++ [over.inc]p1:
1554 //
1555 // [...] If the function is a member function with one
1556 // parameter (which shall be of type int) or a non-member
1557 // function with two parameters (the second of which shall be
1558 // of type int), it defines the postfix increment operator ++
1559 // for objects of that type. When the postfix increment is
1560 // called as a result of using the ++ operator, the int
1561 // argument will have value zero.
1562 Expr *Args[2] = {
1563 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001564 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1565 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001566 };
1567
1568 // Build the candidate set for overloading
1569 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001570 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001571
1572 // Perform overload resolution.
1573 OverloadCandidateSet::iterator Best;
1574 switch (BestViableFunction(CandidateSet, Best)) {
1575 case OR_Success: {
1576 // We found a built-in operator or an overloaded operator.
1577 FunctionDecl *FnDecl = Best->Function;
1578
1579 if (FnDecl) {
1580 // We matched an overloaded operator. Build a call to that
1581 // operator.
1582
1583 // Convert the arguments.
1584 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1585 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001586 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001587 } else {
1588 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001589 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001590 FnDecl->getParamDecl(0)->getType(),
1591 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001592 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001593 }
1594
1595 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001596 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001597 = FnDecl->getType()->getAsFunctionType()->getResultType();
1598 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001599
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001600 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001601 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001602 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001603 UsualUnaryConversions(FnExpr);
1604
Sebastian Redl8b769972009-01-19 00:08:26 +00001605 Input.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001606 Args[0] = Arg;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001607 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1608 Args, 2, ResultTy,
1609 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001610 } else {
1611 // We matched a built-in operator. Convert the arguments, then
1612 // break out so that we will build the appropriate built-in
1613 // operator node.
1614 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1615 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001616 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001617
1618 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001619 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001620 }
1621
1622 case OR_No_Viable_Function:
1623 // No viable function; fall through to handling this as a
1624 // built-in operator, which will produce an error message for us.
1625 break;
1626
1627 case OR_Ambiguous:
1628 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1629 << UnaryOperator::getOpcodeStr(Opc)
1630 << Arg->getSourceRange();
1631 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001632 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001633
1634 case OR_Deleted:
1635 Diag(OpLoc, diag::err_ovl_deleted_oper)
1636 << Best->Function->isDeleted()
1637 << UnaryOperator::getOpcodeStr(Opc)
1638 << Arg->getSourceRange();
1639 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1640 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001641 }
1642
1643 // Either we found no viable overloaded operator or we matched a
1644 // built-in operator. In either case, fall through to trying to
1645 // build a built-in operation.
1646 }
1647
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001648 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1649 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001650 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001651 return ExprError();
1652 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001653 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001654}
1655
Sebastian Redl8b769972009-01-19 00:08:26 +00001656Action::OwningExprResult
1657Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1658 ExprArg Idx, SourceLocation RLoc) {
1659 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1660 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001661
Douglas Gregor80723c52008-11-19 17:17:41 +00001662 if (getLangOptions().CPlusPlus &&
Douglas Gregorde72f3e2009-05-19 00:01:19 +00001663 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1664 Base.release();
1665 Idx.release();
1666 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1667 Context.DependentTy, RLoc));
1668 }
1669
1670 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001671 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001672 LHSExp->getType()->isEnumeralType() ||
1673 RHSExp->getType()->isRecordType() ||
1674 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001675 // Add the appropriate overloaded operators (C++ [over.match.oper])
1676 // to the candidate set.
1677 OverloadCandidateSet CandidateSet;
1678 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001679 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1680 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001681
Douglas Gregor80723c52008-11-19 17:17:41 +00001682 // Perform overload resolution.
1683 OverloadCandidateSet::iterator Best;
1684 switch (BestViableFunction(CandidateSet, Best)) {
1685 case OR_Success: {
1686 // We found a built-in operator or an overloaded operator.
1687 FunctionDecl *FnDecl = Best->Function;
1688
1689 if (FnDecl) {
1690 // We matched an overloaded operator. Build a call to that
1691 // operator.
1692
1693 // Convert the arguments.
1694 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1695 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1696 PerformCopyInitialization(RHSExp,
1697 FnDecl->getParamDecl(0)->getType(),
1698 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001699 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001700 } else {
1701 // Convert the arguments.
1702 if (PerformCopyInitialization(LHSExp,
1703 FnDecl->getParamDecl(0)->getType(),
1704 "passing") ||
1705 PerformCopyInitialization(RHSExp,
1706 FnDecl->getParamDecl(1)->getType(),
1707 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001708 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001709 }
1710
1711 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001712 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001713 = FnDecl->getType()->getAsFunctionType()->getResultType();
1714 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001715
Douglas Gregor80723c52008-11-19 17:17:41 +00001716 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001717 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1718 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001719 UsualUnaryConversions(FnExpr);
1720
Sebastian Redl8b769972009-01-19 00:08:26 +00001721 Base.release();
1722 Idx.release();
Douglas Gregorb2f81ac2009-05-27 05:00:47 +00001723 Args[0] = LHSExp;
1724 Args[1] = RHSExp;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001725 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1726 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001727 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001728 } else {
1729 // We matched a built-in operator. Convert the arguments, then
1730 // break out so that we will build the appropriate built-in
1731 // operator node.
1732 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1733 "passing") ||
1734 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1735 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001736 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001737
1738 break;
1739 }
1740 }
1741
1742 case OR_No_Viable_Function:
1743 // No viable function; fall through to handling this as a
1744 // built-in operator, which will produce an error message for us.
1745 break;
1746
1747 case OR_Ambiguous:
1748 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1749 << "[]"
1750 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1751 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001752 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001753
1754 case OR_Deleted:
1755 Diag(LLoc, diag::err_ovl_deleted_oper)
1756 << Best->Function->isDeleted()
1757 << "[]"
1758 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1759 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1760 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001761 }
1762
1763 // Either we found no viable overloaded operator or we matched a
1764 // built-in operator. In either case, fall through to trying to
1765 // build a built-in operation.
1766 }
1767
Chris Lattner4b009652007-07-25 00:24:17 +00001768 // Perform default conversions.
1769 DefaultFunctionArrayConversion(LHSExp);
1770 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001771
Chris Lattner4b009652007-07-25 00:24:17 +00001772 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1773
1774 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001775 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001776 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001777 // and index from the expression types.
1778 Expr *BaseExpr, *IndexExpr;
1779 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001780 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1781 BaseExpr = LHSExp;
1782 IndexExpr = RHSExp;
1783 ResultType = Context.DependentTy;
1784 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001785 BaseExpr = LHSExp;
1786 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001787 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001788 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001789 // Handle the uncommon case of "123[Ptr]".
1790 BaseExpr = RHSExp;
1791 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001792 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001793 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1794 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001795 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001796
Chris Lattner4b009652007-07-25 00:24:17 +00001797 // FIXME: need to deal with const...
1798 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001799 } else if (LHSTy->isArrayType()) {
1800 // If we see an array that wasn't promoted by
1801 // DefaultFunctionArrayConversion, it must be an array that
1802 // wasn't promoted because of the C90 rule that doesn't
1803 // allow promoting non-lvalue arrays. Warn, then
1804 // force the promotion here.
1805 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1806 LHSExp->getSourceRange();
1807 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1808 LHSTy = LHSExp->getType();
1809
1810 BaseExpr = LHSExp;
1811 IndexExpr = RHSExp;
1812 ResultType = LHSTy->getAsPointerType()->getPointeeType();
1813 } else if (RHSTy->isArrayType()) {
1814 // Same as previous, except for 123[f().a] case
1815 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1816 RHSExp->getSourceRange();
1817 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1818 RHSTy = RHSExp->getType();
1819
1820 BaseExpr = RHSExp;
1821 IndexExpr = LHSExp;
1822 ResultType = RHSTy->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001823 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001824 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1825 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001826 }
Chris Lattner4b009652007-07-25 00:24:17 +00001827 // C99 6.5.2.1p1
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001828 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001829 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1830 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001831
Douglas Gregor05e28f62009-03-24 19:52:54 +00001832 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1833 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1834 // type. Note that Functions are not objects, and that (in C99 parlance)
1835 // incomplete types are not object types.
1836 if (ResultType->isFunctionType()) {
1837 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1838 << ResultType << BaseExpr->getSourceRange();
1839 return ExprError();
1840 }
Chris Lattner95933c12009-04-24 00:30:45 +00001841
Douglas Gregor05e28f62009-03-24 19:52:54 +00001842 if (!ResultType->isDependentType() &&
Chris Lattner95933c12009-04-24 00:30:45 +00001843 RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type,
Douglas Gregor05e28f62009-03-24 19:52:54 +00001844 BaseExpr->getSourceRange()))
1845 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001846
1847 // Diagnose bad cases where we step over interface counts.
1848 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1849 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1850 << ResultType << BaseExpr->getSourceRange();
1851 return ExprError();
1852 }
1853
Sebastian Redl8b769972009-01-19 00:08:26 +00001854 Base.release();
1855 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001856 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001857 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001858}
1859
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001860QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001861CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001862 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001863 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001864
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001865 // The vector accessor can't exceed the number of elements.
1866 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001867
Mike Stump9afab102009-02-19 03:04:26 +00001868 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001869 // special names that indicate a subset of exactly half the elements are
1870 // to be selected.
1871 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001872
Nate Begeman1486b502009-01-18 01:47:54 +00001873 // This flag determines whether or not CompName has an 's' char prefix,
1874 // indicating that it is a string of hex values to be used as vector indices.
1875 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001876
1877 // Check that we've found one of the special components, or that the component
1878 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001879 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001880 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1881 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001882 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001883 do
1884 compStr++;
1885 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001886 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001887 do
1888 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001889 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001890 }
Nate Begeman1486b502009-01-18 01:47:54 +00001891
Mike Stump9afab102009-02-19 03:04:26 +00001892 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001893 // We didn't get to the end of the string. This means the component names
1894 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001895 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1896 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001897 return QualType();
1898 }
Mike Stump9afab102009-02-19 03:04:26 +00001899
Nate Begeman1486b502009-01-18 01:47:54 +00001900 // Ensure no component accessor exceeds the width of the vector type it
1901 // operates on.
1902 if (!HalvingSwizzle) {
1903 compStr = CompName.getName();
1904
1905 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001906 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001907
1908 while (*compStr) {
1909 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1910 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1911 << baseType << SourceRange(CompLoc);
1912 return QualType();
1913 }
1914 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001915 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001916
Nate Begeman1486b502009-01-18 01:47:54 +00001917 // If this is a halving swizzle, verify that the base type has an even
1918 // number of elements.
1919 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001920 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001921 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001922 return QualType();
1923 }
Mike Stump9afab102009-02-19 03:04:26 +00001924
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001925 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001926 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001927 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001928 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001929 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001930 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1931 : CompName.getLength();
1932 if (HexSwizzle)
1933 CompSize--;
1934
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001935 if (CompSize == 1)
1936 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001937
Nate Begemanaf6ed502008-04-18 23:10:10 +00001938 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001939 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001940 // diagostics look bad. We want extended vector types to appear built-in.
1941 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1942 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1943 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001944 }
1945 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001946}
1947
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001948static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1949 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001950 const Selector &Sel,
1951 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001952
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001953 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Context, &Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001954 return PD;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001955 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Context, Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001956 return OMD;
1957
1958 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1959 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001960 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1961 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001962 return D;
1963 }
1964 return 0;
1965}
1966
1967static Decl *FindGetterNameDecl(const ObjCQualifiedIdType *QIdTy,
1968 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001969 const Selector &Sel,
1970 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001971 // Check protocols on qualified interfaces.
1972 Decl *GDecl = 0;
1973 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1974 E = QIdTy->qual_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001975 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context, &Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001976 GDecl = PD;
1977 break;
1978 }
1979 // Also must look for a getter name which uses property syntax.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001980 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Context, Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001981 GDecl = OMD;
1982 break;
1983 }
1984 }
1985 if (!GDecl) {
1986 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1987 E = QIdTy->qual_end(); I != E; ++I) {
1988 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001989 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001990 if (GDecl)
1991 return GDecl;
1992 }
1993 }
1994 return GDecl;
1995}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001996
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001997/// FindMethodInNestedImplementations - Look up a method in current and
1998/// all base class implementations.
1999///
2000ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
2001 const ObjCInterfaceDecl *IFace,
2002 const Selector &Sel) {
2003 ObjCMethodDecl *Method = 0;
Douglas Gregorafd5eb32009-04-24 00:11:27 +00002004 if (ObjCImplementationDecl *ImpDecl
2005 = LookupObjCImplementation(IFace->getIdentifier()))
Douglas Gregorcd19b572009-04-23 01:02:12 +00002006 Method = ImpDecl->getInstanceMethod(Context, Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002007
2008 if (!Method && IFace->getSuperClass())
2009 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
2010 return Method;
2011}
2012
Sebastian Redl8b769972009-01-19 00:08:26 +00002013Action::OwningExprResult
2014Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2015 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002016 IdentifierInfo &Member,
Chris Lattner5261d0c2009-03-28 19:18:32 +00002017 DeclPtrTy ObjCImpDecl) {
Anders Carlssonc154a722009-05-01 19:30:39 +00002018 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00002019 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00002020
2021 // Perform default conversions.
2022 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00002023
Steve Naroff2cb66382007-07-26 03:11:44 +00002024 QualType BaseType = BaseExpr->getType();
2025 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002026
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002027 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2028 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002029 if (OpKind == tok::arrow) {
Anders Carlsson72d3c662009-05-15 23:10:19 +00002030 if (BaseType->isDependentType())
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002031 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2032 BaseExpr, true,
2033 OpLoc,
2034 DeclarationName(&Member),
2035 MemberLoc));
Anders Carlsson72d3c662009-05-15 23:10:19 +00002036 else if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00002037 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00002038 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00002039 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
2040 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00002041 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002042 return ExprError(Diag(MemberLoc,
2043 diag::err_typecheck_member_reference_arrow)
2044 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002045 } else {
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002046 if (BaseType->isDependentType()) {
2047 // Require that the base type isn't a pointer type
2048 // (so we'll report an error for)
2049 // T* t;
2050 // t.f;
2051 //
2052 // In Obj-C++, however, the above expression is valid, since it could be
2053 // accessing the 'f' property if T is an Obj-C interface. The extra check
2054 // allows this, while still reporting an error if T is a struct pointer.
2055 const PointerType *PT = BaseType->getAsPointerType();
2056
2057 if (!PT || (getLangOptions().ObjC1 &&
2058 !PT->getPointeeType()->isRecordType()))
Douglas Gregor93b8b0f2009-05-22 21:13:27 +00002059 return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2060 BaseExpr, false,
2061 OpLoc,
2062 DeclarationName(&Member),
2063 MemberLoc));
Anders Carlsson4082ecd2009-05-16 20:31:20 +00002064 }
Chris Lattner4b009652007-07-25 00:24:17 +00002065 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002066
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002067 // Handle field access to simple records. This also handles access to fields
2068 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00002069 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002070 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002071 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002072 diag::err_typecheck_incomplete_tag,
2073 BaseExpr->getSourceRange()))
2074 return ExprError();
2075
Steve Naroff2cb66382007-07-26 03:11:44 +00002076 // The record definition is complete, now make sure the member is valid.
Mike Stumpe127ae32009-05-16 07:39:55 +00002077 // FIXME: Qualified name lookup for C++ is a bit more complicated than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00002078 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00002079 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00002080 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002081
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002082 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00002083 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
2084 << &Member << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002085 if (Result.isAmbiguous()) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002086 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
2087 MemberLoc, BaseExpr->getSourceRange());
2088 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002089 }
2090
2091 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002092
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002093 // If the decl being referenced had an error, return an error for this
2094 // sub-expr without emitting another error, in order to avoid cascading
2095 // error cases.
2096 if (MemberDecl->isInvalidDecl())
2097 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002098
Douglas Gregoraa57e862009-02-18 21:56:37 +00002099 // Check the use of this field
2100 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2101 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002102
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002103 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002104 // We may have found a field within an anonymous union or struct
2105 // (C++ [class.union]).
2106 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002107 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002108 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002109
Douglas Gregor82d44772008-12-20 23:49:58 +00002110 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2111 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002112 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00002113 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
2114 MemberType = Ref->getPointeeType();
2115 else {
2116 unsigned combinedQualifiers =
2117 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002118 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002119 combinedQualifiers &= ~QualType::Const;
2120 MemberType = MemberType.getQualifiedType(combinedQualifiers);
2121 }
Eli Friedman76b49832008-02-06 22:48:16 +00002122
Steve Naroff774e4152009-01-21 00:14:39 +00002123 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
2124 MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002125 }
2126
2127 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00002128 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002129 Var, MemberLoc,
2130 Var->getType().getNonReferenceType()));
2131 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00002132 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002133 MemberFn, MemberLoc,
2134 MemberFn->getType()));
2135 if (OverloadedFunctionDecl *Ovl
2136 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00002137 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Chris Lattner84ad8332009-03-31 08:18:48 +00002138 MemberLoc, Context.OverloadTy));
2139 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00002140 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2141 Enum, MemberLoc, Enum->getType()));
Chris Lattner84ad8332009-03-31 08:18:48 +00002142 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002143 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2144 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002145
Douglas Gregor82d44772008-12-20 23:49:58 +00002146 // We found a declaration kind that we didn't expect. This is a
2147 // generic error message that tells the user that she can't refer
2148 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002149 return ExprError(Diag(MemberLoc,
2150 diag::err_typecheck_member_reference_unknown)
2151 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002152 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002153
Chris Lattnere9d71612008-07-21 04:59:05 +00002154 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2155 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002156 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002157 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002158 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(Context,
2159 &Member,
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002160 ClassDeclared)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002161 // If the decl being referenced had an error, return an error for this
2162 // sub-expr without emitting another error, in order to avoid cascading
2163 // error cases.
2164 if (IV->isInvalidDecl())
2165 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002166
2167 // Check whether we can reference this field.
2168 if (DiagnoseUseOfDecl(IV, MemberLoc))
2169 return ExprError();
Steve Naroff8c56ee02009-03-26 16:01:08 +00002170 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2171 IV->getAccessControl() != ObjCIvarDecl::Package) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002172 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2173 if (ObjCMethodDecl *MD = getCurMethodDecl())
2174 ClassOfMethodDecl = MD->getClassInterface();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002175 else if (ObjCImpDecl && getCurFunctionDecl()) {
2176 // Case of a c-function declared inside an objc implementation.
2177 // FIXME: For a c-style function nested inside an objc implementation
Mike Stumpe127ae32009-05-16 07:39:55 +00002178 // class, there is no implementation context available, so we pass
2179 // down the context as argument to this routine. Ideally, this context
2180 // need be passed down in the AST node and somehow calculated from the
2181 // AST for a function decl.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002182 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002183 if (ObjCImplementationDecl *IMPD =
2184 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2185 ClassOfMethodDecl = IMPD->getClassInterface();
2186 else if (ObjCCategoryImplDecl* CatImplClass =
2187 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2188 ClassOfMethodDecl = CatImplClass->getClassInterface();
Steve Narofff9606572009-03-04 18:34:24 +00002189 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002190
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002191 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002192 if (ClassDeclared != IFTy->getDecl() ||
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002193 ClassOfMethodDecl != ClassDeclared)
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002194 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
2195 }
2196 // @protected
2197 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
2198 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
2199 }
Mike Stump9afab102009-02-19 03:04:26 +00002200
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00002201 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00002202 MemberLoc, BaseExpr,
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00002203 OpKind == tok::arrow));
Fariborz Jahanian09772392008-12-13 22:20:28 +00002204 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002205 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2206 << IFTy->getDecl()->getDeclName() << &Member
2207 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00002208 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002209
Chris Lattnere9d71612008-07-21 04:59:05 +00002210 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2211 // pointer to a (potentially qualified) interface type.
2212 const PointerType *PTy;
2213 const ObjCInterfaceType *IFTy;
2214 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
2215 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
2216 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00002217
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002218 // Search for a declared property first.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002219 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Context,
2220 &Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002221 // Check whether we can reference this property.
2222 if (DiagnoseUseOfDecl(PD, MemberLoc))
2223 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002224 QualType ResTy = PD->getType();
2225 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2226 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Context, Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002227 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2228 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002229 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002230 MemberLoc, BaseExpr));
2231 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002232
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002233 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00002234 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
2235 E = IFTy->qual_end(); I != E; ++I)
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002236 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context,
2237 &Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002238 // Check whether we can reference this property.
2239 if (DiagnoseUseOfDecl(PD, MemberLoc))
2240 return ExprError();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002241
Steve Naroff774e4152009-01-21 00:14:39 +00002242 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002243 MemberLoc, BaseExpr));
2244 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002245
2246 // If that failed, look for an "implicit" property by seeing if the nullary
2247 // selector is implemented.
2248
2249 // FIXME: The logic for looking up nullary and unary selectors should be
2250 // shared with the code in ActOnInstanceMessage.
2251
2252 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002253 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Context, Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002254
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002255 // If this reference is in an @implementation, check for 'private' methods.
2256 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002257 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002258
Steve Naroff04151f32008-10-22 19:16:27 +00002259 // Look through local category implementations associated with the class.
2260 if (!Getter) {
2261 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
2262 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregorcd19b572009-04-23 01:02:12 +00002263 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Context, Sel);
Steve Naroff04151f32008-10-22 19:16:27 +00002264 }
2265 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002266 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002267 // Check if we can reference this property.
2268 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2269 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002270 }
2271 // If we found a getter then this may be a valid dot-reference, we
2272 // will look for the matching setter, in case it is needed.
2273 Selector SetterSel =
2274 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2275 PP.getSelectorTable(), &Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002276 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(Context, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002277 if (!Setter) {
2278 // If this reference is in an @implementation, also check for 'private'
2279 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002280 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002281 }
2282 // Look through local category implementations associated with the class.
2283 if (!Setter) {
2284 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2285 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregorcd19b572009-04-23 01:02:12 +00002286 Setter = ObjCCategoryImpls[i]->getInstanceMethod(Context, SetterSel);
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002287 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002288 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002289
Steve Naroffdede0c92009-03-11 13:48:17 +00002290 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2291 return ExprError();
2292
2293 if (Getter || Setter) {
2294 QualType PType;
2295
2296 if (Getter)
2297 PType = Getter->getResultType();
2298 else {
2299 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2300 E = Setter->param_end(); PI != E; ++PI)
2301 PType = (*PI)->getType();
2302 }
2303 // FIXME: we must check that the setter has property type.
2304 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2305 Setter, MemberLoc, BaseExpr));
2306 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002307 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2308 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002309 }
Steve Naroffd1d44402008-10-20 22:53:06 +00002310 // Handle properties on qualified "id" protocols.
2311 const ObjCQualifiedIdType *QIdTy;
2312 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
2313 // Check protocols on qualified interfaces.
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002314 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002315 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002316 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002317 // Check the use of this declaration
2318 if (DiagnoseUseOfDecl(PD, MemberLoc))
2319 return ExprError();
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002320
Steve Naroff774e4152009-01-21 00:14:39 +00002321 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002322 MemberLoc, BaseExpr));
2323 }
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002324 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002325 // Check the use of this method.
2326 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2327 return ExprError();
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002328
Mike Stump9afab102009-02-19 03:04:26 +00002329 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002330 OMD->getResultType(),
2331 OMD, OpLoc, MemberLoc,
2332 NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00002333 }
2334 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002335
2336 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2337 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00002338 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002339 // Handle properties on ObjC 'Class' types.
2340 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
2341 // Also must look for a getter name which uses property syntax.
2342 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2343 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002344 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2345 ObjCMethodDecl *Getter;
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002346 // FIXME: need to also look locally in the implementation.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002347 if ((Getter = IFace->lookupClassMethod(Context, Sel))) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002348 // Check the use of this method.
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002349 if (DiagnoseUseOfDecl(Getter, MemberLoc))
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002350 return ExprError();
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002351 }
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002352 // If we found a getter then this may be a valid dot-reference, we
2353 // will look for the matching setter, in case it is needed.
2354 Selector SetterSel =
2355 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2356 PP.getSelectorTable(), &Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002357 ObjCMethodDecl *Setter = IFace->lookupClassMethod(Context, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002358 if (!Setter) {
2359 // If this reference is in an @implementation, also check for 'private'
2360 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002361 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002362 }
2363 // Look through local category implementations associated with the class.
2364 if (!Setter) {
2365 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2366 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregorcd19b572009-04-23 01:02:12 +00002367 Setter = ObjCCategoryImpls[i]->getClassMethod(Context, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002368 }
2369 }
2370
2371 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2372 return ExprError();
2373
2374 if (Getter || Setter) {
2375 QualType PType;
2376
2377 if (Getter)
2378 PType = Getter->getResultType();
2379 else {
2380 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2381 E = Setter->param_end(); PI != E; ++PI)
2382 PType = (*PI)->getType();
2383 }
2384 // FIXME: we must check that the setter has property type.
2385 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2386 Setter, MemberLoc, BaseExpr));
2387 }
2388 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2389 << &Member << BaseType);
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002390 }
2391 }
2392
Chris Lattnera57cf472008-07-21 04:28:12 +00002393 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002394 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00002395 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2396 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002397 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002398 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002399 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002400 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002401
Douglas Gregor762da552009-03-27 06:00:30 +00002402 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2403 << BaseType << BaseExpr->getSourceRange();
2404
2405 // If the user is trying to apply -> or . to a function or function
2406 // pointer, it's probably because they forgot parentheses to call
2407 // the function. Suggest the addition of those parentheses.
2408 if (BaseType == Context.OverloadTy ||
2409 BaseType->isFunctionType() ||
2410 (BaseType->isPointerType() &&
2411 BaseType->getAsPointerType()->isFunctionType())) {
2412 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2413 Diag(Loc, diag::note_member_reference_needs_call)
2414 << CodeModificationHint::CreateInsertion(Loc, "()");
2415 }
2416
2417 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002418}
2419
Douglas Gregor3257fb52008-12-22 05:46:06 +00002420/// ConvertArgumentsForCall - Converts the arguments specified in
2421/// Args/NumArgs to the parameter types of the function FDecl with
2422/// function prototype Proto. Call is the call expression itself, and
2423/// Fn is the function expression. For a C++ member function, this
2424/// routine does not attempt to convert the object argument. Returns
2425/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002426bool
2427Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002428 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002429 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002430 Expr **Args, unsigned NumArgs,
2431 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002432 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002433 // assignment, to the types of the corresponding parameter, ...
2434 unsigned NumArgsInProto = Proto->getNumArgs();
2435 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002436 bool Invalid = false;
2437
Douglas Gregor3257fb52008-12-22 05:46:06 +00002438 // If too few arguments are available (and we don't have default
2439 // arguments for the remaining parameters), don't make the call.
2440 if (NumArgs < NumArgsInProto) {
2441 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2442 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2443 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2444 // Use default arguments for missing arguments
2445 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002446 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002447 }
2448
2449 // If too many are passed and not variadic, error on the extras and drop
2450 // them.
2451 if (NumArgs > NumArgsInProto) {
2452 if (!Proto->isVariadic()) {
2453 Diag(Args[NumArgsInProto]->getLocStart(),
2454 diag::err_typecheck_call_too_many_args)
2455 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2456 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2457 Args[NumArgs-1]->getLocEnd());
2458 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002459 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002460 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002461 }
2462 NumArgsToCheck = NumArgsInProto;
2463 }
Mike Stump9afab102009-02-19 03:04:26 +00002464
Douglas Gregor3257fb52008-12-22 05:46:06 +00002465 // Continue to check argument types (even if we have too few/many args).
2466 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2467 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002468
Douglas Gregor3257fb52008-12-22 05:46:06 +00002469 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002470 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002471 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002472
Eli Friedman83dec9e2009-03-22 22:00:50 +00002473 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2474 ProtoArgType,
2475 diag::err_call_incomplete_argument,
2476 Arg->getSourceRange()))
2477 return true;
2478
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002479 // Pass the argument.
2480 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2481 return true;
Mike Stump9afab102009-02-19 03:04:26 +00002482 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002483 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00002484 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002485 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002486
Douglas Gregor3257fb52008-12-22 05:46:06 +00002487 Call->setArg(i, Arg);
2488 }
Mike Stump9afab102009-02-19 03:04:26 +00002489
Douglas Gregor3257fb52008-12-22 05:46:06 +00002490 // If this is a variadic call, handle args passed through "...".
2491 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002492 VariadicCallType CallType = VariadicFunction;
2493 if (Fn->getType()->isBlockPointerType())
2494 CallType = VariadicBlock; // Block
2495 else if (isa<MemberExpr>(Fn))
2496 CallType = VariadicMethod;
2497
Douglas Gregor3257fb52008-12-22 05:46:06 +00002498 // Promote the arguments (C99 6.5.2.2p7).
2499 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2500 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002501 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002502 Call->setArg(i, Arg);
2503 }
2504 }
2505
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002506 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002507}
2508
Steve Naroff87d58b42007-09-16 03:34:24 +00002509/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002510/// This provides the location of the left/right parens and a list of comma
2511/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002512Action::OwningExprResult
2513Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2514 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002515 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002516 unsigned NumArgs = args.size();
Anders Carlssonc154a722009-05-01 19:30:39 +00002517 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002518 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002519 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002520 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002521 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002522 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002523
Douglas Gregor3257fb52008-12-22 05:46:06 +00002524 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002525 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002526 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002527 // FIXME: Will need to cache the results of name lookup (including ADL) in
2528 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002529 bool Dependent = false;
2530 if (Fn->isTypeDependent())
2531 Dependent = true;
2532 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2533 Dependent = true;
2534
2535 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002536 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002537 Context.DependentTy, RParenLoc));
2538
2539 // Determine whether this is a call to an object (C++ [over.call.object]).
2540 if (Fn->getType()->isRecordType())
2541 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2542 CommaLocs, RParenLoc));
2543
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002544 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002545 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2546 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2547 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002548 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2549 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002550 }
2551
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002552 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002553 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002554 Expr *FnExpr = Fn;
2555 bool ADL = true;
2556 while (true) {
2557 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2558 FnExpr = IcExpr->getSubExpr();
2559 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002560 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002561 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002562 ADL = false;
2563 FnExpr = PExpr->getSubExpr();
2564 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002565 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002566 == UnaryOperator::AddrOf) {
2567 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002568 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2569 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2570 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2571 break;
Mike Stump9afab102009-02-19 03:04:26 +00002572 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002573 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2574 UnqualifiedName = DepName->getName();
2575 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002576 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002577 // Any kind of name that does not refer to a declaration (or
2578 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2579 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002580 break;
2581 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002582 }
Mike Stump9afab102009-02-19 03:04:26 +00002583
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002584 OverloadedFunctionDecl *Ovl = 0;
2585 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002586 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002587 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002588 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002589 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002590
Douglas Gregorfcb19192009-02-11 23:02:49 +00002591 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002592 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002593 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002594 ADL = false;
2595
Douglas Gregorfcb19192009-02-11 23:02:49 +00002596 // We don't perform ADL in C.
2597 if (!getLangOptions().CPlusPlus)
2598 ADL = false;
2599
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002600 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002601 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2602 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002603 NumArgs, CommaLocs, RParenLoc, ADL);
2604 if (!FDecl)
2605 return ExprError();
2606
2607 // Update Fn to refer to the actual function selected.
2608 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002609 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002610 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002611 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2612 QDRExpr->getLocation(),
2613 false, false,
2614 QDRExpr->getQualifierRange(),
2615 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002616 else
Mike Stump9afab102009-02-19 03:04:26 +00002617 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002618 Fn->getSourceRange().getBegin());
2619 Fn->Destroy(Context);
2620 Fn = NewFn;
2621 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002622 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002623
2624 // Promote the function operand.
2625 UsualUnaryConversions(Fn);
2626
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002627 // Make the call expr early, before semantic checks. This guarantees cleanup
2628 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002629 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2630 Args, NumArgs,
2631 Context.BoolTy,
2632 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002633
Steve Naroffd6163f32008-09-05 22:11:13 +00002634 const FunctionType *FuncT;
2635 if (!Fn->getType()->isBlockPointerType()) {
2636 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2637 // have type pointer to function".
2638 const PointerType *PT = Fn->getType()->getAsPointerType();
2639 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002640 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2641 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002642 FuncT = PT->getPointeeType()->getAsFunctionType();
2643 } else { // This is a block call.
2644 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2645 getAsFunctionType();
2646 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002647 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002648 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2649 << Fn->getType() << Fn->getSourceRange());
2650
Eli Friedman83dec9e2009-03-22 22:00:50 +00002651 // Check for a valid return type
2652 if (!FuncT->getResultType()->isVoidType() &&
2653 RequireCompleteType(Fn->getSourceRange().getBegin(),
2654 FuncT->getResultType(),
2655 diag::err_call_incomplete_return,
2656 TheCall->getSourceRange()))
2657 return ExprError();
2658
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002659 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002660 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002661
Douglas Gregor4fa58902009-02-26 23:50:07 +00002662 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002663 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002664 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002665 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002666 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002667 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002668
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002669 if (FDecl) {
2670 // Check if we have too few/too many template arguments, based
2671 // on our knowledge of the function definition.
2672 const FunctionDecl *Def = 0;
Eli Friedmanf7ed7812009-06-01 09:24:59 +00002673 if (FDecl->getBody(Context, Def) && NumArgs != Def->param_size()) {
2674 const FunctionProtoType *Proto =
2675 Def->getType()->getAsFunctionProtoType();
2676 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2677 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2678 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2679 }
2680 }
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002681 }
2682
Steve Naroffdb65e052007-08-28 23:30:39 +00002683 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002684 for (unsigned i = 0; i != NumArgs; i++) {
2685 Expr *Arg = Args[i];
2686 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002687 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2688 Arg->getType(),
2689 diag::err_call_incomplete_argument,
2690 Arg->getSourceRange()))
2691 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002692 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002693 }
Chris Lattner4b009652007-07-25 00:24:17 +00002694 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002695
Douglas Gregor3257fb52008-12-22 05:46:06 +00002696 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2697 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002698 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2699 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002700
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002701 // Check for sentinels
2702 if (NDecl)
2703 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Chris Lattner2e64c072007-08-10 20:18:51 +00002704 // Do special checking on direct calls to functions.
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002705 if (FDecl)
Eli Friedmand0e9d092008-05-14 19:38:39 +00002706 return CheckFunctionCall(FDecl, TheCall.take());
Fariborz Jahanianf83c85f2009-05-18 21:05:18 +00002707 if (NDecl)
2708 return CheckBlockCall(NDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002709
Sebastian Redl8b769972009-01-19 00:08:26 +00002710 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002711}
2712
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002713Action::OwningExprResult
2714Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2715 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002716 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002717 QualType literalType = QualType::getFromOpaquePtr(Ty);
2718 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002719 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002720 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002721
Eli Friedman8c2173d2008-05-20 05:22:08 +00002722 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002723 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002724 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2725 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregored71c542009-05-21 23:48:18 +00002726 } else if (!literalType->isDependentType() &&
2727 RequireCompleteType(LParenLoc, literalType,
2728 diag::err_typecheck_decl_incomplete_type,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002729 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002730 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002731
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002732 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002733 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002734 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002735
Chris Lattnere5cb5862008-12-04 23:50:19 +00002736 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002737 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002738 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002739 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002740 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002741 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002742 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002743 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002744}
2745
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002746Action::OwningExprResult
2747Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002748 SourceLocation RBraceLoc) {
2749 unsigned NumInit = initlist.size();
2750 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002751
Steve Naroff0acc9c92007-09-15 18:49:24 +00002752 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002753 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002754
Mike Stump9afab102009-02-19 03:04:26 +00002755 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002756 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002757 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002758 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002759}
2760
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002761/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002762bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002763 UsualUnaryConversions(castExpr);
2764
2765 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2766 // type needs to be scalar.
2767 if (castType->isVoidType()) {
2768 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002769 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2770 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002771 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002772 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2773 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2774 (castType->isStructureType() || castType->isUnionType())) {
2775 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002776 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002777 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2778 << castType << castExpr->getSourceRange();
2779 } else if (castType->isUnionType()) {
2780 // GCC cast to union extension
2781 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2782 RecordDecl::field_iterator Field, FieldEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002783 for (Field = RD->field_begin(Context), FieldEnd = RD->field_end(Context);
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002784 Field != FieldEnd; ++Field) {
2785 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2786 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2787 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2788 << castExpr->getSourceRange();
2789 break;
2790 }
2791 }
2792 if (Field == FieldEnd)
2793 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2794 << castExpr->getType() << castExpr->getSourceRange();
2795 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002796 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002797 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002798 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002799 }
Mike Stump9afab102009-02-19 03:04:26 +00002800 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002801 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002802 return Diag(castExpr->getLocStart(),
2803 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002804 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002805 } else if (castExpr->getType()->isVectorType()) {
2806 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2807 return true;
2808 } else if (castType->isVectorType()) {
2809 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2810 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002811 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00002812 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00002813 } else if (!castType->isArithmeticType()) {
2814 QualType castExprType = castExpr->getType();
2815 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2816 return Diag(castExpr->getLocStart(),
2817 diag::err_cast_pointer_from_non_pointer_int)
2818 << castExprType << castExpr->getSourceRange();
2819 } else if (!castExpr->getType()->isArithmeticType()) {
2820 if (!castType->isIntegralType() && castType->isArithmeticType())
2821 return Diag(castExpr->getLocStart(),
2822 diag::err_cast_pointer_to_non_pointer_int)
2823 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002824 }
Fariborz Jahanian4862e872009-05-22 21:42:52 +00002825 if (isa<ObjCSelectorExpr>(castExpr))
2826 return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002827 return false;
2828}
2829
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002830bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002831 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002832
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002833 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002834 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002835 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002836 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002837 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002838 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002839 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002840 } else
2841 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002842 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002843 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002844
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002845 return false;
2846}
2847
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002848Action::OwningExprResult
2849Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2850 SourceLocation RParenLoc, ExprArg Op) {
2851 assert((Ty != 0) && (Op.get() != 0) &&
2852 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002853
Anders Carlssonc154a722009-05-01 19:30:39 +00002854 Expr *castExpr = Op.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00002855 QualType castType = QualType::getFromOpaquePtr(Ty);
2856
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002857 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002858 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002859 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002860 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002861}
2862
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00002863/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2864/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002865/// C99 6.5.15
2866QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2867 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002868 // C++ is sufficiently different to merit its own checker.
2869 if (getLangOptions().CPlusPlus)
2870 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
2871
Chris Lattnere2897262009-02-18 04:28:32 +00002872 UsualUnaryConversions(Cond);
2873 UsualUnaryConversions(LHS);
2874 UsualUnaryConversions(RHS);
2875 QualType CondTy = Cond->getType();
2876 QualType LHSTy = LHS->getType();
2877 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002878
2879 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00002880 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2881 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2882 << CondTy;
2883 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002884 }
Mike Stump9afab102009-02-19 03:04:26 +00002885
Chris Lattner992ae932008-01-06 22:42:25 +00002886 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002887
Chris Lattner992ae932008-01-06 22:42:25 +00002888 // If both operands have arithmetic type, do the usual arithmetic conversions
2889 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002890 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2891 UsualArithmeticConversions(LHS, RHS);
2892 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002893 }
Mike Stump9afab102009-02-19 03:04:26 +00002894
Chris Lattner992ae932008-01-06 22:42:25 +00002895 // If both operands are the same structure or union type, the result is that
2896 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002897 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2898 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002899 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002900 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002901 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002902 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00002903 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00002904 }
Mike Stump9afab102009-02-19 03:04:26 +00002905
Chris Lattner992ae932008-01-06 22:42:25 +00002906 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002907 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002908 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2909 if (!LHSTy->isVoidType())
2910 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2911 << RHS->getSourceRange();
2912 if (!RHSTy->isVoidType())
2913 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2914 << LHS->getSourceRange();
2915 ImpCastExprToType(LHS, Context.VoidTy);
2916 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002917 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002918 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002919 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2920 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002921 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2922 Context.isObjCObjectPointerType(LHSTy)) &&
2923 RHS->isNullPointerConstant(Context)) {
2924 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2925 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002926 }
Chris Lattnere2897262009-02-18 04:28:32 +00002927 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2928 Context.isObjCObjectPointerType(RHSTy)) &&
2929 LHS->isNullPointerConstant(Context)) {
2930 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2931 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002932 }
Mike Stump9afab102009-02-19 03:04:26 +00002933
Mike Stumpe97a8542009-05-07 03:14:14 +00002934 const PointerType *LHSPT = LHSTy->getAsPointerType();
2935 const PointerType *RHSPT = RHSTy->getAsPointerType();
2936 const BlockPointerType *LHSBPT = LHSTy->getAsBlockPointerType();
2937 const BlockPointerType *RHSBPT = RHSTy->getAsBlockPointerType();
2938
Chris Lattner0ac51632008-01-06 22:50:31 +00002939 // Handle the case where both operands are pointers before we handle null
2940 // pointer constants in case both operands are null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00002941 if ((LHSPT || LHSBPT) && (RHSPT || RHSBPT)) { // C99 6.5.15p3,6
2942 // get the "pointed to" types
Mike Stumpea3d74e2009-05-07 18:43:07 +00002943 QualType lhptee = (LHSPT ? LHSPT->getPointeeType()
2944 : LHSBPT->getPointeeType());
2945 QualType rhptee = (RHSPT ? RHSPT->getPointeeType()
2946 : RHSBPT->getPointeeType());
Chris Lattner4b009652007-07-25 00:24:17 +00002947
Mike Stumpe97a8542009-05-07 03:14:14 +00002948 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2949 if (lhptee->isVoidType()
2950 && (RHSBPT || rhptee->isIncompleteOrObjectType())) {
2951 // Figure out necessary qualifiers (C99 6.5.15p6)
2952 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
2953 QualType destType = Context.getPointerType(destPointee);
2954 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2955 ImpCastExprToType(RHS, destType); // promote to void*
2956 return destType;
2957 }
2958 if (rhptee->isVoidType()
2959 && (LHSBPT || lhptee->isIncompleteOrObjectType())) {
2960 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
2961 QualType destType = Context.getPointerType(destPointee);
2962 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2963 ImpCastExprToType(RHS, destType); // promote to void*
2964 return destType;
2965 }
Chris Lattner4b009652007-07-25 00:24:17 +00002966
Mike Stumpe97a8542009-05-07 03:14:14 +00002967 bool sameKind = (LHSPT && RHSPT) || (LHSBPT && RHSBPT);
2968 if (sameKind
2969 && Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
2970 // Two identical pointer types are always compatible.
2971 return LHSTy;
2972 }
Mike Stump9afab102009-02-19 03:04:26 +00002973
Mike Stumpe97a8542009-05-07 03:14:14 +00002974 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002975
Mike Stumpe97a8542009-05-07 03:14:14 +00002976 // If either type is an Objective-C object type then check
2977 // compatibility according to Objective-C.
2978 if (Context.isObjCObjectPointerType(LHSTy) ||
2979 Context.isObjCObjectPointerType(RHSTy)) {
2980 // If both operands are interfaces and either operand can be
2981 // assigned to the other, use that type as the composite
2982 // type. This allows
2983 // xxx ? (A*) a : (B*) b
2984 // where B is a subclass of A.
2985 //
2986 // Additionally, as for assignment, if either type is 'id'
2987 // allow silent coercion. Finally, if the types are
2988 // incompatible then make sure to use 'id' as the composite
2989 // type so the result is acceptable for sending messages to.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002990
Mike Stumpe97a8542009-05-07 03:14:14 +00002991 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2992 // It could return the composite type.
2993 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2994 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2995 if (LHSIface && RHSIface &&
2996 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2997 compositeType = LHSTy;
2998 } else if (LHSIface && RHSIface &&
2999 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
3000 compositeType = RHSTy;
3001 } else if (Context.isObjCIdStructType(lhptee) ||
3002 Context.isObjCIdStructType(rhptee)) {
3003 compositeType = Context.getObjCIdType();
3004 } else if (LHSBPT || RHSBPT) {
3005 if (!sameKind
3006 || !Context.typesAreBlockCompatible(lhptee.getUnqualifiedType(),
3007 rhptee.getUnqualifiedType()))
3008 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3009 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3010 return QualType();
3011 } else {
3012 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3013 << LHSTy << RHSTy
3014 << LHS->getSourceRange() << RHS->getSourceRange();
3015 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00003016 ImpCastExprToType(LHS, incompatTy);
3017 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00003018 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00003019 }
Mike Stumpe97a8542009-05-07 03:14:14 +00003020 } else if (!sameKind
3021 || !Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3022 rhptee.getUnqualifiedType())) {
3023 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3024 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3025 // In this situation, we assume void* type. No especially good
3026 // reason, but this is what gcc does, and we do have to pick
3027 // to get a consistent AST.
3028 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3029 ImpCastExprToType(LHS, incompatTy);
3030 ImpCastExprToType(RHS, incompatTy);
3031 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003032 }
Mike Stumpe97a8542009-05-07 03:14:14 +00003033 // The pointer types are compatible.
3034 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3035 // differently qualified versions of compatible types, the result type is
3036 // a pointer to an appropriately qualified version of the *composite*
3037 // type.
3038 // FIXME: Need to calculate the composite type.
3039 // FIXME: Need to add qualifiers
3040 ImpCastExprToType(LHS, compositeType);
3041 ImpCastExprToType(RHS, compositeType);
3042 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00003043 }
Mike Stump9afab102009-02-19 03:04:26 +00003044
Steve Naroff6ba22682009-04-08 17:05:15 +00003045 // GCC compatibility: soften pointer/integer mismatch.
3046 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3047 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3048 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3049 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3050 return RHSTy;
3051 }
3052 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3053 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3054 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3055 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3056 return LHSTy;
3057 }
3058
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003059 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
3060 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00003061 // id with statically typed objects).
3062 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003063 // GCC allows qualified id and any Objective-C type to devolve to
3064 // id. Currently localizing to here until clear this should be
3065 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003066 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00003067 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00003068 Context.isObjCObjectPointerType(RHSTy)) ||
3069 (RHSTy->isObjCQualifiedIdType() &&
3070 Context.isObjCObjectPointerType(LHSTy))) {
Mike Stumpe127ae32009-05-16 07:39:55 +00003071 // FIXME: This is not the correct composite type. This only happens to
3072 // work because id can more or less be used anywhere, however this may
3073 // change the type of method sends.
3074
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003075 // FIXME: gcc adds some type-checking of the arguments and emits
3076 // (confusing) incompatible comparison warnings in some
3077 // cases. Investigate.
3078 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00003079 ImpCastExprToType(LHS, compositeType);
3080 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003081 return compositeType;
3082 }
3083 }
3084
Chris Lattner992ae932008-01-06 22:42:25 +00003085 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003086 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3087 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003088 return QualType();
3089}
3090
Steve Naroff87d58b42007-09-16 03:34:24 +00003091/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003092/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003093Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3094 SourceLocation ColonLoc,
3095 ExprArg Cond, ExprArg LHS,
3096 ExprArg RHS) {
3097 Expr *CondExpr = (Expr *) Cond.get();
3098 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003099
3100 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3101 // was the condition.
3102 bool isLHSNull = LHSExpr == 0;
3103 if (isLHSNull)
3104 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003105
3106 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003107 RHSExpr, QuestionLoc);
3108 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003109 return ExprError();
3110
3111 Cond.release();
3112 LHS.release();
3113 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00003114 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00003115 isLHSNull ? 0 : LHSExpr,
3116 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003117}
3118
Chris Lattner4b009652007-07-25 00:24:17 +00003119
3120// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003121// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003122// routine is it effectively iqnores the qualifiers on the top level pointee.
3123// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3124// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003125Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003126Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3127 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003128
Chris Lattner4b009652007-07-25 00:24:17 +00003129 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00003130 lhptee = lhsType->getAsPointerType()->getPointeeType();
3131 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003132
Chris Lattner4b009652007-07-25 00:24:17 +00003133 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003134 lhptee = Context.getCanonicalType(lhptee);
3135 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003136
Chris Lattner005ed752008-01-04 18:04:52 +00003137 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003138
3139 // C99 6.5.16.1p1: This following citation is common to constraints
3140 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3141 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003142 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003143 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003144 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003145
Mike Stump9afab102009-02-19 03:04:26 +00003146 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3147 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003148 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003149 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003150 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003151 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003152
Chris Lattner4ca3d772008-01-03 22:56:36 +00003153 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003154 assert(rhptee->isFunctionType());
3155 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003156 }
Mike Stump9afab102009-02-19 03:04:26 +00003157
Chris Lattner4ca3d772008-01-03 22:56:36 +00003158 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003159 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003160 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003161
3162 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003163 assert(lhptee->isFunctionType());
3164 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003165 }
Mike Stump9afab102009-02-19 03:04:26 +00003166 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003167 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003168 lhptee = lhptee.getUnqualifiedType();
3169 rhptee = rhptee.getUnqualifiedType();
3170 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3171 // Check if the pointee types are compatible ignoring the sign.
3172 // We explicitly check for char so that we catch "char" vs
3173 // "unsigned char" on systems where "char" is unsigned.
3174 if (lhptee->isCharType()) {
3175 lhptee = Context.UnsignedCharTy;
3176 } else if (lhptee->isSignedIntegerType()) {
3177 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3178 }
3179 if (rhptee->isCharType()) {
3180 rhptee = Context.UnsignedCharTy;
3181 } else if (rhptee->isSignedIntegerType()) {
3182 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3183 }
3184 if (lhptee == rhptee) {
3185 // Types are compatible ignoring the sign. Qualifier incompatibility
3186 // takes priority over sign incompatibility because the sign
3187 // warning can be disabled.
3188 if (ConvTy != Compatible)
3189 return ConvTy;
3190 return IncompatiblePointerSign;
3191 }
3192 // General pointer incompatibility takes priority over qualifiers.
3193 return IncompatiblePointer;
3194 }
Chris Lattner005ed752008-01-04 18:04:52 +00003195 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003196}
3197
Steve Naroff3454b6c2008-09-04 15:10:53 +00003198/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3199/// block pointer types are compatible or whether a block and normal pointer
3200/// are compatible. It is more restrict than comparing two function pointer
3201// types.
Mike Stump9afab102009-02-19 03:04:26 +00003202Sema::AssignConvertType
3203Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003204 QualType rhsType) {
3205 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003206
Steve Naroff3454b6c2008-09-04 15:10:53 +00003207 // get the "pointed to" type (ignoring qualifiers at the top level)
3208 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003209 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
3210
Steve Naroff3454b6c2008-09-04 15:10:53 +00003211 // make sure we operate on the canonical type
3212 lhptee = Context.getCanonicalType(lhptee);
3213 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003214
Steve Naroff3454b6c2008-09-04 15:10:53 +00003215 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003216
Steve Naroff3454b6c2008-09-04 15:10:53 +00003217 // For blocks we enforce that qualifiers are identical.
3218 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3219 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003220
Steve Naroff3454b6c2008-09-04 15:10:53 +00003221 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003222 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003223 return ConvTy;
3224}
3225
Mike Stump9afab102009-02-19 03:04:26 +00003226/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3227/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003228/// pointers. Here are some objectionable examples that GCC considers warnings:
3229///
3230/// int a, *pint;
3231/// short *pshort;
3232/// struct foo *pfoo;
3233///
3234/// pint = pshort; // warning: assignment from incompatible pointer type
3235/// a = pint; // warning: assignment makes integer from pointer without a cast
3236/// pint = a; // warning: assignment makes pointer from integer without a cast
3237/// pint = pfoo; // warning: assignment from incompatible pointer type
3238///
3239/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003240/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003241///
Chris Lattner005ed752008-01-04 18:04:52 +00003242Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003243Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003244 // Get canonical types. We're not formatting these types, just comparing
3245 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003246 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3247 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003248
3249 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003250 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003251
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003252 // If the left-hand side is a reference type, then we are in a
3253 // (rare!) case where we've allowed the use of references in C,
3254 // e.g., as a parameter type in a built-in function. In this case,
3255 // just make sure that the type referenced is compatible with the
3256 // right-hand side type. The caller is responsible for adjusting
3257 // lhsType so that the resulting expression does not have reference
3258 // type.
3259 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
3260 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003261 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003262 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003263 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003264
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003265 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
3266 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003267 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00003268 // Relax integer conversions like we do for pointers below.
3269 if (rhsType->isIntegerType())
3270 return IntToPointer;
3271 if (lhsType->isIntegerType())
3272 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00003273 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003274 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003275
Nate Begemanc5f0f652008-07-14 18:02:46 +00003276 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00003277 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00003278 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
3279 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003280 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003281
Nate Begemanc5f0f652008-07-14 18:02:46 +00003282 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003283 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003284 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003285 if (getLangOptions().LaxVectorConversions &&
3286 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003287 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003288 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003289 }
3290 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003291 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003292
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003293 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003294 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003295
Chris Lattner390564e2008-04-07 06:49:41 +00003296 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003297 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003298 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003299
Chris Lattner390564e2008-04-07 06:49:41 +00003300 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003301 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003302
Steve Naroffa982c712008-09-29 18:10:17 +00003303 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00003304 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003305 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003306
3307 // Treat block pointers as objects.
3308 if (getLangOptions().ObjC1 &&
3309 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
3310 return Compatible;
3311 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003312 return Incompatible;
3313 }
3314
3315 if (isa<BlockPointerType>(lhsType)) {
3316 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003317 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003318
Steve Naroffa982c712008-09-29 18:10:17 +00003319 // Treat block pointers as objects.
3320 if (getLangOptions().ObjC1 &&
3321 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
3322 return Compatible;
3323
Steve Naroff3454b6c2008-09-04 15:10:53 +00003324 if (rhsType->isBlockPointerType())
3325 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003326
Steve Naroff3454b6c2008-09-04 15:10:53 +00003327 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
3328 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003329 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003330 }
Chris Lattner1853da22008-01-04 23:18:45 +00003331 return Incompatible;
3332 }
3333
Chris Lattner390564e2008-04-07 06:49:41 +00003334 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003335 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003336 if (lhsType == Context.BoolTy)
3337 return Compatible;
3338
3339 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003340 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003341
Mike Stump9afab102009-02-19 03:04:26 +00003342 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003343 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003344
3345 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00003346 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003347 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003348 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003349 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003350
Chris Lattner1853da22008-01-04 23:18:45 +00003351 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003352 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003353 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003354 }
3355 return Incompatible;
3356}
3357
Douglas Gregor144b06c2009-04-29 22:16:16 +00003358/// \brief Constructs a transparent union from an expression that is
3359/// used to initialize the transparent union.
3360static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3361 QualType UnionType, FieldDecl *Field) {
3362 // Build an initializer list that designates the appropriate member
3363 // of the transparent union.
3364 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3365 &E, 1,
3366 SourceLocation());
3367 Initializer->setType(UnionType);
3368 Initializer->setInitializedFieldInUnion(Field);
3369
3370 // Build a compound literal constructing a value of the transparent
3371 // union type from this initializer list.
3372 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3373 false);
3374}
3375
3376Sema::AssignConvertType
3377Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3378 QualType FromType = rExpr->getType();
3379
3380 // If the ArgType is a Union type, we want to handle a potential
3381 // transparent_union GCC extension.
3382 const RecordType *UT = ArgType->getAsUnionType();
3383 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
3384 return Incompatible;
3385
3386 // The field to initialize within the transparent union.
3387 RecordDecl *UD = UT->getDecl();
3388 FieldDecl *InitField = 0;
3389 // It's compatible if the expression matches any of the fields.
3390 for (RecordDecl::field_iterator it = UD->field_begin(Context),
3391 itend = UD->field_end(Context);
3392 it != itend; ++it) {
3393 if (it->getType()->isPointerType()) {
3394 // If the transparent union contains a pointer type, we allow:
3395 // 1) void pointer
3396 // 2) null pointer constant
3397 if (FromType->isPointerType())
3398 if (FromType->getAsPointerType()->getPointeeType()->isVoidType()) {
3399 ImpCastExprToType(rExpr, it->getType());
3400 InitField = *it;
3401 break;
3402 }
3403
3404 if (rExpr->isNullPointerConstant(Context)) {
3405 ImpCastExprToType(rExpr, it->getType());
3406 InitField = *it;
3407 break;
3408 }
3409 }
3410
3411 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3412 == Compatible) {
3413 InitField = *it;
3414 break;
3415 }
3416 }
3417
3418 if (!InitField)
3419 return Incompatible;
3420
3421 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3422 return Compatible;
3423}
3424
Chris Lattner005ed752008-01-04 18:04:52 +00003425Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003426Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003427 if (getLangOptions().CPlusPlus) {
3428 if (!lhsType->isRecordType()) {
3429 // C++ 5.17p3: If the left operand is not of class type, the
3430 // expression is implicitly converted (C++ 4) to the
3431 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003432 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3433 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003434 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003435 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003436 }
3437
3438 // FIXME: Currently, we fall through and treat C++ classes like C
3439 // structures.
3440 }
3441
Steve Naroffcdee22d2007-11-27 17:58:44 +00003442 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3443 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003444 if ((lhsType->isPointerType() ||
3445 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003446 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003447 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003448 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003449 return Compatible;
3450 }
Mike Stump9afab102009-02-19 03:04:26 +00003451
Chris Lattner5f505bf2007-10-16 02:55:40 +00003452 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003453 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003454 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003455 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003456 //
Mike Stump9afab102009-02-19 03:04:26 +00003457 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003458 if (!lhsType->isReferenceType())
3459 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003460
Chris Lattner005ed752008-01-04 18:04:52 +00003461 Sema::AssignConvertType result =
3462 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003463
Steve Naroff0f32f432007-08-24 22:33:52 +00003464 // C99 6.5.16.1p2: The value of the right operand is converted to the
3465 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003466 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3467 // so that we can use references in built-in functions even in C.
3468 // The getNonReferenceType() call makes sure that the resulting expression
3469 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003470 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003471 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003472 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003473}
3474
Chris Lattner1eafdea2008-11-18 01:30:42 +00003475QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003476 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003477 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003478 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003479 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003480}
3481
Mike Stump9afab102009-02-19 03:04:26 +00003482inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003483 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003484 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003485 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003486 QualType lhsType =
3487 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3488 QualType rhsType =
3489 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003490
Nate Begemanc5f0f652008-07-14 18:02:46 +00003491 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003492 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003493 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003494
Nate Begemanc5f0f652008-07-14 18:02:46 +00003495 // Handle the case of a vector & extvector type of the same size and element
3496 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003497 if (getLangOptions().LaxVectorConversions) {
3498 // FIXME: Should we warn here?
3499 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003500 if (const VectorType *RV = rhsType->getAsVectorType())
3501 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003502 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003503 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003504 }
3505 }
3506 }
Mike Stump9afab102009-02-19 03:04:26 +00003507
Nate Begemanc5f0f652008-07-14 18:02:46 +00003508 // If the lhs is an extended vector and the rhs is a scalar of the same type
3509 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003510 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003511 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00003512
3513 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003514 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
3515 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003516 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003517 return lhsType;
3518 }
3519 }
3520
Nate Begemanc5f0f652008-07-14 18:02:46 +00003521 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00003522 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003523 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003524 QualType eltType = V->getElementType();
3525
Mike Stump9afab102009-02-19 03:04:26 +00003526 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003527 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
3528 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003529 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003530 return rhsType;
3531 }
3532 }
3533
Chris Lattner4b009652007-07-25 00:24:17 +00003534 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00003535 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003536 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003537 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003538 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003539}
3540
Chris Lattner4b009652007-07-25 00:24:17 +00003541inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003542 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003543{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003544 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003545 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003546
Steve Naroff8f708362007-08-24 19:07:16 +00003547 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003548
Chris Lattner4b009652007-07-25 00:24:17 +00003549 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003550 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003551 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003552}
3553
3554inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003555 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003556{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003557 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3558 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3559 return CheckVectorOperands(Loc, lex, rex);
3560 return InvalidOperands(Loc, lex, rex);
3561 }
Chris Lattner4b009652007-07-25 00:24:17 +00003562
Steve Naroff8f708362007-08-24 19:07:16 +00003563 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003564
Chris Lattner4b009652007-07-25 00:24:17 +00003565 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003566 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003567 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003568}
3569
3570inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003571 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003572{
Eli Friedman3cd92882009-03-28 01:22:36 +00003573 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3574 QualType compType = CheckVectorOperands(Loc, lex, rex);
3575 if (CompLHSTy) *CompLHSTy = compType;
3576 return compType;
3577 }
Chris Lattner4b009652007-07-25 00:24:17 +00003578
Eli Friedman3cd92882009-03-28 01:22:36 +00003579 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003580
Chris Lattner4b009652007-07-25 00:24:17 +00003581 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003582 if (lex->getType()->isArithmeticType() &&
3583 rex->getType()->isArithmeticType()) {
3584 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003585 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003586 }
Chris Lattner4b009652007-07-25 00:24:17 +00003587
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003588 // Put any potential pointer into PExp
3589 Expr* PExp = lex, *IExp = rex;
3590 if (IExp->getType()->isPointerType())
3591 std::swap(PExp, IExp);
3592
Chris Lattner184f92d2009-04-24 23:50:08 +00003593 if (const PointerType *PTy = PExp->getType()->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003594 if (IExp->getType()->isIntegerType()) {
Chris Lattner184f92d2009-04-24 23:50:08 +00003595 QualType PointeeTy = PTy->getPointeeType();
3596 // Check for arithmetic on pointers to incomplete types.
3597 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003598 if (getLangOptions().CPlusPlus) {
3599 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003600 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003601 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003602 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003603
3604 // GNU extension: arithmetic on pointer to void
3605 Diag(Loc, diag::ext_gnu_void_ptr)
3606 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00003607 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003608 if (getLangOptions().CPlusPlus) {
3609 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3610 << lex->getType() << lex->getSourceRange();
3611 return QualType();
3612 }
3613
3614 // GNU extension: arithmetic on pointer to function
3615 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3616 << lex->getType() << lex->getSourceRange();
3617 } else if (!PTy->isDependentType() &&
Chris Lattner184f92d2009-04-24 23:50:08 +00003618 RequireCompleteType(Loc, PointeeTy,
Douglas Gregor05e28f62009-03-24 19:52:54 +00003619 diag::err_typecheck_arithmetic_incomplete_type,
Chris Lattner184f92d2009-04-24 23:50:08 +00003620 PExp->getSourceRange(), SourceRange(),
3621 PExp->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00003622 return QualType();
3623
Chris Lattner184f92d2009-04-24 23:50:08 +00003624 // Diagnose bad cases where we step over interface counts.
3625 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3626 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3627 << PointeeTy << PExp->getSourceRange();
3628 return QualType();
3629 }
3630
Eli Friedman3cd92882009-03-28 01:22:36 +00003631 if (CompLHSTy) {
3632 QualType LHSTy = lex->getType();
3633 if (LHSTy->isPromotableIntegerType())
3634 LHSTy = Context.IntTy;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00003635 else {
3636 QualType T = isPromotableBitField(lex, Context);
3637 if (!T.isNull())
3638 LHSTy = T;
3639 }
3640
Eli Friedman3cd92882009-03-28 01:22:36 +00003641 *CompLHSTy = LHSTy;
3642 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003643 return PExp->getType();
3644 }
3645 }
3646
Chris Lattner1eafdea2008-11-18 01:30:42 +00003647 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003648}
3649
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003650// C99 6.5.6
3651QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00003652 SourceLocation Loc, QualType* CompLHSTy) {
3653 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3654 QualType compType = CheckVectorOperands(Loc, lex, rex);
3655 if (CompLHSTy) *CompLHSTy = compType;
3656 return compType;
3657 }
Mike Stump9afab102009-02-19 03:04:26 +00003658
Eli Friedman3cd92882009-03-28 01:22:36 +00003659 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00003660
Chris Lattnerf6da2912007-12-09 21:53:25 +00003661 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00003662
Chris Lattnerf6da2912007-12-09 21:53:25 +00003663 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00003664 if (lex->getType()->isArithmeticType()
3665 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00003666 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003667 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003668 }
Mike Stump9afab102009-02-19 03:04:26 +00003669
Chris Lattnerf6da2912007-12-09 21:53:25 +00003670 // Either ptr - int or ptr - ptr.
3671 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00003672 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003673
Douglas Gregor05e28f62009-03-24 19:52:54 +00003674 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00003675
Douglas Gregor05e28f62009-03-24 19:52:54 +00003676 bool ComplainAboutVoid = false;
3677 Expr *ComplainAboutFunc = 0;
3678 if (lpointee->isVoidType()) {
3679 if (getLangOptions().CPlusPlus) {
3680 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3681 << lex->getSourceRange() << rex->getSourceRange();
3682 return QualType();
3683 }
3684
3685 // GNU C extension: arithmetic on pointer to void
3686 ComplainAboutVoid = true;
3687 } else if (lpointee->isFunctionType()) {
3688 if (getLangOptions().CPlusPlus) {
3689 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003690 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003691 return QualType();
3692 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003693
3694 // GNU C extension: arithmetic on pointer to function
3695 ComplainAboutFunc = lex;
3696 } else if (!lpointee->isDependentType() &&
3697 RequireCompleteType(Loc, lpointee,
3698 diag::err_typecheck_sub_ptr_object,
3699 lex->getSourceRange(),
3700 SourceRange(),
3701 lex->getType()))
3702 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003703
Chris Lattner184f92d2009-04-24 23:50:08 +00003704 // Diagnose bad cases where we step over interface counts.
3705 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3706 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3707 << lpointee << lex->getSourceRange();
3708 return QualType();
3709 }
3710
Chris Lattnerf6da2912007-12-09 21:53:25 +00003711 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00003712 if (rex->getType()->isIntegerType()) {
3713 if (ComplainAboutVoid)
3714 Diag(Loc, diag::ext_gnu_void_ptr)
3715 << lex->getSourceRange() << rex->getSourceRange();
3716 if (ComplainAboutFunc)
3717 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3718 << ComplainAboutFunc->getType()
3719 << ComplainAboutFunc->getSourceRange();
3720
Eli Friedman3cd92882009-03-28 01:22:36 +00003721 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003722 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00003723 }
Mike Stump9afab102009-02-19 03:04:26 +00003724
Chris Lattnerf6da2912007-12-09 21:53:25 +00003725 // Handle pointer-pointer subtractions.
3726 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003727 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003728
Douglas Gregor05e28f62009-03-24 19:52:54 +00003729 // RHS must be a completely-type object type.
3730 // Handle the GNU void* extension.
3731 if (rpointee->isVoidType()) {
3732 if (getLangOptions().CPlusPlus) {
3733 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3734 << lex->getSourceRange() << rex->getSourceRange();
3735 return QualType();
3736 }
Mike Stump9afab102009-02-19 03:04:26 +00003737
Douglas Gregor05e28f62009-03-24 19:52:54 +00003738 ComplainAboutVoid = true;
3739 } else if (rpointee->isFunctionType()) {
3740 if (getLangOptions().CPlusPlus) {
3741 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003742 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003743 return QualType();
3744 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003745
3746 // GNU extension: arithmetic on pointer to function
3747 if (!ComplainAboutFunc)
3748 ComplainAboutFunc = rex;
3749 } else if (!rpointee->isDependentType() &&
3750 RequireCompleteType(Loc, rpointee,
3751 diag::err_typecheck_sub_ptr_object,
3752 rex->getSourceRange(),
3753 SourceRange(),
3754 rex->getType()))
3755 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003756
Eli Friedman143ddc92009-05-16 13:54:38 +00003757 if (getLangOptions().CPlusPlus) {
3758 // Pointee types must be the same: C++ [expr.add]
3759 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
3760 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
3761 << lex->getType() << rex->getType()
3762 << lex->getSourceRange() << rex->getSourceRange();
3763 return QualType();
3764 }
3765 } else {
3766 // Pointee types must be compatible C99 6.5.6p3
3767 if (!Context.typesAreCompatible(
3768 Context.getCanonicalType(lpointee).getUnqualifiedType(),
3769 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
3770 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
3771 << lex->getType() << rex->getType()
3772 << lex->getSourceRange() << rex->getSourceRange();
3773 return QualType();
3774 }
Chris Lattnerf6da2912007-12-09 21:53:25 +00003775 }
Mike Stump9afab102009-02-19 03:04:26 +00003776
Douglas Gregor05e28f62009-03-24 19:52:54 +00003777 if (ComplainAboutVoid)
3778 Diag(Loc, diag::ext_gnu_void_ptr)
3779 << lex->getSourceRange() << rex->getSourceRange();
3780 if (ComplainAboutFunc)
3781 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3782 << ComplainAboutFunc->getType()
3783 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00003784
3785 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003786 return Context.getPointerDiffType();
3787 }
3788 }
Mike Stump9afab102009-02-19 03:04:26 +00003789
Chris Lattner1eafdea2008-11-18 01:30:42 +00003790 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003791}
3792
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003793// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003794QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003795 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003796 // C99 6.5.7p2: Each of the operands shall have integer type.
3797 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003798 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003799
Chris Lattner2c8bff72007-12-12 05:47:28 +00003800 // Shifts don't perform usual arithmetic conversions, they just do integer
3801 // promotions on each operand. C99 6.5.7p3
Eli Friedman3cd92882009-03-28 01:22:36 +00003802 QualType LHSTy;
3803 if (lex->getType()->isPromotableIntegerType())
3804 LHSTy = Context.IntTy;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00003805 else {
3806 LHSTy = isPromotableBitField(lex, Context);
3807 if (LHSTy.isNull())
3808 LHSTy = lex->getType();
3809 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003810 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00003811 ImpCastExprToType(lex, LHSTy);
3812
Chris Lattner2c8bff72007-12-12 05:47:28 +00003813 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003814
Chris Lattner2c8bff72007-12-12 05:47:28 +00003815 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00003816 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003817}
3818
Douglas Gregor30eed0f2009-05-04 06:07:12 +00003819// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003820QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00003821 unsigned OpaqueOpc, bool isRelational) {
3822 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
3823
Nate Begemanc5f0f652008-07-14 18:02:46 +00003824 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003825 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003826
Chris Lattner254f3bc2007-08-26 01:18:55 +00003827 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003828 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3829 UsualArithmeticConversions(lex, rex);
3830 else {
3831 UsualUnaryConversions(lex);
3832 UsualUnaryConversions(rex);
3833 }
Chris Lattner4b009652007-07-25 00:24:17 +00003834 QualType lType = lex->getType();
3835 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003836
Mike Stumpea3d74e2009-05-07 18:43:07 +00003837 if (!lType->isFloatingType()
3838 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003839 // For non-floating point types, check for self-comparisons of the form
3840 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3841 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00003842 // NOTE: Don't warn about comparisons of enum constants. These can arise
3843 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00003844 Expr *LHSStripped = lex->IgnoreParens();
3845 Expr *RHSStripped = rex->IgnoreParens();
3846 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3847 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00003848 if (DRL->getDecl() == DRR->getDecl() &&
3849 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00003850 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00003851
3852 if (isa<CastExpr>(LHSStripped))
3853 LHSStripped = LHSStripped->IgnoreParenCasts();
3854 if (isa<CastExpr>(RHSStripped))
3855 RHSStripped = RHSStripped->IgnoreParenCasts();
3856
3857 // Warn about comparisons against a string constant (unless the other
3858 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00003859 Expr *literalString = 0;
3860 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00003861 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00003862 !RHSStripped->isNullPointerConstant(Context)) {
3863 literalString = lex;
3864 literalStringStripped = LHSStripped;
3865 }
Chris Lattner4e479f92009-03-08 19:39:53 +00003866 else if ((isa<StringLiteral>(RHSStripped) ||
3867 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00003868 !LHSStripped->isNullPointerConstant(Context)) {
3869 literalString = rex;
3870 literalStringStripped = RHSStripped;
3871 }
3872
3873 if (literalString) {
3874 std::string resultComparison;
3875 switch (Opc) {
3876 case BinaryOperator::LT: resultComparison = ") < 0"; break;
3877 case BinaryOperator::GT: resultComparison = ") > 0"; break;
3878 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
3879 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
3880 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
3881 case BinaryOperator::NE: resultComparison = ") != 0"; break;
3882 default: assert(false && "Invalid comparison operator");
3883 }
3884 Diag(Loc, diag::warn_stringcompare)
3885 << isa<ObjCEncodeExpr>(literalStringStripped)
3886 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00003887 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
3888 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
3889 "strcmp(")
3890 << CodeModificationHint::CreateInsertion(
3891 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00003892 resultComparison);
3893 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003894 }
Mike Stump9afab102009-02-19 03:04:26 +00003895
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003896 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00003897 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003898
Chris Lattner254f3bc2007-08-26 01:18:55 +00003899 if (isRelational) {
3900 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003901 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003902 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003903 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003904 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003905 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003906 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003907 }
Mike Stump9afab102009-02-19 03:04:26 +00003908
Chris Lattner254f3bc2007-08-26 01:18:55 +00003909 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003910 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003911 }
Mike Stump9afab102009-02-19 03:04:26 +00003912
Chris Lattner22be8422007-08-26 01:10:14 +00003913 bool LHSIsNull = lex->isNullPointerConstant(Context);
3914 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003915
Chris Lattner254f3bc2007-08-26 01:18:55 +00003916 // All of the following pointer related warnings are GCC extensions, except
3917 // when handling null pointer constants. One day, we can consider making them
3918 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003919 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003920 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003921 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003922 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003923 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003924
Douglas Gregor30eed0f2009-05-04 06:07:12 +00003925 // Simple check: if the pointee types are identical, we're done.
3926 if (LCanPointeeTy == RCanPointeeTy)
3927 return ResultTy;
3928
3929 if (getLangOptions().CPlusPlus) {
3930 // C++ [expr.rel]p2:
3931 // [...] Pointer conversions (4.10) and qualification
3932 // conversions (4.4) are performed on pointer operands (or on
3933 // a pointer operand and a null pointer constant) to bring
3934 // them to their composite pointer type. [...]
3935 //
3936 // C++ [expr.eq]p2 uses the same notion for (in)equality
3937 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00003938 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00003939 if (T.isNull()) {
3940 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
3941 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3942 return QualType();
3943 }
3944
3945 ImpCastExprToType(lex, T);
3946 ImpCastExprToType(rex, T);
3947 return ResultTy;
3948 }
3949
Steve Naroff3b435622007-11-13 14:57:38 +00003950 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003951 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3952 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003953 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003954 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003955 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003956 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003957 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003958 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003959 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003960 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00003961 // C++ allows comparison of pointers with null pointer constants.
3962 if (getLangOptions().CPlusPlus) {
3963 if (lType->isPointerType() && RHSIsNull) {
3964 ImpCastExprToType(rex, lType);
3965 return ResultTy;
3966 }
3967 if (rType->isPointerType() && LHSIsNull) {
3968 ImpCastExprToType(lex, rType);
3969 return ResultTy;
3970 }
3971 // And comparison of nullptr_t with itself.
3972 if (lType->isNullPtrType() && rType->isNullPtrType())
3973 return ResultTy;
3974 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003975 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00003976 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003977 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3978 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003979
Steve Naroff3454b6c2008-09-04 15:10:53 +00003980 if (!LHSIsNull && !RHSIsNull &&
3981 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003982 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003983 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003984 }
3985 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003986 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003987 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003988 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00003989 if (!isRelational
3990 && ((lType->isBlockPointerType() && rType->isPointerType())
3991 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00003992 if (!LHSIsNull && !RHSIsNull) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003993 if (!((rType->isPointerType() && rType->getAsPointerType()
3994 ->getPointeeType()->isVoidType())
3995 || (lType->isPointerType() && lType->getAsPointerType()
3996 ->getPointeeType()->isVoidType())))
3997 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
3998 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003999 }
4000 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004001 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00004002 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00004003
Steve Naroff936c4362008-06-03 14:04:54 +00004004 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00004005 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00004006 const PointerType *LPT = lType->getAsPointerType();
4007 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00004008 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004009 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004010 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00004011 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00004012
Steve Naroff030fcda2008-11-17 19:49:16 +00004013 if (!LPtrToVoid && !RPtrToVoid &&
4014 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004015 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004016 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00004017 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004018 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00004019 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004020 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004021 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00004022 }
Steve Naroff936c4362008-06-03 14:04:54 +00004023 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
4024 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004025 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00004026 } else {
4027 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00004028 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00004029 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00004030 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004031 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00004032 }
Steve Naroff936c4362008-06-03 14:04:54 +00004033 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00004034 }
Mike Stump9afab102009-02-19 03:04:26 +00004035 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00004036 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00004037 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00004038 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004039 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00004040 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004041 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004042 }
Mike Stump9afab102009-02-19 03:04:26 +00004043 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00004044 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00004045 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00004046 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004047 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00004048 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004049 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004050 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004051 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004052 if (!isRelational && RHSIsNull
4053 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004054 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004055 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004056 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004057 if (!isRelational && LHSIsNull
4058 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004059 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004060 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004061 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004062 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004063}
4064
Nate Begemanc5f0f652008-07-14 18:02:46 +00004065/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004066/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004067/// like a scalar comparison, a vector comparison produces a vector of integer
4068/// types.
4069QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004070 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004071 bool isRelational) {
4072 // Check to make sure we're operating on vectors of the same type and width,
4073 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004074 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004075 if (vType.isNull())
4076 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004077
Nate Begemanc5f0f652008-07-14 18:02:46 +00004078 QualType lType = lex->getType();
4079 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004080
Nate Begemanc5f0f652008-07-14 18:02:46 +00004081 // For non-floating point types, check for self-comparisons of the form
4082 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4083 // often indicate logic errors in the program.
4084 if (!lType->isFloatingType()) {
4085 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4086 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4087 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004088 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004089 }
Mike Stump9afab102009-02-19 03:04:26 +00004090
Nate Begemanc5f0f652008-07-14 18:02:46 +00004091 // Check for comparisons of floating point operands using != and ==.
4092 if (!isRelational && lType->isFloatingType()) {
4093 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004094 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004095 }
Mike Stump9afab102009-02-19 03:04:26 +00004096
Chris Lattner10687e32009-03-31 07:46:52 +00004097 // FIXME: Vector compare support in the LLVM backend is not fully reliable,
4098 // just reject all vector comparisons for now.
4099 if (1) {
4100 Diag(Loc, diag::err_typecheck_vector_comparison)
4101 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4102 return QualType();
4103 }
4104
Nate Begemanc5f0f652008-07-14 18:02:46 +00004105 // Return the type for the comparison, which is the same as vector type for
4106 // integer vectors, or an integer type of identical size and number of
4107 // elements for floating point vectors.
4108 if (lType->isIntegerType())
4109 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004110
Nate Begemanc5f0f652008-07-14 18:02:46 +00004111 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004112 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004113 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004114 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004115 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004116 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4117
Mike Stump9afab102009-02-19 03:04:26 +00004118 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004119 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004120 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4121}
4122
Chris Lattner4b009652007-07-25 00:24:17 +00004123inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004124 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004125{
4126 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004127 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004128
Steve Naroff8f708362007-08-24 19:07:16 +00004129 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004130
Chris Lattner4b009652007-07-25 00:24:17 +00004131 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004132 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004133 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004134}
4135
4136inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004137 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004138{
4139 UsualUnaryConversions(lex);
4140 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004141
Eli Friedmanbea3f842008-05-13 20:16:47 +00004142 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004143 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004144 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004145}
4146
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004147/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4148/// is a read-only property; return true if so. A readonly property expression
4149/// depends on various declarations and thus must be treated specially.
4150///
Mike Stump9afab102009-02-19 03:04:26 +00004151static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004152{
4153 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4154 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4155 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4156 QualType BaseType = PropExpr->getBase()->getType();
4157 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00004158 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004159 PTy->getPointeeType()->getAsObjCInterfaceType())
4160 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
4161 if (S.isPropertyReadonly(PDecl, IFace))
4162 return true;
4163 }
4164 }
4165 return false;
4166}
4167
Chris Lattner4c2642c2008-11-18 01:22:49 +00004168/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4169/// emit an error and return true. If so, return false.
4170static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004171 SourceLocation OrigLoc = Loc;
4172 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4173 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004174 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4175 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004176 if (IsLV == Expr::MLV_Valid)
4177 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004178
Chris Lattner4c2642c2008-11-18 01:22:49 +00004179 unsigned Diag = 0;
4180 bool NeedType = false;
4181 switch (IsLV) { // C99 6.5.16p2
4182 default: assert(0 && "Unknown result from isModifiableLvalue!");
4183 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004184 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004185 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4186 NeedType = true;
4187 break;
Mike Stump9afab102009-02-19 03:04:26 +00004188 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004189 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4190 NeedType = true;
4191 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004192 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004193 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4194 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004195 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004196 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4197 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004198 case Expr::MLV_IncompleteType:
4199 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004200 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004201 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
4202 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004203 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004204 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4205 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004206 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004207 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4208 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004209 case Expr::MLV_ReadonlyProperty:
4210 Diag = diag::error_readonly_property_assignment;
4211 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004212 case Expr::MLV_NoSetterProperty:
4213 Diag = diag::error_nosetter_property_assignment;
4214 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004215 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004216
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004217 SourceRange Assign;
4218 if (Loc != OrigLoc)
4219 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004220 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004221 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004222 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004223 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004224 return true;
4225}
4226
4227
4228
4229// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004230QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4231 SourceLocation Loc,
4232 QualType CompoundType) {
4233 // Verify that LHS is a modifiable lvalue, and emit error if not.
4234 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004235 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004236
4237 QualType LHSType = LHS->getType();
4238 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004239
Chris Lattner005ed752008-01-04 18:04:52 +00004240 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004241 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004242 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004243 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004244 // Special case of NSObject attributes on c-style pointer types.
4245 if (ConvTy == IncompatiblePointer &&
4246 ((Context.isObjCNSObjectType(LHSType) &&
4247 Context.isObjCObjectPointerType(RHSType)) ||
4248 (Context.isObjCNSObjectType(RHSType) &&
4249 Context.isObjCObjectPointerType(LHSType))))
4250 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004251
Chris Lattner34c85082008-08-21 18:04:13 +00004252 // If the RHS is a unary plus or minus, check to see if they = and + are
4253 // right next to each other. If so, the user may have typo'd "x =+ 4"
4254 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004255 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004256 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4257 RHSCheck = ICE->getSubExpr();
4258 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4259 if ((UO->getOpcode() == UnaryOperator::Plus ||
4260 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004261 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004262 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004263 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4264 // And there is a space or other character before the subexpr of the
4265 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004266 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4267 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004268 Diag(Loc, diag::warn_not_compound_assign)
4269 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4270 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004271 }
Chris Lattner34c85082008-08-21 18:04:13 +00004272 }
4273 } else {
4274 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004275 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004276 }
Chris Lattner005ed752008-01-04 18:04:52 +00004277
Chris Lattner1eafdea2008-11-18 01:30:42 +00004278 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4279 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004280 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004281
Chris Lattner4b009652007-07-25 00:24:17 +00004282 // C99 6.5.16p3: The type of an assignment expression is the type of the
4283 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004284 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004285 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4286 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004287 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004288 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004289 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004290}
4291
Chris Lattner1eafdea2008-11-18 01:30:42 +00004292// C99 6.5.17
4293QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004294 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004295 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004296
4297 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4298 // incomplete in C++).
4299
Chris Lattner1eafdea2008-11-18 01:30:42 +00004300 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004301}
4302
4303/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4304/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004305QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4306 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004307 if (Op->isTypeDependent())
4308 return Context.DependentTy;
4309
Chris Lattnere65182c2008-11-21 07:05:48 +00004310 QualType ResType = Op->getType();
4311 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004312
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004313 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4314 // Decrement of bool is not allowed.
4315 if (!isInc) {
4316 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4317 return QualType();
4318 }
4319 // Increment of bool sets it to true, but is deprecated.
4320 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4321 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004322 // OK!
4323 } else if (const PointerType *PT = ResType->getAsPointerType()) {
4324 // C99 6.5.2.4p2, 6.5.6p2
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004325 if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004326 if (getLangOptions().CPlusPlus) {
4327 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4328 << Op->getSourceRange();
4329 return QualType();
4330 }
4331
4332 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004333 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004334 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004335 if (getLangOptions().CPlusPlus) {
4336 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4337 << Op->getType() << Op->getSourceRange();
4338 return QualType();
4339 }
4340
4341 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004342 << ResType << Op->getSourceRange();
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004343 } else if (RequireCompleteType(OpLoc, PT->getPointeeType(),
4344 diag::err_typecheck_arithmetic_incomplete_type,
4345 Op->getSourceRange(), SourceRange(),
4346 ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004347 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004348 } else if (ResType->isComplexType()) {
4349 // C99 does not support ++/-- on complex types, we allow as an extension.
4350 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004351 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004352 } else {
4353 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004354 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004355 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004356 }
Mike Stump9afab102009-02-19 03:04:26 +00004357 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004358 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004359 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004360 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004361 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004362}
4363
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004364/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004365/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004366/// where the declaration is needed for type checking. We only need to
4367/// handle cases when the expression references a function designator
4368/// or is an lvalue. Here are some examples:
4369/// - &(x) => x
4370/// - &*****f => f for f a function designator.
4371/// - &s.xx => s
4372/// - &s.zz[1].yy -> s, if zz is an array
4373/// - *(x + 1) -> x, if x is an array
4374/// - &"123"[2] -> 0
4375/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004376static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004377 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004378 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004379 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004380 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004381 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004382 // If this is an arrow operator, the address is an offset from
4383 // the base's value, so the object the base refers to is
4384 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004385 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004386 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004387 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004388 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004389 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004390 // FIXME: This code shouldn't be necessary! We should catch the implicit
4391 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004392 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4393 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4394 if (ICE->getSubExpr()->getType()->isArrayType())
4395 return getPrimaryDecl(ICE->getSubExpr());
4396 }
4397 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004398 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004399 case Stmt::UnaryOperatorClass: {
4400 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004401
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004402 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004403 case UnaryOperator::Real:
4404 case UnaryOperator::Imag:
4405 case UnaryOperator::Extension:
4406 return getPrimaryDecl(UO->getSubExpr());
4407 default:
4408 return 0;
4409 }
4410 }
Chris Lattner4b009652007-07-25 00:24:17 +00004411 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004412 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004413 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004414 // If the result of an implicit cast is an l-value, we care about
4415 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004416 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004417 default:
4418 return 0;
4419 }
4420}
4421
4422/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004423/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004424/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004425/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004426/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004427/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004428/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004429QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004430 // Make sure to ignore parentheses in subsequent checks
4431 op = op->IgnoreParens();
4432
Douglas Gregore6be68a2008-12-17 22:52:20 +00004433 if (op->isTypeDependent())
4434 return Context.DependentTy;
4435
Steve Naroff9c6c3592008-01-13 17:10:08 +00004436 if (getLangOptions().C99) {
4437 // Implement C99-only parts of addressof rules.
4438 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4439 if (uOp->getOpcode() == UnaryOperator::Deref)
4440 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4441 // (assuming the deref expression is valid).
4442 return uOp->getSubExpr()->getType();
4443 }
4444 // Technically, there should be a check for array subscript
4445 // expressions here, but the result of one is always an lvalue anyway.
4446 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004447 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004448 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004449
Eli Friedman14ab4c42009-05-16 23:27:50 +00004450 if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4451 // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004452 // The operand must be either an l-value or a function designator
Eli Friedman14ab4c42009-05-16 23:27:50 +00004453 if (!op->getType()->isFunctionType()) {
Chris Lattnera3249072007-11-16 17:46:48 +00004454 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004455 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4456 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004457 return QualType();
4458 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004459 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004460 // The operand cannot be a bit-field
4461 Diag(OpLoc, diag::err_typecheck_address_of)
4462 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004463 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004464 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4465 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004466 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004467 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004468 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004469 return QualType();
4470 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004471 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004472 // with the register storage-class specifier.
4473 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4474 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004475 Diag(OpLoc, diag::err_typecheck_address_of)
4476 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004477 return QualType();
4478 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00004479 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004480 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00004481 } else if (isa<FieldDecl>(dcl)) {
4482 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004483 // Could be a pointer to member, though, if there is an explicit
4484 // scope qualifier for the class.
4485 if (isa<QualifiedDeclRefExpr>(op)) {
4486 DeclContext *Ctx = dcl->getDeclContext();
4487 if (Ctx && Ctx->isRecord())
4488 return Context.getMemberPointerType(op->getType(),
4489 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4490 }
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004491 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
Nuno Lopesdf239522008-12-16 22:58:26 +00004492 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004493 // As above.
Anders Carlssone9cc4c42009-05-16 21:43:42 +00004494 if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4495 return Context.getMemberPointerType(op->getType(),
4496 Context.getTypeDeclType(MD->getParent()).getTypePtr());
4497 } else if (!isa<FunctionDecl>(dcl))
Chris Lattner4b009652007-07-25 00:24:17 +00004498 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004499 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004500
Eli Friedman14ab4c42009-05-16 23:27:50 +00004501 if (lval == Expr::LV_IncompleteVoidType) {
4502 // Taking the address of a void variable is technically illegal, but we
4503 // allow it in cases which are otherwise valid.
4504 // Example: "extern void x; void* y = &x;".
4505 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
4506 }
4507
Chris Lattner4b009652007-07-25 00:24:17 +00004508 // If the operand has type "type", the result has type "pointer to type".
4509 return Context.getPointerType(op->getType());
4510}
4511
Chris Lattnerda5c0872008-11-23 09:13:29 +00004512QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004513 if (Op->isTypeDependent())
4514 return Context.DependentTy;
4515
Chris Lattnerda5c0872008-11-23 09:13:29 +00004516 UsualUnaryConversions(Op);
4517 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004518
Chris Lattnerda5c0872008-11-23 09:13:29 +00004519 // Note that per both C89 and C99, this is always legal, even if ptype is an
4520 // incomplete type or void. It would be possible to warn about dereferencing
4521 // a void pointer, but it's completely well-defined, and such a warning is
4522 // unlikely to catch any mistakes.
4523 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00004524 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004525
Chris Lattner77d52da2008-11-20 06:06:08 +00004526 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00004527 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004528 return QualType();
4529}
4530
4531static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4532 tok::TokenKind Kind) {
4533 BinaryOperator::Opcode Opc;
4534 switch (Kind) {
4535 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00004536 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
4537 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004538 case tok::star: Opc = BinaryOperator::Mul; break;
4539 case tok::slash: Opc = BinaryOperator::Div; break;
4540 case tok::percent: Opc = BinaryOperator::Rem; break;
4541 case tok::plus: Opc = BinaryOperator::Add; break;
4542 case tok::minus: Opc = BinaryOperator::Sub; break;
4543 case tok::lessless: Opc = BinaryOperator::Shl; break;
4544 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
4545 case tok::lessequal: Opc = BinaryOperator::LE; break;
4546 case tok::less: Opc = BinaryOperator::LT; break;
4547 case tok::greaterequal: Opc = BinaryOperator::GE; break;
4548 case tok::greater: Opc = BinaryOperator::GT; break;
4549 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
4550 case tok::equalequal: Opc = BinaryOperator::EQ; break;
4551 case tok::amp: Opc = BinaryOperator::And; break;
4552 case tok::caret: Opc = BinaryOperator::Xor; break;
4553 case tok::pipe: Opc = BinaryOperator::Or; break;
4554 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
4555 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
4556 case tok::equal: Opc = BinaryOperator::Assign; break;
4557 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
4558 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
4559 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
4560 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
4561 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
4562 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
4563 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
4564 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
4565 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
4566 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
4567 case tok::comma: Opc = BinaryOperator::Comma; break;
4568 }
4569 return Opc;
4570}
4571
4572static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
4573 tok::TokenKind Kind) {
4574 UnaryOperator::Opcode Opc;
4575 switch (Kind) {
4576 default: assert(0 && "Unknown unary op!");
4577 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
4578 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
4579 case tok::amp: Opc = UnaryOperator::AddrOf; break;
4580 case tok::star: Opc = UnaryOperator::Deref; break;
4581 case tok::plus: Opc = UnaryOperator::Plus; break;
4582 case tok::minus: Opc = UnaryOperator::Minus; break;
4583 case tok::tilde: Opc = UnaryOperator::Not; break;
4584 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004585 case tok::kw___real: Opc = UnaryOperator::Real; break;
4586 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
4587 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
4588 }
4589 return Opc;
4590}
4591
Douglas Gregord7f915e2008-11-06 23:29:22 +00004592/// CreateBuiltinBinOp - Creates a new built-in binary operation with
4593/// operator @p Opc at location @c TokLoc. This routine only supports
4594/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004595Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
4596 unsigned Op,
4597 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004598 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00004599 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00004600 // The following two variables are used for compound assignment operators
4601 QualType CompLHSTy; // Type of LHS after promotions for computation
4602 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00004603
4604 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00004605 case BinaryOperator::Assign:
4606 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
4607 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004608 case BinaryOperator::PtrMemD:
4609 case BinaryOperator::PtrMemI:
4610 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
4611 Opc == BinaryOperator::PtrMemI);
4612 break;
4613 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004614 case BinaryOperator::Div:
4615 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
4616 break;
4617 case BinaryOperator::Rem:
4618 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
4619 break;
4620 case BinaryOperator::Add:
4621 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
4622 break;
4623 case BinaryOperator::Sub:
4624 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4625 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004626 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004627 case BinaryOperator::Shr:
4628 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4629 break;
4630 case BinaryOperator::LE:
4631 case BinaryOperator::LT:
4632 case BinaryOperator::GE:
4633 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004634 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004635 break;
4636 case BinaryOperator::EQ:
4637 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004638 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004639 break;
4640 case BinaryOperator::And:
4641 case BinaryOperator::Xor:
4642 case BinaryOperator::Or:
4643 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
4644 break;
4645 case BinaryOperator::LAnd:
4646 case BinaryOperator::LOr:
4647 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
4648 break;
4649 case BinaryOperator::MulAssign:
4650 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004651 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
4652 CompLHSTy = CompResultTy;
4653 if (!CompResultTy.isNull())
4654 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004655 break;
4656 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004657 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
4658 CompLHSTy = CompResultTy;
4659 if (!CompResultTy.isNull())
4660 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004661 break;
4662 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004663 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4664 if (!CompResultTy.isNull())
4665 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004666 break;
4667 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004668 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4669 if (!CompResultTy.isNull())
4670 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004671 break;
4672 case BinaryOperator::ShlAssign:
4673 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004674 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
4675 CompLHSTy = CompResultTy;
4676 if (!CompResultTy.isNull())
4677 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004678 break;
4679 case BinaryOperator::AndAssign:
4680 case BinaryOperator::XorAssign:
4681 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004682 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
4683 CompLHSTy = CompResultTy;
4684 if (!CompResultTy.isNull())
4685 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004686 break;
4687 case BinaryOperator::Comma:
4688 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
4689 break;
4690 }
4691 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004692 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00004693 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00004694 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
4695 else
4696 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00004697 CompLHSTy, CompResultTy,
4698 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00004699}
4700
Chris Lattner4b009652007-07-25 00:24:17 +00004701// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004702Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4703 tok::TokenKind Kind,
4704 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00004705 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00004706 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00004707
Steve Naroff87d58b42007-09-16 03:34:24 +00004708 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4709 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004710
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004711 if (getLangOptions().CPlusPlus &&
4712 (lhs->getType()->isOverloadableType() ||
4713 rhs->getType()->isOverloadableType())) {
4714 // Find all of the overloaded operators visible from this
4715 // point. We perform both an operator-name lookup from the local
4716 // scope and an argument-dependent lookup based on the types of
4717 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00004718 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004719 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4720 if (OverOp != OO_None) {
4721 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4722 Functions);
4723 Expr *Args[2] = { lhs, rhs };
4724 DeclarationName OpName
4725 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4726 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00004727 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004728
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004729 // Build the (potentially-overloaded, potentially-dependent)
4730 // binary operation.
4731 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004732 }
4733
Douglas Gregord7f915e2008-11-06 23:29:22 +00004734 // Build a built-in binary operation.
4735 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00004736}
4737
Douglas Gregorc78182d2009-03-13 23:49:33 +00004738Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4739 unsigned OpcIn,
4740 ExprArg InputArg) {
4741 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004742
Mike Stumpe127ae32009-05-16 07:39:55 +00004743 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00004744 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004745 QualType resultType;
4746 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004747 case UnaryOperator::PostInc:
4748 case UnaryOperator::PostDec:
4749 case UnaryOperator::OffsetOf:
4750 assert(false && "Invalid unary operator");
4751 break;
4752
Chris Lattner4b009652007-07-25 00:24:17 +00004753 case UnaryOperator::PreInc:
4754 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004755 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4756 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004757 break;
Mike Stump9afab102009-02-19 03:04:26 +00004758 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004759 resultType = CheckAddressOfOperand(Input, OpLoc);
4760 break;
Mike Stump9afab102009-02-19 03:04:26 +00004761 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004762 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004763 resultType = CheckIndirectionOperand(Input, OpLoc);
4764 break;
4765 case UnaryOperator::Plus:
4766 case UnaryOperator::Minus:
4767 UsualUnaryConversions(Input);
4768 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004769 if (resultType->isDependentType())
4770 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004771 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4772 break;
4773 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4774 resultType->isEnumeralType())
4775 break;
4776 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4777 Opc == UnaryOperator::Plus &&
4778 resultType->isPointerType())
4779 break;
4780
Sebastian Redl8b769972009-01-19 00:08:26 +00004781 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4782 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004783 case UnaryOperator::Not: // bitwise complement
4784 UsualUnaryConversions(Input);
4785 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004786 if (resultType->isDependentType())
4787 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00004788 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4789 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4790 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004791 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004792 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004793 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004794 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4795 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004796 break;
4797 case UnaryOperator::LNot: // logical negation
4798 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4799 DefaultFunctionArrayConversion(Input);
4800 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004801 if (resultType->isDependentType())
4802 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004803 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004804 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4805 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004806 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004807 // In C++, it's bool. C++ 5.3.1p8
4808 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004809 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004810 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004811 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004812 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004813 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004814 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004815 resultType = Input->getType();
4816 break;
4817 }
4818 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004819 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00004820
4821 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004822 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004823}
4824
Douglas Gregorc78182d2009-03-13 23:49:33 +00004825// Unary Operators. 'Tok' is the token for the operator.
4826Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4827 tok::TokenKind Op, ExprArg input) {
4828 Expr *Input = (Expr*)input.get();
4829 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4830
4831 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
4832 // Find all of the overloaded operators visible from this
4833 // point. We perform both an operator-name lookup from the local
4834 // scope and an argument-dependent lookup based on the types of
4835 // the arguments.
4836 FunctionSet Functions;
4837 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
4838 if (OverOp != OO_None) {
4839 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
4840 Functions);
4841 DeclarationName OpName
4842 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4843 ArgumentDependentLookup(OpName, &Input, 1, Functions);
4844 }
4845
4846 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
4847 }
4848
4849 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
4850}
4851
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004852/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004853Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4854 SourceLocation LabLoc,
4855 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00004856 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00004857 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00004858
Daniel Dunbar879788d2008-08-04 16:51:22 +00004859 // If we haven't seen this label yet, create a forward reference. It
4860 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00004861 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004862 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004863
Chris Lattner4b009652007-07-25 00:24:17 +00004864 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004865 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4866 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00004867}
4868
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004869Sema::OwningExprResult
4870Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
4871 SourceLocation RPLoc) { // "({..})"
4872 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00004873 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4874 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4875
Eli Friedmanbc941e12009-01-24 23:09:00 +00004876 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00004877 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004878 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00004879
Chris Lattner4b009652007-07-25 00:24:17 +00004880 // FIXME: there are a variety of strange constraints to enforce here, for
4881 // example, it is not possible to goto into a stmt expression apparently.
4882 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004883
Chris Lattner4b009652007-07-25 00:24:17 +00004884 // If there are sub stmts in the compound stmt, take the type of the last one
4885 // as the type of the stmtexpr.
4886 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004887
Chris Lattner200964f2008-07-26 19:51:01 +00004888 if (!Compound->body_empty()) {
4889 Stmt *LastStmt = Compound->body_back();
4890 // If LastStmt is a label, skip down through into the body.
4891 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4892 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004893
Chris Lattner200964f2008-07-26 19:51:01 +00004894 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004895 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004896 }
Mike Stump9afab102009-02-19 03:04:26 +00004897
Eli Friedman2b128322009-03-23 00:24:07 +00004898 // FIXME: Check that expression type is complete/non-abstract; statement
4899 // expressions are not lvalues.
4900
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004901 substmt.release();
4902 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004903}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004904
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004905Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4906 SourceLocation BuiltinLoc,
4907 SourceLocation TypeLoc,
4908 TypeTy *argty,
4909 OffsetOfComponent *CompPtr,
4910 unsigned NumComponents,
4911 SourceLocation RPLoc) {
4912 // FIXME: This function leaks all expressions in the offset components on
4913 // error.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004914 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4915 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004916
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004917 bool Dependent = ArgTy->isDependentType();
4918
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004919 // We must have at least one component that refers to the type, and the first
4920 // one is known to be a field designator. Verify that the ArgTy represents
4921 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004922 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004923 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00004924
Eli Friedman2b128322009-03-23 00:24:07 +00004925 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
4926 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00004927
Eli Friedman342d9432009-02-27 06:44:11 +00004928 // Otherwise, create a null pointer as the base, and iteratively process
4929 // the offsetof designators.
4930 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4931 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004932 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00004933 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004934
Chris Lattnerb37522e2007-08-31 21:49:13 +00004935 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4936 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00004937 // FIXME: This diagnostic isn't actually visible because the location is in
4938 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00004939 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004940 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4941 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004942
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004943 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00004944 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00004945
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004946 // FIXME: Dependent case loses a lot of information here. And probably
4947 // leaks like a sieve.
4948 for (unsigned i = 0; i != NumComponents; ++i) {
4949 const OffsetOfComponent &OC = CompPtr[i];
4950 if (OC.isBrackets) {
4951 // Offset of an array sub-field. TODO: Should we allow vector elements?
4952 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4953 if (!AT) {
4954 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004955 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
4956 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004957 }
4958
4959 // FIXME: C++: Verify that operator[] isn't overloaded.
4960
Eli Friedman342d9432009-02-27 06:44:11 +00004961 // Promote the array so it looks more like a normal array subscript
4962 // expression.
4963 DefaultFunctionArrayConversion(Res);
4964
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004965 // C99 6.5.2.1p1
4966 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004967 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004968 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004969 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00004970 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004971 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004972
4973 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4974 OC.LocEnd);
4975 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004976 }
Mike Stump9afab102009-02-19 03:04:26 +00004977
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004978 const RecordType *RC = Res->getType()->getAsRecordType();
4979 if (!RC) {
4980 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004981 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
4982 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004983 }
Chris Lattner2af6a802007-08-30 17:59:59 +00004984
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004985 // Get the decl corresponding to this.
4986 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00004987 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00004988 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00004989 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
4990 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
4991 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00004992 DidWarnAboutNonPOD = true;
4993 }
Anders Carlsson356946e2009-05-01 23:20:30 +00004994 }
4995
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004996 FieldDecl *MemberDecl
4997 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4998 LookupMemberName)
4999 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005000 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005001 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005002 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
5003 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00005004
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005005 // FIXME: C++: Verify that MemberDecl isn't a static field.
5006 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00005007 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00005008 Res = BuildAnonymousStructUnionMemberReference(
5009 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00005010 } else {
5011 // MemberDecl->getType() doesn't get the right qualifiers, but it
5012 // doesn't matter here.
5013 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5014 MemberDecl->getType().getNonReferenceType());
5015 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005016 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005017 }
Mike Stump9afab102009-02-19 03:04:26 +00005018
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005019 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5020 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00005021}
5022
5023
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005024Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5025 TypeTy *arg1,TypeTy *arg2,
5026 SourceLocation RPLoc) {
Steve Naroff63bad2d2007-08-01 22:05:33 +00005027 QualType argT1 = QualType::getFromOpaquePtr(arg1);
5028 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00005029
Steve Naroff63bad2d2007-08-01 22:05:33 +00005030 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00005031
Douglas Gregore6211502009-05-19 22:28:02 +00005032 if (getLangOptions().CPlusPlus) {
5033 Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5034 << SourceRange(BuiltinLoc, RPLoc);
5035 return ExprError();
5036 }
5037
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005038 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5039 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00005040}
5041
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005042Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5043 ExprArg cond,
5044 ExprArg expr1, ExprArg expr2,
5045 SourceLocation RPLoc) {
5046 Expr *CondExpr = static_cast<Expr*>(cond.get());
5047 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5048 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005049
Steve Naroff93c53012007-08-03 21:21:27 +00005050 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5051
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005052 QualType resType;
Douglas Gregordd4ae3f2009-05-19 22:43:30 +00005053 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005054 resType = Context.DependentTy;
5055 } else {
5056 // The conditional expression is required to be a constant expression.
5057 llvm::APSInt condEval(32);
5058 SourceLocation ExpLoc;
5059 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005060 return ExprError(Diag(ExpLoc,
5061 diag::err_typecheck_choose_expr_requires_constant)
5062 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005063
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005064 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5065 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5066 }
5067
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005068 cond.release(); expr1.release(); expr2.release();
5069 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5070 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005071}
5072
Steve Naroff52a81c02008-09-03 18:15:37 +00005073//===----------------------------------------------------------------------===//
5074// Clang Extensions.
5075//===----------------------------------------------------------------------===//
5076
5077/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005078void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005079 // Analyze block parameters.
5080 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005081
Steve Naroff52a81c02008-09-03 18:15:37 +00005082 // Add BSI to CurBlock.
5083 BSI->PrevBlockInfo = CurBlock;
5084 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005085
Steve Naroff52a81c02008-09-03 18:15:37 +00005086 BSI->ReturnType = 0;
5087 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005088 BSI->hasBlockDeclRefExprs = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005089 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5090 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005091
Steve Naroff52059382008-10-10 01:28:17 +00005092 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005093 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005094}
5095
Mike Stumpc1fddff2009-02-04 22:31:32 +00005096void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005097 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005098
5099 if (ParamInfo.getNumTypeObjects() == 0
5100 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
Fariborz Jahanian262c0d72009-05-18 23:17:46 +00005101 ProcessDeclAttributes(CurBlock->TheDecl, ParamInfo);
Mike Stumpc1fddff2009-02-04 22:31:32 +00005102 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5103
Mike Stump458287d2009-04-28 01:10:27 +00005104 if (T->isArrayType()) {
5105 Diag(ParamInfo.getSourceRange().getBegin(),
5106 diag::err_block_returns_array);
5107 return;
5108 }
5109
Mike Stumpc1fddff2009-02-04 22:31:32 +00005110 // The parameter list is optional, if there was none, assume ().
5111 if (!T->isFunctionType())
5112 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5113
5114 CurBlock->hasPrototype = true;
5115 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005116 // Check for a valid sentinel attribute on this block.
5117 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5118 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005119 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005120 // FIXME: remove the attribute.
5121 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005122 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5123
5124 // Do not allow returning a objc interface by-value.
5125 if (RetTy->isObjCInterfaceType()) {
5126 Diag(ParamInfo.getSourceRange().getBegin(),
5127 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5128 return;
5129 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005130 return;
5131 }
5132
Steve Naroff52a81c02008-09-03 18:15:37 +00005133 // Analyze arguments to block.
5134 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5135 "Not a function declarator!");
5136 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005137
Steve Naroff52059382008-10-10 01:28:17 +00005138 CurBlock->hasPrototype = FTI.hasPrototype;
5139 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005140
Steve Naroff52a81c02008-09-03 18:15:37 +00005141 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5142 // no arguments, not a function that takes a single void argument.
5143 if (FTI.hasPrototype &&
5144 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005145 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5146 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005147 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005148 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005149 } else if (FTI.hasPrototype) {
5150 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005151 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005152 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005153 }
Jay Foad9e6bef42009-05-21 09:52:38 +00005154 CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005155 CurBlock->Params.size());
Fariborz Jahanian536f73d2009-05-19 17:08:59 +00005156 CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
Fariborz Jahanian262c0d72009-05-18 23:17:46 +00005157 ProcessDeclAttributes(CurBlock->TheDecl, ParamInfo);
Steve Naroff52059382008-10-10 01:28:17 +00005158 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5159 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5160 // If this has an identifier, add it to the scope stack.
5161 if ((*AI)->getIdentifier())
5162 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005163
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005164 // Check for a valid sentinel attribute on this block.
5165 if (!CurBlock->isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5166 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005167 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005168 // FIXME: remove the attribute.
5169 }
5170
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005171 // Analyze the return type.
5172 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5173 QualType RetTy = T->getAsFunctionType()->getResultType();
5174
5175 // Do not allow returning a objc interface by-value.
5176 if (RetTy->isObjCInterfaceType()) {
5177 Diag(ParamInfo.getSourceRange().getBegin(),
5178 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5179 } else if (!RetTy->isDependentType())
5180 CurBlock->ReturnType = RetTy.getTypePtr();
Steve Naroff52a81c02008-09-03 18:15:37 +00005181}
5182
5183/// ActOnBlockError - If there is an error parsing a block, this callback
5184/// is invoked to pop the information about the block from the action impl.
5185void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5186 // Ensure that CurBlock is deleted.
5187 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005188
Chris Lattnere7765e12009-04-19 05:28:12 +00005189 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5190
Steve Naroff52a81c02008-09-03 18:15:37 +00005191 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005192 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005193 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005194 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005195}
5196
5197/// ActOnBlockStmtExpr - This is called when the body of a block statement
5198/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005199Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5200 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005201 // If blocks are disabled, emit an error.
5202 if (!LangOpts.Blocks)
5203 Diag(CaretLoc, diag::err_blocks_disable);
5204
Steve Naroff52a81c02008-09-03 18:15:37 +00005205 // Ensure that CurBlock is deleted.
5206 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005207
Steve Naroff52059382008-10-10 01:28:17 +00005208 PopDeclContext();
5209
Steve Naroff52a81c02008-09-03 18:15:37 +00005210 // Pop off CurBlock, handle nested blocks.
5211 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005212
Steve Naroff52a81c02008-09-03 18:15:37 +00005213 QualType RetTy = Context.VoidTy;
5214 if (BSI->ReturnType)
5215 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005216
Steve Naroff52a81c02008-09-03 18:15:37 +00005217 llvm::SmallVector<QualType, 8> ArgTypes;
5218 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5219 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005220
Steve Naroff52a81c02008-09-03 18:15:37 +00005221 QualType BlockTy;
5222 if (!BSI->hasPrototype)
Douglas Gregor4fa58902009-02-26 23:50:07 +00005223 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00005224 else
Jay Foad9e6bef42009-05-21 09:52:38 +00005225 BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00005226 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005227
Eli Friedman2b128322009-03-23 00:24:07 +00005228 // FIXME: Check that return/parameter types are complete/non-abstract
5229
Steve Naroff52a81c02008-09-03 18:15:37 +00005230 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005231
Chris Lattnere7765e12009-04-19 05:28:12 +00005232 // If needed, diagnose invalid gotos and switches in the block.
5233 if (CurFunctionNeedsScopeChecking)
5234 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5235 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5236
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005237 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005238 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5239 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005240}
5241
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005242Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5243 ExprArg expr, TypeTy *type,
5244 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00005245 QualType T = QualType::getFromOpaquePtr(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005246 Expr *E = static_cast<Expr*>(expr.get());
5247 Expr *OrigExpr = E;
5248
Anders Carlsson36760332007-10-15 20:28:48 +00005249 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005250
5251 // Get the va_list type
5252 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedman6f6e8922009-05-16 12:46:54 +00005253 if (VaListType->isArrayType()) {
5254 // Deal with implicit array decay; for example, on x86-64,
5255 // va_list is an array, but it's supposed to decay to
5256 // a pointer for va_arg.
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005257 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman6f6e8922009-05-16 12:46:54 +00005258 // Make sure the input expression also decays appropriately.
5259 UsualUnaryConversions(E);
5260 } else {
5261 // Otherwise, the va_list argument must be an l-value because
5262 // it is modified by va_arg.
Douglas Gregor25990972009-05-19 23:10:31 +00005263 if (!E->isTypeDependent() &&
5264 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedman6f6e8922009-05-16 12:46:54 +00005265 return ExprError();
5266 }
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005267
Douglas Gregor25990972009-05-19 23:10:31 +00005268 if (!E->isTypeDependent() &&
5269 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005270 return ExprError(Diag(E->getLocStart(),
5271 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005272 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005273 }
Mike Stump9afab102009-02-19 03:04:26 +00005274
Eli Friedman2b128322009-03-23 00:24:07 +00005275 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005276 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005277
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005278 expr.release();
5279 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5280 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005281}
5282
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005283Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005284 // The type of __null will be int or long, depending on the size of
5285 // pointers on the target.
5286 QualType Ty;
5287 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5288 Ty = Context.IntTy;
5289 else
5290 Ty = Context.LongTy;
5291
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005292 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005293}
5294
Chris Lattner005ed752008-01-04 18:04:52 +00005295bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5296 SourceLocation Loc,
5297 QualType DstType, QualType SrcType,
5298 Expr *SrcExpr, const char *Flavor) {
5299 // Decode the result (notice that AST's are still created for extensions).
5300 bool isInvalid = false;
5301 unsigned DiagKind;
5302 switch (ConvTy) {
5303 default: assert(0 && "Unknown conversion type");
5304 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005305 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005306 DiagKind = diag::ext_typecheck_convert_pointer_int;
5307 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005308 case IntToPointer:
5309 DiagKind = diag::ext_typecheck_convert_int_pointer;
5310 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005311 case IncompatiblePointer:
5312 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5313 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005314 case IncompatiblePointerSign:
5315 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5316 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005317 case FunctionVoidPointer:
5318 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5319 break;
5320 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005321 // If the qualifiers lost were because we were applying the
5322 // (deprecated) C++ conversion from a string literal to a char*
5323 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5324 // Ideally, this check would be performed in
5325 // CheckPointerTypesForAssignment. However, that would require a
5326 // bit of refactoring (so that the second argument is an
5327 // expression, rather than a type), which should be done as part
5328 // of a larger effort to fix CheckPointerTypesForAssignment for
5329 // C++ semantics.
5330 if (getLangOptions().CPlusPlus &&
5331 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5332 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005333 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5334 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005335 case IntToBlockPointer:
5336 DiagKind = diag::err_int_to_block_pointer;
5337 break;
5338 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005339 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005340 break;
Steve Naroff19608432008-10-14 22:18:38 +00005341 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005342 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005343 // it can give a more specific diagnostic.
5344 DiagKind = diag::warn_incompatible_qualified_id;
5345 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005346 case IncompatibleVectors:
5347 DiagKind = diag::warn_incompatible_vectors;
5348 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005349 case Incompatible:
5350 DiagKind = diag::err_typecheck_convert_incompatible;
5351 isInvalid = true;
5352 break;
5353 }
Mike Stump9afab102009-02-19 03:04:26 +00005354
Chris Lattner271d4c22008-11-24 05:29:24 +00005355 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5356 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005357 return isInvalid;
5358}
Anders Carlssond5201b92008-11-30 19:50:32 +00005359
Chris Lattnereec8ae22009-04-25 21:59:05 +00005360bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005361 llvm::APSInt ICEResult;
5362 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5363 if (Result)
5364 *Result = ICEResult;
5365 return false;
5366 }
5367
Anders Carlssond5201b92008-11-30 19:50:32 +00005368 Expr::EvalResult EvalResult;
5369
Mike Stump9afab102009-02-19 03:04:26 +00005370 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005371 EvalResult.HasSideEffects) {
5372 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5373
5374 if (EvalResult.Diag) {
5375 // We only show the note if it's not the usual "invalid subexpression"
5376 // or if it's actually in a subexpression.
5377 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5378 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5379 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5380 }
Mike Stump9afab102009-02-19 03:04:26 +00005381
Anders Carlssond5201b92008-11-30 19:50:32 +00005382 return true;
5383 }
5384
Eli Friedmance329412009-04-25 22:26:58 +00005385 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5386 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005387
Eli Friedmance329412009-04-25 22:26:58 +00005388 if (EvalResult.Diag &&
5389 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5390 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005391
Anders Carlssond5201b92008-11-30 19:50:32 +00005392 if (Result)
5393 *Result = EvalResult.Val.getInt();
5394 return false;
5395}