blob: ea0d22ce253e5efff3c120f5e76e6d00689e9969 [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.
821 if (SS && isDependentScopeSpecifier(*SS)) {
Douglas Gregor1e589cc2009-03-26 23:50:42 +0000822 return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
823 Loc, SS->getRange(),
Douglas Gregor041e9292009-03-26 23:56:24 +0000824 static_cast<NestedNameSpecifier *>(SS->getScopeRep())));
Douglas Gregor47bde7c2009-03-19 17:26:29 +0000825 }
826
Douglas Gregor411889e2009-02-13 23:20:09 +0000827 LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
828 false, true, Loc);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +0000829
Sebastian Redlcd883f72009-01-18 18:53:16 +0000830 if (Lookup.isAmbiguous()) {
831 DiagnoseAmbiguousLookup(Lookup, Name, Loc,
832 SS && SS->isSet() ? SS->getRange()
833 : SourceRange());
834 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000835 }
836
837 NamedDecl *D = Lookup.getAsDecl();
Douglas Gregora133e262008-12-06 00:22:45 +0000838
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000839 // If this reference is in an Objective-C method, then ivar lookup happens as
840 // well.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000841 IdentifierInfo *II = Name.getAsIdentifierInfo();
842 if (II && getCurMethodDecl()) {
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000843 // There are two cases to handle here. 1) scoped lookup could have failed,
844 // in which case we should look for an ivar. 2) scoped lookup could have
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000845 // found a decl, but that decl is outside the current instance method (i.e.
846 // a global variable). In these two cases, we do a lookup for an ivar with
847 // this name, if the lookup sucedes, we replace it our current decl.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000848 if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000849 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000850 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000851 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II,
852 ClassDeclared)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +0000853 // Check if referencing a field with __attribute__((deprecated)).
Douglas Gregoraa57e862009-02-18 21:56:37 +0000854 if (DiagnoseUseOfDecl(IV, Loc))
855 return ExprError();
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000856
857 // If we're referencing an invalid decl, just return this as a silent
858 // error node. The error diagnostic was already emitted on the decl.
859 if (IV->isInvalidDecl())
860 return ExprError();
861
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000862 bool IsClsMethod = getCurMethodDecl()->isClassMethod();
863 // If a class method attemps to use a free standing ivar, this is
864 // an error.
865 if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
866 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
867 << IV->getDeclName());
868 // If a class method uses a global variable, even if an ivar with
869 // same name exists, use the global.
870 if (!IsClsMethod) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000871 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
872 ClassDeclared != IFace)
873 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
Mike Stumpe127ae32009-05-16 07:39:55 +0000874 // FIXME: This should use a new expr for a direct reference, don't
875 // turn this into Self->ivar, just return a BareIVarExpr or something.
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000876 IdentifierInfo &II = Context.Idents.get("self");
877 OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
Daniel Dunbarf5254bd2009-04-21 01:19:28 +0000878 return Owned(new (Context)
879 ObjCIvarRefExpr(IV, IV->getType(), Loc,
Anders Carlsson39ecdcf2009-05-01 19:49:17 +0000880 SelfExpr.takeAs<Expr>(), true, true));
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000881 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000882 }
883 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000884 else if (getCurMethodDecl()->isInstanceMethod()) {
885 // We should warn if a local variable hides an ivar.
886 ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000887 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +0000888 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(Context, II,
889 ClassDeclared)) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000890 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
891 IFace == ClassDeclared)
Chris Lattnerf3ce8572009-04-24 22:30:50 +0000892 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
Fariborz Jahaniandd71e752009-03-03 01:21:12 +0000893 }
Fariborz Jahanian67502db2009-03-02 21:55:29 +0000894 }
Steve Naroff0ccfaa42008-08-10 19:10:41 +0000895 // Needed to implement property "super.method" notation.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000896 if (D == 0 && II->isStr("super")) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +0000897 QualType T;
898
899 if (getCurMethodDecl()->isInstanceMethod())
900 T = Context.getPointerType(Context.getObjCInterfaceType(
901 getCurMethodDecl()->getClassInterface()));
902 else
903 T = Context.getObjCClassType();
Steve Naroff774e4152009-01-21 00:14:39 +0000904 return Owned(new (Context) ObjCSuperExpr(Loc, T));
Steve Naroff6f786252008-06-02 23:03:37 +0000905 }
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000906 }
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000907
Douglas Gregoraa57e862009-02-18 21:56:37 +0000908 // Determine whether this name might be a candidate for
909 // argument-dependent lookup.
910 bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
911 HasTrailingLParen;
912
913 if (ADL && D == 0) {
Douglas Gregore2d88fd2009-02-16 19:28:42 +0000914 // We've seen something of the form
915 //
916 // identifier(
917 //
918 // and we did not find any entity by the name
919 // "identifier". However, this identifier is still subject to
920 // argument-dependent lookup, so keep track of the name.
921 return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
922 Context.OverloadTy,
923 Loc));
924 }
925
Chris Lattner4b009652007-07-25 00:24:17 +0000926 if (D == 0) {
927 // Otherwise, this could be an implicitly declared function reference (legal
928 // in C90, extension in C99).
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000929 if (HasTrailingLParen && II &&
Chris Lattnerc72d22d2008-03-31 00:36:02 +0000930 !getLangOptions().CPlusPlus) // Not in C++.
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000931 D = ImplicitlyDefineFunction(Loc, *II, S);
Chris Lattner4b009652007-07-25 00:24:17 +0000932 else {
933 // If this name wasn't predeclared and if this is not a function call,
934 // diagnose the problem.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000935 if (SS && !SS->isEmpty())
Sebastian Redlcd883f72009-01-18 18:53:16 +0000936 return ExprError(Diag(Loc, diag::err_typecheck_no_member)
937 << Name << SS->getRange());
Douglas Gregoraee3bf82008-11-18 15:03:34 +0000938 else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
939 Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
Sebastian Redlcd883f72009-01-18 18:53:16 +0000940 return ExprError(Diag(Loc, diag::err_undeclared_use)
941 << Name.getAsString());
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000942 else
Sebastian Redlcd883f72009-01-18 18:53:16 +0000943 return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +0000944 }
945 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000946
Sebastian Redl0c9da212009-02-03 20:19:35 +0000947 // If this is an expression of the form &Class::member, don't build an
948 // implicit member ref, because we want a pointer to the member in general,
949 // not any specific instance's member.
950 if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +0000951 DeclContext *DC = computeDeclContext(*SS);
Douglas Gregor09be81b2009-02-04 17:27:36 +0000952 if (D && isa<CXXRecordDecl>(DC)) {
Sebastian Redl0c9da212009-02-03 20:19:35 +0000953 QualType DType;
954 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
955 DType = FD->getType().getNonReferenceType();
956 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
957 DType = Method->getType();
958 } else if (isa<OverloadedFunctionDecl>(D)) {
959 DType = Context.OverloadTy;
960 }
961 // Could be an inner type. That's diagnosed below, so ignore it here.
962 if (!DType.isNull()) {
963 // The pointer is type- and value-dependent if it points into something
964 // dependent.
965 bool Dependent = false;
966 for (; DC; DC = DC->getParent()) {
967 // FIXME: could stop early at namespace scope.
968 if (DC->isRecord()) {
969 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
970 if (Context.getTypeDeclType(Record)->isDependentType()) {
971 Dependent = true;
972 break;
973 }
974 }
975 }
Douglas Gregor09be81b2009-02-04 17:27:36 +0000976 return Owned(BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS));
Sebastian Redl0c9da212009-02-03 20:19:35 +0000977 }
978 }
979 }
980
Douglas Gregor723d3332009-01-07 00:43:41 +0000981 // We may have found a field within an anonymous union or struct
982 // (C++ [class.union]).
983 if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
984 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
985 return BuildAnonymousStructUnionMemberReference(Loc, FD);
Sebastian Redlcd883f72009-01-18 18:53:16 +0000986
Douglas Gregor3257fb52008-12-22 05:46:06 +0000987 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
988 if (!MD->isStatic()) {
989 // C++ [class.mfct.nonstatic]p2:
990 // [...] if name lookup (3.4.1) resolves the name in the
991 // id-expression to a nonstatic nontype member of class X or of
992 // a base class of X, the id-expression is transformed into a
993 // class member access expression (5.2.5) using (*this) (9.3.2)
994 // as the postfix-expression to the left of the '.' operator.
995 DeclContext *Ctx = 0;
996 QualType MemberType;
997 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
998 Ctx = FD->getDeclContext();
999 MemberType = FD->getType();
1000
1001 if (const ReferenceType *RefType = MemberType->getAsReferenceType())
1002 MemberType = RefType->getPointeeType();
1003 else if (!FD->isMutable()) {
1004 unsigned combinedQualifiers
1005 = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
1006 MemberType = MemberType.getQualifiedType(combinedQualifiers);
1007 }
1008 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1009 if (!Method->isStatic()) {
1010 Ctx = Method->getParent();
1011 MemberType = Method->getType();
1012 }
1013 } else if (OverloadedFunctionDecl *Ovl
1014 = dyn_cast<OverloadedFunctionDecl>(D)) {
1015 for (OverloadedFunctionDecl::function_iterator
1016 Func = Ovl->function_begin(),
1017 FuncEnd = Ovl->function_end();
1018 Func != FuncEnd; ++Func) {
1019 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
1020 if (!DMethod->isStatic()) {
1021 Ctx = Ovl->getDeclContext();
1022 MemberType = Context.OverloadTy;
1023 break;
1024 }
1025 }
1026 }
Douglas Gregor723d3332009-01-07 00:43:41 +00001027
1028 if (Ctx && Ctx->isRecord()) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00001029 QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
1030 QualType ThisType = Context.getTagDeclType(MD->getParent());
1031 if ((Context.getCanonicalType(CtxType)
1032 == Context.getCanonicalType(ThisType)) ||
1033 IsDerivedFrom(ThisType, CtxType)) {
1034 // Build the implicit member access expression.
Steve Naroff774e4152009-01-21 00:14:39 +00001035 Expr *This = new (Context) CXXThisExpr(SourceLocation(),
Mike Stump9afab102009-02-19 03:04:26 +00001036 MD->getThisType(Context));
Douglas Gregor09be81b2009-02-04 17:27:36 +00001037 return Owned(new (Context) MemberExpr(This, true, D,
Eli Friedman1653e232009-04-29 17:56:47 +00001038 Loc, MemberType));
Douglas Gregor3257fb52008-12-22 05:46:06 +00001039 }
1040 }
1041 }
1042 }
1043
Douglas Gregor8acb7272008-12-11 16:49:14 +00001044 if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001045 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1046 if (MD->isStatic())
1047 // "invalid use of member 'x' in static member function"
Sebastian Redlcd883f72009-01-18 18:53:16 +00001048 return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1049 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001050 }
1051
Douglas Gregor3257fb52008-12-22 05:46:06 +00001052 // Any other ways we could have found the field in a well-formed
1053 // program would have been turned into implicit member expressions
1054 // above.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001055 return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1056 << FD->getDeclName());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001057 }
Douglas Gregor3257fb52008-12-22 05:46:06 +00001058
Chris Lattner4b009652007-07-25 00:24:17 +00001059 if (isa<TypedefDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001060 return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
Ted Kremenek42730c52008-01-07 19:49:32 +00001061 if (isa<ObjCInterfaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001062 return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00001063 if (isa<NamespaceDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001064 return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
Chris Lattner4b009652007-07-25 00:24:17 +00001065
Steve Naroffd6163f32008-09-05 22:11:13 +00001066 // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
Douglas Gregord2baafd2008-10-21 16:13:35 +00001067 if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
Sebastian Redlcd883f72009-01-18 18:53:16 +00001068 return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1069 false, false, SS));
Douglas Gregor35d81bb2009-02-09 23:23:08 +00001070 else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
1071 return Owned(BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1072 false, false, SS));
Steve Naroffd6163f32008-09-05 22:11:13 +00001073 ValueDecl *VD = cast<ValueDecl>(D);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001074
Douglas Gregoraa57e862009-02-18 21:56:37 +00001075 // Check whether this declaration can be used. Note that we suppress
1076 // this check when we're going to perform argument-dependent lookup
1077 // on this function name, because this might not be the function
1078 // that overload resolution actually selects.
1079 if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1080 return ExprError();
1081
Douglas Gregor48840c72008-12-10 23:01:14 +00001082 if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
Chris Lattner2a3bef92009-02-16 17:19:12 +00001083 // Warn about constructs like:
1084 // if (void *X = foo()) { ... } else { X }.
1085 // In the else block, the pointer is always false.
Douglas Gregor48840c72008-12-10 23:01:14 +00001086 if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1087 Scope *CheckS = S;
1088 while (CheckS) {
1089 if (CheckS->isWithinElse() &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00001090 CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
Douglas Gregor48840c72008-12-10 23:01:14 +00001091 if (Var->getType()->isBooleanType())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001092 ExprError(Diag(Loc, diag::warn_value_always_false)
1093 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +00001094 else
Sebastian Redlcd883f72009-01-18 18:53:16 +00001095 ExprError(Diag(Loc, diag::warn_value_always_zero)
1096 << Var->getDeclName());
Douglas Gregor48840c72008-12-10 23:01:14 +00001097 break;
1098 }
1099
1100 // Move up one more control parent to check again.
1101 CheckS = CheckS->getControlParent();
1102 if (CheckS)
1103 CheckS = CheckS->getParent();
1104 }
1105 }
Douglas Gregor1f88aa72009-02-25 16:33:18 +00001106 } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(VD)) {
1107 if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1108 // C99 DR 316 says that, if a function type comes from a
1109 // function definition (without a prototype), that type is only
1110 // used for checking compatibility. Therefore, when referencing
1111 // the function, we pretend that we don't have the full function
1112 // type.
1113 QualType T = Func->getType();
1114 QualType NoProtoType = T;
Douglas Gregor4fa58902009-02-26 23:50:07 +00001115 if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
1116 NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
Douglas Gregor1f88aa72009-02-25 16:33:18 +00001117 return Owned(BuildDeclRefExpr(VD, NoProtoType, Loc, false, false, SS));
1118 }
Douglas Gregor48840c72008-12-10 23:01:14 +00001119 }
Steve Naroffd6163f32008-09-05 22:11:13 +00001120
1121 // Only create DeclRefExpr's for valid Decl's.
1122 if (VD->isInvalidDecl())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001123 return ExprError();
1124
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001125 // If the identifier reference is inside a block, and it refers to a value
1126 // that is outside the block, create a BlockDeclRefExpr instead of a
1127 // DeclRefExpr. This ensures the value is treated as a copy-in snapshot when
1128 // the block is formed.
Steve Naroffd6163f32008-09-05 22:11:13 +00001129 //
Chris Lattnerb2ebd482008-10-20 05:16:36 +00001130 // We do not do this for things like enum constants, global variables, etc,
1131 // as they do not get snapshotted.
1132 //
1133 if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001134 QualType ExprTy = VD->getType().getNonReferenceType();
Steve Naroff52059382008-10-10 01:28:17 +00001135 // The BlocksAttr indicates the variable is bound by-reference.
1136 if (VD->getAttr<BlocksAttr>())
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001137 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001138
Steve Naroff52059382008-10-10 01:28:17 +00001139 // Variable will be bound by-copy, make it const within the closure.
Eli Friedman9c2b33f2009-03-22 23:00:19 +00001140 ExprTy.addConst();
1141 return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false));
Steve Naroff52059382008-10-10 01:28:17 +00001142 }
1143 // If this reference is not in a block or if the referenced variable is
1144 // within the block, create a normal DeclRefExpr.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001145
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001146 bool TypeDependent = false;
Douglas Gregora5d84612008-12-10 20:57:37 +00001147 bool ValueDependent = false;
1148 if (getLangOptions().CPlusPlus) {
1149 // C++ [temp.dep.expr]p3:
1150 // An id-expression is type-dependent if it contains:
1151 // - an identifier that was declared with a dependent type,
1152 if (VD->getType()->isDependentType())
1153 TypeDependent = true;
1154 // - FIXME: a template-id that is dependent,
1155 // - a conversion-function-id that specifies a dependent type,
1156 else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1157 Name.getCXXNameType()->isDependentType())
1158 TypeDependent = true;
1159 // - a nested-name-specifier that contains a class-name that
1160 // names a dependent type.
1161 else if (SS && !SS->isEmpty()) {
Douglas Gregor734b4ba2009-03-19 00:18:19 +00001162 for (DeclContext *DC = computeDeclContext(*SS);
Douglas Gregora5d84612008-12-10 20:57:37 +00001163 DC; DC = DC->getParent()) {
1164 // FIXME: could stop early at namespace scope.
Douglas Gregor723d3332009-01-07 00:43:41 +00001165 if (DC->isRecord()) {
Douglas Gregora5d84612008-12-10 20:57:37 +00001166 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1167 if (Context.getTypeDeclType(Record)->isDependentType()) {
1168 TypeDependent = true;
1169 break;
1170 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001171 }
1172 }
1173 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001174
Douglas Gregora5d84612008-12-10 20:57:37 +00001175 // C++ [temp.dep.constexpr]p2:
1176 //
1177 // An identifier is value-dependent if it is:
1178 // - a name declared with a dependent type,
1179 if (TypeDependent)
1180 ValueDependent = true;
1181 // - the name of a non-type template parameter,
1182 else if (isa<NonTypeTemplateParmDecl>(VD))
1183 ValueDependent = true;
1184 // - a constant with integral or enumeration type and is
1185 // initialized with an expression that is value-dependent
1186 // (FIXME!).
1187 }
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001188
Sebastian Redlcd883f72009-01-18 18:53:16 +00001189 return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1190 TypeDependent, ValueDependent, SS));
Chris Lattner4b009652007-07-25 00:24:17 +00001191}
1192
Sebastian Redlcd883f72009-01-18 18:53:16 +00001193Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1194 tok::TokenKind Kind) {
Chris Lattner69909292008-08-10 01:53:14 +00001195 PredefinedExpr::IdentType IT;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001196
Chris Lattner4b009652007-07-25 00:24:17 +00001197 switch (Kind) {
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001198 default: assert(0 && "Unknown simple primary expr!");
Chris Lattner69909292008-08-10 01:53:14 +00001199 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1200 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1201 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001202 }
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001203
Chris Lattner7e637512008-01-12 08:14:25 +00001204 // Pre-defined identifiers are of type char[x], where x is the length of the
1205 // string.
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001206 unsigned Length;
Chris Lattnere5cb5862008-12-04 23:50:19 +00001207 if (FunctionDecl *FD = getCurFunctionDecl())
1208 Length = FD->getIdentifier()->getLength();
Chris Lattnerbce5e4f2008-12-12 05:05:20 +00001209 else if (ObjCMethodDecl *MD = getCurMethodDecl())
1210 Length = MD->getSynthesizedMethodSize();
1211 else {
1212 Diag(Loc, diag::ext_predef_outside_function);
1213 // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1214 Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1215 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001216
1217
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001218 llvm::APInt LengthI(32, Length + 1);
Chris Lattnere12ca5d2008-01-12 18:39:25 +00001219 QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
Chris Lattnerfc9511c2008-01-12 19:32:28 +00001220 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
Steve Naroff774e4152009-01-21 00:14:39 +00001221 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattner4b009652007-07-25 00:24:17 +00001222}
1223
Sebastian Redlcd883f72009-01-18 18:53:16 +00001224Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Chris Lattner4b009652007-07-25 00:24:17 +00001225 llvm::SmallString<16> CharBuffer;
1226 CharBuffer.resize(Tok.getLength());
1227 const char *ThisTokBegin = &CharBuffer[0];
1228 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001229
Chris Lattner4b009652007-07-25 00:24:17 +00001230 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1231 Tok.getLocation(), PP);
1232 if (Literal.hadError())
Sebastian Redlcd883f72009-01-18 18:53:16 +00001233 return ExprError();
Chris Lattner6b22fb72008-03-01 08:32:21 +00001234
1235 QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1236
Sebastian Redl75324932009-01-20 22:23:13 +00001237 return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1238 Literal.isWide(),
1239 type, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001240}
1241
Sebastian Redlcd883f72009-01-18 18:53:16 +00001242Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1243 // Fast path for a single digit (which is quite common). A single digit
Chris Lattner4b009652007-07-25 00:24:17 +00001244 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1245 if (Tok.getLength() == 1) {
Chris Lattnerc374f8b2009-01-26 22:36:52 +00001246 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Chris Lattnerfd5f1432009-01-16 07:10:29 +00001247 unsigned IntSize = Context.Target.getIntWidth();
Steve Naroff774e4152009-01-21 00:14:39 +00001248 return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
Steve Naroffe5f128a2009-01-20 19:53:53 +00001249 Context.IntTy, Tok.getLocation()));
Chris Lattner4b009652007-07-25 00:24:17 +00001250 }
Ted Kremenekdbde2282009-01-13 23:19:12 +00001251
Chris Lattner4b009652007-07-25 00:24:17 +00001252 llvm::SmallString<512> IntegerBuffer;
Chris Lattner46d91342008-09-30 20:53:45 +00001253 // Add padding so that NumericLiteralParser can overread by one character.
1254 IntegerBuffer.resize(Tok.getLength()+1);
Chris Lattner4b009652007-07-25 00:24:17 +00001255 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlcd883f72009-01-18 18:53:16 +00001256
Chris Lattner4b009652007-07-25 00:24:17 +00001257 // Get the spelling of the token, which eliminates trigraphs, etc.
1258 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001259
Chris Lattner4b009652007-07-25 00:24:17 +00001260 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1261 Tok.getLocation(), PP);
1262 if (Literal.hadError)
Sebastian Redlcd883f72009-01-18 18:53:16 +00001263 return ExprError();
1264
Chris Lattner1de66eb2007-08-26 03:42:43 +00001265 Expr *Res;
Sebastian Redlcd883f72009-01-18 18:53:16 +00001266
Chris Lattner1de66eb2007-08-26 03:42:43 +00001267 if (Literal.isFloatingLiteral()) {
Chris Lattner858eece2007-09-22 18:29:59 +00001268 QualType Ty;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001269 if (Literal.isFloat)
Chris Lattner858eece2007-09-22 18:29:59 +00001270 Ty = Context.FloatTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001271 else if (!Literal.isLong)
Chris Lattner858eece2007-09-22 18:29:59 +00001272 Ty = Context.DoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001273 else
Chris Lattnerfc18dcc2008-03-08 08:52:55 +00001274 Ty = Context.LongDoubleTy;
Chris Lattner2a674dc2008-06-30 18:32:54 +00001275
1276 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1277
Ted Kremenekddedbe22007-11-29 00:56:49 +00001278 // isExact will be set by GetFloatValue().
1279 bool isExact = false;
Sebastian Redl75324932009-01-20 22:23:13 +00001280 Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
1281 &isExact, Ty, Tok.getLocation());
Sebastian Redlcd883f72009-01-18 18:53:16 +00001282
Chris Lattner1de66eb2007-08-26 03:42:43 +00001283 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlcd883f72009-01-18 18:53:16 +00001284 return ExprError();
Chris Lattner1de66eb2007-08-26 03:42:43 +00001285 } else {
Chris Lattner48d7f382008-04-02 04:24:33 +00001286 QualType Ty;
Chris Lattner4b009652007-07-25 00:24:17 +00001287
Neil Booth7421e9c2007-08-29 22:00:19 +00001288 // long long is a C99 feature.
1289 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
Neil Booth9bd47082007-08-29 22:13:52 +00001290 Literal.isLongLong)
Neil Booth7421e9c2007-08-29 22:00:19 +00001291 Diag(Tok.getLocation(), diag::ext_longlong);
1292
Chris Lattner4b009652007-07-25 00:24:17 +00001293 // Get the value in the widest-possible width.
Chris Lattner8cd0e932008-03-05 18:54:05 +00001294 llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
Sebastian Redlcd883f72009-01-18 18:53:16 +00001295
Chris Lattner4b009652007-07-25 00:24:17 +00001296 if (Literal.GetIntegerValue(ResultVal)) {
1297 // If this value didn't fit into uintmax_t, warn and force to ull.
1298 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner48d7f382008-04-02 04:24:33 +00001299 Ty = Context.UnsignedLongLongTy;
1300 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner8cd0e932008-03-05 18:54:05 +00001301 "long long is not intmax_t?");
Chris Lattner4b009652007-07-25 00:24:17 +00001302 } else {
1303 // If this value fits into a ULL, try to figure out what else it fits into
1304 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlcd883f72009-01-18 18:53:16 +00001305
Chris Lattner4b009652007-07-25 00:24:17 +00001306 // Octal, Hexadecimal, and integers with a U suffix are allowed to
1307 // be an unsigned int.
1308 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1309
1310 // Check from smallest to largest, picking the smallest type we can.
Chris Lattnere4068872008-05-09 05:59:00 +00001311 unsigned Width = 0;
Chris Lattner98540b62007-08-23 21:58:08 +00001312 if (!Literal.isLong && !Literal.isLongLong) {
1313 // Are int/unsigned possibilities?
Chris Lattnere4068872008-05-09 05:59:00 +00001314 unsigned IntSize = Context.Target.getIntWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001315
Chris Lattner4b009652007-07-25 00:24:17 +00001316 // Does it fit in a unsigned int?
1317 if (ResultVal.isIntN(IntSize)) {
1318 // Does it fit in a signed int?
1319 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001320 Ty = Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001321 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001322 Ty = Context.UnsignedIntTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001323 Width = IntSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001324 }
Chris Lattner4b009652007-07-25 00:24:17 +00001325 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001326
Chris Lattner4b009652007-07-25 00:24:17 +00001327 // Are long/unsigned long possibilities?
Chris Lattner48d7f382008-04-02 04:24:33 +00001328 if (Ty.isNull() && !Literal.isLongLong) {
Chris Lattnere4068872008-05-09 05:59:00 +00001329 unsigned LongSize = Context.Target.getLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001330
Chris Lattner4b009652007-07-25 00:24:17 +00001331 // Does it fit in a unsigned long?
1332 if (ResultVal.isIntN(LongSize)) {
1333 // Does it fit in a signed long?
1334 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001335 Ty = Context.LongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001336 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001337 Ty = Context.UnsignedLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001338 Width = LongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001339 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001340 }
1341
Chris Lattner4b009652007-07-25 00:24:17 +00001342 // Finally, check long long if needed.
Chris Lattner48d7f382008-04-02 04:24:33 +00001343 if (Ty.isNull()) {
Chris Lattnere4068872008-05-09 05:59:00 +00001344 unsigned LongLongSize = Context.Target.getLongLongWidth();
Sebastian Redlcd883f72009-01-18 18:53:16 +00001345
Chris Lattner4b009652007-07-25 00:24:17 +00001346 // Does it fit in a unsigned long long?
1347 if (ResultVal.isIntN(LongLongSize)) {
1348 // Does it fit in a signed long long?
1349 if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
Chris Lattner48d7f382008-04-02 04:24:33 +00001350 Ty = Context.LongLongTy;
Chris Lattner4b009652007-07-25 00:24:17 +00001351 else if (AllowUnsigned)
Chris Lattner48d7f382008-04-02 04:24:33 +00001352 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001353 Width = LongLongSize;
Chris Lattner4b009652007-07-25 00:24:17 +00001354 }
1355 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001356
Chris Lattner4b009652007-07-25 00:24:17 +00001357 // If we still couldn't decide a type, we probably have something that
1358 // does not fit in a signed long long, but has no U suffix.
Chris Lattner48d7f382008-04-02 04:24:33 +00001359 if (Ty.isNull()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001360 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner48d7f382008-04-02 04:24:33 +00001361 Ty = Context.UnsignedLongLongTy;
Chris Lattnere4068872008-05-09 05:59:00 +00001362 Width = Context.Target.getLongLongWidth();
Chris Lattner4b009652007-07-25 00:24:17 +00001363 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001364
Chris Lattnere4068872008-05-09 05:59:00 +00001365 if (ResultVal.getBitWidth() != Width)
1366 ResultVal.trunc(Width);
Chris Lattner4b009652007-07-25 00:24:17 +00001367 }
Sebastian Redl75324932009-01-20 22:23:13 +00001368 Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
Chris Lattner4b009652007-07-25 00:24:17 +00001369 }
Sebastian Redlcd883f72009-01-18 18:53:16 +00001370
Chris Lattner1de66eb2007-08-26 03:42:43 +00001371 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1372 if (Literal.isImaginary)
Steve Naroff774e4152009-01-21 00:14:39 +00001373 Res = new (Context) ImaginaryLiteral(Res,
1374 Context.getComplexType(Res->getType()));
Sebastian Redlcd883f72009-01-18 18:53:16 +00001375
1376 return Owned(Res);
Chris Lattner4b009652007-07-25 00:24:17 +00001377}
1378
Sebastian Redlcd883f72009-01-18 18:53:16 +00001379Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1380 SourceLocation R, ExprArg Val) {
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00001381 Expr *E = Val.takeAs<Expr>();
Chris Lattner48d7f382008-04-02 04:24:33 +00001382 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Naroff774e4152009-01-21 00:14:39 +00001383 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattner4b009652007-07-25 00:24:17 +00001384}
1385
1386/// The UsualUnaryConversions() function is *not* called by this routine.
1387/// See C99 6.3.2.1p[2-4] for more details.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001388bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001389 SourceLocation OpLoc,
1390 const SourceRange &ExprRange,
1391 bool isSizeof) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001392 if (exprType->isDependentType())
1393 return false;
1394
Chris Lattner4b009652007-07-25 00:24:17 +00001395 // C99 6.5.3.4p1:
Chris Lattner159fe082009-01-24 19:46:37 +00001396 if (isa<FunctionType>(exprType)) {
Chris Lattner95933c12009-04-24 00:30:45 +00001397 // alignof(function) is allowed as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001398 if (isSizeof)
1399 Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1400 return false;
1401 }
1402
Chris Lattner95933c12009-04-24 00:30:45 +00001403 // Allow sizeof(void)/alignof(void) as an extension.
Chris Lattner159fe082009-01-24 19:46:37 +00001404 if (exprType->isVoidType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001405 Diag(OpLoc, diag::ext_sizeof_void_type)
1406 << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
Chris Lattner159fe082009-01-24 19:46:37 +00001407 return false;
1408 }
Chris Lattnere1127c42009-04-21 19:55:16 +00001409
Chris Lattner95933c12009-04-24 00:30:45 +00001410 if (RequireCompleteType(OpLoc, exprType,
1411 isSizeof ? diag::err_sizeof_incomplete_type :
1412 diag::err_alignof_incomplete_type,
1413 ExprRange))
1414 return true;
1415
1416 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
Fariborz Jahanianbf2b0952009-04-24 17:34:33 +00001417 if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
Chris Lattner95933c12009-04-24 00:30:45 +00001418 Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
Chris Lattnerf3ce8572009-04-24 22:30:50 +00001419 << exprType << isSizeof << ExprRange;
1420 return true;
Chris Lattnere1127c42009-04-21 19:55:16 +00001421 }
1422
Chris Lattner95933c12009-04-24 00:30:45 +00001423 return false;
Chris Lattner4b009652007-07-25 00:24:17 +00001424}
1425
Chris Lattner8d9f7962009-01-24 20:17:12 +00001426bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1427 const SourceRange &ExprRange) {
1428 E = E->IgnoreParens();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001429
Chris Lattner8d9f7962009-01-24 20:17:12 +00001430 // alignof decl is always ok.
1431 if (isa<DeclRefExpr>(E))
1432 return false;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001433
1434 // Cannot know anything else if the expression is dependent.
1435 if (E->isTypeDependent())
1436 return false;
1437
Douglas Gregor531434b2009-05-02 02:18:30 +00001438 if (E->getBitField()) {
1439 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1440 return true;
Chris Lattner8d9f7962009-01-24 20:17:12 +00001441 }
Douglas Gregor531434b2009-05-02 02:18:30 +00001442
1443 // Alignment of a field access is always okay, so long as it isn't a
1444 // bit-field.
1445 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1446 if (dyn_cast<FieldDecl>(ME->getMemberDecl()))
1447 return false;
1448
Chris Lattner8d9f7962009-01-24 20:17:12 +00001449 return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1450}
1451
Douglas Gregor396f1142009-03-13 21:01:28 +00001452/// \brief Build a sizeof or alignof expression given a type operand.
1453Action::OwningExprResult
1454Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1455 bool isSizeOf, SourceRange R) {
1456 if (T.isNull())
1457 return ExprError();
1458
1459 if (!T->isDependentType() &&
1460 CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1461 return ExprError();
1462
1463 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1464 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1465 Context.getSizeType(), OpLoc,
1466 R.getEnd()));
1467}
1468
1469/// \brief Build a sizeof or alignof expression given an expression
1470/// operand.
1471Action::OwningExprResult
1472Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1473 bool isSizeOf, SourceRange R) {
1474 // Verify that the operand is valid.
1475 bool isInvalid = false;
1476 if (E->isTypeDependent()) {
1477 // Delay type-checking for type-dependent expressions.
1478 } else if (!isSizeOf) {
1479 isInvalid = CheckAlignOfExpr(E, OpLoc, R);
Douglas Gregor531434b2009-05-02 02:18:30 +00001480 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Douglas Gregor396f1142009-03-13 21:01:28 +00001481 Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1482 isInvalid = true;
1483 } else {
1484 isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1485 }
1486
1487 if (isInvalid)
1488 return ExprError();
1489
1490 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1491 return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1492 Context.getSizeType(), OpLoc,
1493 R.getEnd()));
1494}
1495
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001496/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1497/// the same for @c alignof and @c __alignof
1498/// Note that the ArgRange is invalid if isType is false.
Sebastian Redl8b769972009-01-19 00:08:26 +00001499Action::OwningExprResult
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001500Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1501 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner4b009652007-07-25 00:24:17 +00001502 // If error parsing type, ignore.
Sebastian Redl8b769972009-01-19 00:08:26 +00001503 if (TyOrEx == 0) return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00001504
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001505 if (isType) {
Douglas Gregor396f1142009-03-13 21:01:28 +00001506 QualType ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1507 return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1508 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001509
Douglas Gregor396f1142009-03-13 21:01:28 +00001510 // Get the end location.
1511 Expr *ArgEx = (Expr *)TyOrEx;
1512 Action::OwningExprResult Result
1513 = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1514
1515 if (Result.isInvalid())
1516 DeleteExpr(ArgEx);
1517
1518 return move(Result);
Chris Lattner4b009652007-07-25 00:24:17 +00001519}
1520
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001521QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001522 if (V->isTypeDependent())
1523 return Context.DependentTy;
Chris Lattner03931a72007-08-24 21:16:53 +00001524
Chris Lattnera16e42d2007-08-26 05:39:26 +00001525 // These operators return the element type of a complex type.
Chris Lattner03931a72007-08-24 21:16:53 +00001526 if (const ComplexType *CT = V->getType()->getAsComplexType())
1527 return CT->getElementType();
Chris Lattnera16e42d2007-08-26 05:39:26 +00001528
1529 // Otherwise they pass through real integer and floating point types here.
1530 if (V->getType()->isArithmeticType())
1531 return V->getType();
1532
1533 // Reject anything else.
Chris Lattner57e5f7e2009-02-17 08:12:06 +00001534 Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1535 << (isReal ? "__real" : "__imag");
Chris Lattnera16e42d2007-08-26 05:39:26 +00001536 return QualType();
Chris Lattner03931a72007-08-24 21:16:53 +00001537}
1538
1539
Chris Lattner4b009652007-07-25 00:24:17 +00001540
Sebastian Redl8b769972009-01-19 00:08:26 +00001541Action::OwningExprResult
1542Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1543 tok::TokenKind Kind, ExprArg Input) {
1544 Expr *Arg = (Expr *)Input.get();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001545
Chris Lattner4b009652007-07-25 00:24:17 +00001546 UnaryOperator::Opcode Opc;
1547 switch (Kind) {
1548 default: assert(0 && "Unknown unary op!");
1549 case tok::plusplus: Opc = UnaryOperator::PostInc; break;
1550 case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1551 }
Sebastian Redl8b769972009-01-19 00:08:26 +00001552
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001553 if (getLangOptions().CPlusPlus &&
1554 (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1555 // Which overloaded operator?
Sebastian Redl8b769972009-01-19 00:08:26 +00001556 OverloadedOperatorKind OverOp =
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001557 (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1558
1559 // C++ [over.inc]p1:
1560 //
1561 // [...] If the function is a member function with one
1562 // parameter (which shall be of type int) or a non-member
1563 // function with two parameters (the second of which shall be
1564 // of type int), it defines the postfix increment operator ++
1565 // for objects of that type. When the postfix increment is
1566 // called as a result of using the ++ operator, the int
1567 // argument will have value zero.
1568 Expr *Args[2] = {
1569 Arg,
Steve Naroff774e4152009-01-21 00:14:39 +00001570 new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1571 /*isSigned=*/true), Context.IntTy, SourceLocation())
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001572 };
1573
1574 // Build the candidate set for overloading
1575 OverloadCandidateSet CandidateSet;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001576 AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001577
1578 // Perform overload resolution.
1579 OverloadCandidateSet::iterator Best;
1580 switch (BestViableFunction(CandidateSet, Best)) {
1581 case OR_Success: {
1582 // We found a built-in operator or an overloaded operator.
1583 FunctionDecl *FnDecl = Best->Function;
1584
1585 if (FnDecl) {
1586 // We matched an overloaded operator. Build a call to that
1587 // operator.
1588
1589 // Convert the arguments.
1590 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1591 if (PerformObjectArgumentInitialization(Arg, Method))
Sebastian Redl8b769972009-01-19 00:08:26 +00001592 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001593 } else {
1594 // Convert the arguments.
Sebastian Redl8b769972009-01-19 00:08:26 +00001595 if (PerformCopyInitialization(Arg,
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001596 FnDecl->getParamDecl(0)->getType(),
1597 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001598 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001599 }
1600
1601 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001602 QualType ResultTy
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001603 = FnDecl->getType()->getAsFunctionType()->getResultType();
1604 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001605
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001606 // Build the actual expression node.
Steve Naroff774e4152009-01-21 00:14:39 +00001607 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Mike Stump6d8e5732009-02-19 02:54:59 +00001608 SourceLocation());
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001609 UsualUnaryConversions(FnExpr);
1610
Sebastian Redl8b769972009-01-19 00:08:26 +00001611 Input.release();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001612 return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1613 Args, 2, ResultTy,
1614 OpLoc));
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001615 } else {
1616 // We matched a built-in operator. Convert the arguments, then
1617 // break out so that we will build the appropriate built-in
1618 // operator node.
1619 if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1620 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001621 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001622
1623 break;
Sebastian Redl8b769972009-01-19 00:08:26 +00001624 }
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001625 }
1626
1627 case OR_No_Viable_Function:
1628 // No viable function; fall through to handling this as a
1629 // built-in operator, which will produce an error message for us.
1630 break;
1631
1632 case OR_Ambiguous:
1633 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
1634 << UnaryOperator::getOpcodeStr(Opc)
1635 << Arg->getSourceRange();
1636 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001637 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001638
1639 case OR_Deleted:
1640 Diag(OpLoc, diag::err_ovl_deleted_oper)
1641 << Best->Function->isDeleted()
1642 << UnaryOperator::getOpcodeStr(Opc)
1643 << Arg->getSourceRange();
1644 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1645 return ExprError();
Douglas Gregor4f6904d2008-11-19 15:42:04 +00001646 }
1647
1648 // Either we found no viable overloaded operator or we matched a
1649 // built-in operator. In either case, fall through to trying to
1650 // build a built-in operation.
1651 }
1652
Sebastian Redl0440c8c2008-12-20 09:35:34 +00001653 QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1654 Opc == UnaryOperator::PostInc);
Chris Lattner4b009652007-07-25 00:24:17 +00001655 if (result.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00001656 return ExprError();
1657 Input.release();
Steve Naroff774e4152009-01-21 00:14:39 +00001658 return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001659}
1660
Sebastian Redl8b769972009-01-19 00:08:26 +00001661Action::OwningExprResult
1662Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1663 ExprArg Idx, SourceLocation RLoc) {
1664 Expr *LHSExp = static_cast<Expr*>(Base.get()),
1665 *RHSExp = static_cast<Expr*>(Idx.get());
Chris Lattner4b009652007-07-25 00:24:17 +00001666
Douglas Gregor80723c52008-11-19 17:17:41 +00001667 if (getLangOptions().CPlusPlus &&
Sebastian Redl8b769972009-01-19 00:08:26 +00001668 (LHSExp->getType()->isRecordType() ||
Eli Friedmane658bf52008-12-15 22:34:21 +00001669 LHSExp->getType()->isEnumeralType() ||
1670 RHSExp->getType()->isRecordType() ||
1671 RHSExp->getType()->isEnumeralType())) {
Douglas Gregor80723c52008-11-19 17:17:41 +00001672 // Add the appropriate overloaded operators (C++ [over.match.oper])
1673 // to the candidate set.
1674 OverloadCandidateSet CandidateSet;
1675 Expr *Args[2] = { LHSExp, RHSExp };
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001676 AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1677 SourceRange(LLoc, RLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00001678
Douglas Gregor80723c52008-11-19 17:17:41 +00001679 // Perform overload resolution.
1680 OverloadCandidateSet::iterator Best;
1681 switch (BestViableFunction(CandidateSet, Best)) {
1682 case OR_Success: {
1683 // We found a built-in operator or an overloaded operator.
1684 FunctionDecl *FnDecl = Best->Function;
1685
1686 if (FnDecl) {
1687 // We matched an overloaded operator. Build a call to that
1688 // operator.
1689
1690 // Convert the arguments.
1691 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1692 if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1693 PerformCopyInitialization(RHSExp,
1694 FnDecl->getParamDecl(0)->getType(),
1695 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001696 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001697 } else {
1698 // Convert the arguments.
1699 if (PerformCopyInitialization(LHSExp,
1700 FnDecl->getParamDecl(0)->getType(),
1701 "passing") ||
1702 PerformCopyInitialization(RHSExp,
1703 FnDecl->getParamDecl(1)->getType(),
1704 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001705 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001706 }
1707
1708 // Determine the result type
Sebastian Redl8b769972009-01-19 00:08:26 +00001709 QualType ResultTy
Douglas Gregor80723c52008-11-19 17:17:41 +00001710 = FnDecl->getType()->getAsFunctionType()->getResultType();
1711 ResultTy = ResultTy.getNonReferenceType();
Sebastian Redl8b769972009-01-19 00:08:26 +00001712
Douglas Gregor80723c52008-11-19 17:17:41 +00001713 // Build the actual expression node.
Mike Stump9afab102009-02-19 03:04:26 +00001714 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1715 SourceLocation());
Douglas Gregor80723c52008-11-19 17:17:41 +00001716 UsualUnaryConversions(FnExpr);
1717
Sebastian Redl8b769972009-01-19 00:08:26 +00001718 Base.release();
1719 Idx.release();
Douglas Gregor00fe3f62009-03-13 18:40:31 +00001720 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1721 FnExpr, Args, 2,
Steve Naroff774e4152009-01-21 00:14:39 +00001722 ResultTy, LLoc));
Douglas Gregor80723c52008-11-19 17:17:41 +00001723 } else {
1724 // We matched a built-in operator. Convert the arguments, then
1725 // break out so that we will build the appropriate built-in
1726 // operator node.
1727 if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1728 "passing") ||
1729 PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1730 "passing"))
Sebastian Redl8b769972009-01-19 00:08:26 +00001731 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001732
1733 break;
1734 }
1735 }
1736
1737 case OR_No_Viable_Function:
1738 // No viable function; fall through to handling this as a
1739 // built-in operator, which will produce an error message for us.
1740 break;
1741
1742 case OR_Ambiguous:
1743 Diag(LLoc, diag::err_ovl_ambiguous_oper)
1744 << "[]"
1745 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1746 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Sebastian Redl8b769972009-01-19 00:08:26 +00001747 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00001748
1749 case OR_Deleted:
1750 Diag(LLoc, diag::err_ovl_deleted_oper)
1751 << Best->Function->isDeleted()
1752 << "[]"
1753 << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1754 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1755 return ExprError();
Douglas Gregor80723c52008-11-19 17:17:41 +00001756 }
1757
1758 // Either we found no viable overloaded operator or we matched a
1759 // built-in operator. In either case, fall through to trying to
1760 // build a built-in operation.
1761 }
1762
Chris Lattner4b009652007-07-25 00:24:17 +00001763 // Perform default conversions.
1764 DefaultFunctionArrayConversion(LHSExp);
1765 DefaultFunctionArrayConversion(RHSExp);
Sebastian Redl8b769972009-01-19 00:08:26 +00001766
Chris Lattner4b009652007-07-25 00:24:17 +00001767 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1768
1769 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattner0d9bcea2007-08-30 17:45:32 +00001770 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump9afab102009-02-19 03:04:26 +00001771 // in the subscript position. As a result, we need to derive the array base
Chris Lattner4b009652007-07-25 00:24:17 +00001772 // and index from the expression types.
1773 Expr *BaseExpr, *IndexExpr;
1774 QualType ResultType;
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001775 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1776 BaseExpr = LHSExp;
1777 IndexExpr = RHSExp;
1778 ResultType = Context.DependentTy;
1779 } else if (const PointerType *PTy = LHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001780 BaseExpr = LHSExp;
1781 IndexExpr = RHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001782 ResultType = PTy->getPointeeType();
Chris Lattner7931f4a2007-07-31 16:53:04 +00001783 } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001784 // Handle the uncommon case of "123[Ptr]".
1785 BaseExpr = RHSExp;
1786 IndexExpr = LHSExp;
Chris Lattner4b009652007-07-25 00:24:17 +00001787 ResultType = PTy->getPointeeType();
Chris Lattnere35a1042007-07-31 19:29:30 +00001788 } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1789 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner4b009652007-07-25 00:24:17 +00001790 IndexExpr = RHSExp;
Nate Begeman57385472009-01-18 00:45:31 +00001791
Chris Lattner4b009652007-07-25 00:24:17 +00001792 // FIXME: need to deal with const...
1793 ResultType = VTy->getElementType();
Eli Friedmand4614072009-04-25 23:46:54 +00001794 } else if (LHSTy->isArrayType()) {
1795 // If we see an array that wasn't promoted by
1796 // DefaultFunctionArrayConversion, it must be an array that
1797 // wasn't promoted because of the C90 rule that doesn't
1798 // allow promoting non-lvalue arrays. Warn, then
1799 // force the promotion here.
1800 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1801 LHSExp->getSourceRange();
1802 ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1803 LHSTy = LHSExp->getType();
1804
1805 BaseExpr = LHSExp;
1806 IndexExpr = RHSExp;
1807 ResultType = LHSTy->getAsPointerType()->getPointeeType();
1808 } else if (RHSTy->isArrayType()) {
1809 // Same as previous, except for 123[f().a] case
1810 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1811 RHSExp->getSourceRange();
1812 ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1813 RHSTy = RHSExp->getType();
1814
1815 BaseExpr = RHSExp;
1816 IndexExpr = LHSExp;
1817 ResultType = RHSTy->getAsPointerType()->getPointeeType();
Chris Lattner4b009652007-07-25 00:24:17 +00001818 } else {
Chris Lattner7264d212009-04-25 22:50:55 +00001819 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1820 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redl8b769972009-01-19 00:08:26 +00001821 }
Chris Lattner4b009652007-07-25 00:24:17 +00001822 // C99 6.5.2.1p1
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00001823 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner7264d212009-04-25 22:50:55 +00001824 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1825 << IndexExpr->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00001826
Douglas Gregor05e28f62009-03-24 19:52:54 +00001827 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1828 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1829 // type. Note that Functions are not objects, and that (in C99 parlance)
1830 // incomplete types are not object types.
1831 if (ResultType->isFunctionType()) {
1832 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1833 << ResultType << BaseExpr->getSourceRange();
1834 return ExprError();
1835 }
Chris Lattner95933c12009-04-24 00:30:45 +00001836
Douglas Gregor05e28f62009-03-24 19:52:54 +00001837 if (!ResultType->isDependentType() &&
Chris Lattner95933c12009-04-24 00:30:45 +00001838 RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type,
Douglas Gregor05e28f62009-03-24 19:52:54 +00001839 BaseExpr->getSourceRange()))
1840 return ExprError();
Chris Lattner95933c12009-04-24 00:30:45 +00001841
1842 // Diagnose bad cases where we step over interface counts.
1843 if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1844 Diag(LLoc, diag::err_subscript_nonfragile_interface)
1845 << ResultType << BaseExpr->getSourceRange();
1846 return ExprError();
1847 }
1848
Sebastian Redl8b769972009-01-19 00:08:26 +00001849 Base.release();
1850 Idx.release();
Mike Stump9afab102009-02-19 03:04:26 +00001851 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
Steve Naroff774e4152009-01-21 00:14:39 +00001852 ResultType, RLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00001853}
1854
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001855QualType Sema::
Nate Begemanaf6ed502008-04-18 23:10:10 +00001856CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001857 IdentifierInfo &CompName, SourceLocation CompLoc) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00001858 const ExtVectorType *vecType = baseType->getAsExtVectorType();
Nate Begemanc8e51f82008-05-09 06:41:27 +00001859
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001860 // The vector accessor can't exceed the number of elements.
1861 const char *compStr = CompName.getName();
Nate Begeman1486b502009-01-18 01:47:54 +00001862
Mike Stump9afab102009-02-19 03:04:26 +00001863 // This flag determines whether or not the component is one of the four
Nate Begeman1486b502009-01-18 01:47:54 +00001864 // special names that indicate a subset of exactly half the elements are
1865 // to be selected.
1866 bool HalvingSwizzle = false;
Mike Stump9afab102009-02-19 03:04:26 +00001867
Nate Begeman1486b502009-01-18 01:47:54 +00001868 // This flag determines whether or not CompName has an 's' char prefix,
1869 // indicating that it is a string of hex values to be used as vector indices.
1870 bool HexSwizzle = *compStr == 's';
Nate Begemanc8e51f82008-05-09 06:41:27 +00001871
1872 // Check that we've found one of the special components, or that the component
1873 // names must come from the same set.
Mike Stump9afab102009-02-19 03:04:26 +00001874 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
Nate Begeman1486b502009-01-18 01:47:54 +00001875 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1876 HalvingSwizzle = true;
Nate Begemanc8e51f82008-05-09 06:41:27 +00001877 } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001878 do
1879 compStr++;
1880 while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
Nate Begeman1486b502009-01-18 01:47:54 +00001881 } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
Chris Lattner9096b792007-08-02 22:33:49 +00001882 do
1883 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001884 while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
Chris Lattner9096b792007-08-02 22:33:49 +00001885 }
Nate Begeman1486b502009-01-18 01:47:54 +00001886
Mike Stump9afab102009-02-19 03:04:26 +00001887 if (!HalvingSwizzle && *compStr) {
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001888 // We didn't get to the end of the string. This means the component names
1889 // didn't come from the same set *or* we encountered an illegal name.
Chris Lattner8ba580c2008-11-19 05:08:23 +00001890 Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1891 << std::string(compStr,compStr+1) << SourceRange(CompLoc);
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001892 return QualType();
1893 }
Mike Stump9afab102009-02-19 03:04:26 +00001894
Nate Begeman1486b502009-01-18 01:47:54 +00001895 // Ensure no component accessor exceeds the width of the vector type it
1896 // operates on.
1897 if (!HalvingSwizzle) {
1898 compStr = CompName.getName();
1899
1900 if (HexSwizzle)
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001901 compStr++;
Nate Begeman1486b502009-01-18 01:47:54 +00001902
1903 while (*compStr) {
1904 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1905 Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1906 << baseType << SourceRange(CompLoc);
1907 return QualType();
1908 }
1909 }
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001910 }
Nate Begemanc8e51f82008-05-09 06:41:27 +00001911
Nate Begeman1486b502009-01-18 01:47:54 +00001912 // If this is a halving swizzle, verify that the base type has an even
1913 // number of elements.
1914 if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00001915 Diag(OpLoc, diag::err_ext_vector_component_requires_even)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001916 << baseType << SourceRange(CompLoc);
Nate Begemanc8e51f82008-05-09 06:41:27 +00001917 return QualType();
1918 }
Mike Stump9afab102009-02-19 03:04:26 +00001919
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001920 // The component accessor looks fine - now we need to compute the actual type.
Mike Stump9afab102009-02-19 03:04:26 +00001921 // The vector type is implied by the component accessor. For example,
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001922 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
Nate Begeman1486b502009-01-18 01:47:54 +00001923 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
Nate Begemanc8e51f82008-05-09 06:41:27 +00001924 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
Nate Begeman1486b502009-01-18 01:47:54 +00001925 unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1926 : CompName.getLength();
1927 if (HexSwizzle)
1928 CompSize--;
1929
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001930 if (CompSize == 1)
1931 return vecType->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00001932
Nate Begemanaf6ed502008-04-18 23:10:10 +00001933 QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
Mike Stump9afab102009-02-19 03:04:26 +00001934 // Now look up the TypeDefDecl from the vector type. Without this,
Nate Begemanaf6ed502008-04-18 23:10:10 +00001935 // diagostics look bad. We want extended vector types to appear built-in.
1936 for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1937 if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1938 return Context.getTypedefType(ExtVectorDecls[i]);
Steve Naroff82113e32007-07-29 16:33:31 +00001939 }
1940 return VT; // should never get here (a typedef type should always be found).
Steve Naroff1b8a46c2007-07-27 22:15:19 +00001941}
1942
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001943static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1944 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001945 const Selector &Sel,
1946 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001947
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001948 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Context, &Member))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001949 return PD;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001950 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Context, Sel))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001951 return OMD;
1952
1953 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1954 E = PDecl->protocol_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001955 if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1956 Context))
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001957 return D;
1958 }
1959 return 0;
1960}
1961
1962static Decl *FindGetterNameDecl(const ObjCQualifiedIdType *QIdTy,
1963 IdentifierInfo &Member,
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001964 const Selector &Sel,
1965 ASTContext &Context) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001966 // Check protocols on qualified interfaces.
1967 Decl *GDecl = 0;
1968 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1969 E = QIdTy->qual_end(); I != E; ++I) {
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001970 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Context, &Member)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001971 GDecl = PD;
1972 break;
1973 }
1974 // Also must look for a getter name which uses property syntax.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001975 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Context, Sel)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001976 GDecl = OMD;
1977 break;
1978 }
1979 }
1980 if (!GDecl) {
1981 for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1982 E = QIdTy->qual_end(); I != E; ++I) {
1983 // Search in the protocol-qualifier list of current protocol.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00001984 GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
Fariborz Jahanian854f4002009-03-19 18:15:34 +00001985 if (GDecl)
1986 return GDecl;
1987 }
1988 }
1989 return GDecl;
1990}
Chris Lattner2cb744b2009-02-15 22:43:40 +00001991
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00001992/// FindMethodInNestedImplementations - Look up a method in current and
1993/// all base class implementations.
1994///
1995ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1996 const ObjCInterfaceDecl *IFace,
1997 const Selector &Sel) {
1998 ObjCMethodDecl *Method = 0;
Douglas Gregorafd5eb32009-04-24 00:11:27 +00001999 if (ObjCImplementationDecl *ImpDecl
2000 = LookupObjCImplementation(IFace->getIdentifier()))
Douglas Gregorcd19b572009-04-23 01:02:12 +00002001 Method = ImpDecl->getInstanceMethod(Context, Sel);
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002002
2003 if (!Method && IFace->getSuperClass())
2004 return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
2005 return Method;
2006}
2007
Sebastian Redl8b769972009-01-19 00:08:26 +00002008Action::OwningExprResult
2009Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2010 tok::TokenKind OpKind, SourceLocation MemberLoc,
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002011 IdentifierInfo &Member,
Chris Lattner5261d0c2009-03-28 19:18:32 +00002012 DeclPtrTy ObjCImpDecl) {
Anders Carlssonc154a722009-05-01 19:30:39 +00002013 Expr *BaseExpr = Base.takeAs<Expr>();
Steve Naroff2cb66382007-07-26 03:11:44 +00002014 assert(BaseExpr && "no record expression");
Steve Naroff137e11d2007-12-16 21:42:28 +00002015
2016 // Perform default conversions.
2017 DefaultFunctionArrayConversion(BaseExpr);
Sebastian Redl8b769972009-01-19 00:08:26 +00002018
Steve Naroff2cb66382007-07-26 03:11:44 +00002019 QualType BaseType = BaseExpr->getType();
2020 assert(!BaseType.isNull() && "no type for member expression");
Sebastian Redl8b769972009-01-19 00:08:26 +00002021
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002022 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
2023 // must have pointer type, and the accessed type is the pointee.
Chris Lattner4b009652007-07-25 00:24:17 +00002024 if (OpKind == tok::arrow) {
Anders Carlsson72d3c662009-05-15 23:10:19 +00002025 if (BaseType->isDependentType())
2026 return Owned(new (Context) MemberExpr(BaseExpr, true, 0,
2027 MemberLoc, Context.DependentTy));
2028 else if (const PointerType *PT = BaseType->getAsPointerType())
Steve Naroff2cb66382007-07-26 03:11:44 +00002029 BaseType = PT->getPointeeType();
Douglas Gregor7f3fec52008-11-20 16:27:02 +00002030 else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
Sebastian Redl8b769972009-01-19 00:08:26 +00002031 return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
2032 MemberLoc, Member));
Steve Naroff2cb66382007-07-26 03:11:44 +00002033 else
Sebastian Redl8b769972009-01-19 00:08:26 +00002034 return ExprError(Diag(MemberLoc,
2035 diag::err_typecheck_member_reference_arrow)
2036 << BaseType << BaseExpr->getSourceRange());
Anders Carlsson72d3c662009-05-15 23:10:19 +00002037 } else {
2038 // We use isTemplateTypeParmType directly here, instead of simply checking
2039 // whether BaseType is dependent, because we want to report an error for
2040 //
2041 // T *t;
2042 // t.foo;
2043 //
2044 //
2045 if (BaseType->isTemplateTypeParmType())
2046 return Owned(new (Context) MemberExpr(BaseExpr, false, 0,
2047 MemberLoc, Context.DependentTy));
Chris Lattner4b009652007-07-25 00:24:17 +00002048 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002049
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002050 // Handle field access to simple records. This also handles access to fields
2051 // of the ObjC 'id' struct.
Chris Lattnere35a1042007-07-31 19:29:30 +00002052 if (const RecordType *RTy = BaseType->getAsRecordType()) {
Steve Naroff2cb66382007-07-26 03:11:44 +00002053 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorc84d8932009-03-09 16:13:40 +00002054 if (RequireCompleteType(OpLoc, BaseType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002055 diag::err_typecheck_incomplete_tag,
2056 BaseExpr->getSourceRange()))
2057 return ExprError();
2058
Steve Naroff2cb66382007-07-26 03:11:44 +00002059 // The record definition is complete, now make sure the member is valid.
Mike Stumpe127ae32009-05-16 07:39:55 +00002060 // FIXME: Qualified name lookup for C++ is a bit more complicated than this.
Sebastian Redl8b769972009-01-19 00:08:26 +00002061 LookupResult Result
Mike Stump9afab102009-02-19 03:04:26 +00002062 = LookupQualifiedName(RDecl, DeclarationName(&Member),
Douglas Gregor52ae30c2009-01-30 01:04:22 +00002063 LookupMemberName, false);
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002064
Douglas Gregor29dfa2f2009-01-15 00:26:24 +00002065 if (!Result)
Sebastian Redl8b769972009-01-19 00:08:26 +00002066 return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
2067 << &Member << BaseExpr->getSourceRange());
Chris Lattner84ad8332009-03-31 08:18:48 +00002068 if (Result.isAmbiguous()) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002069 DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
2070 MemberLoc, BaseExpr->getSourceRange());
2071 return ExprError();
Chris Lattner84ad8332009-03-31 08:18:48 +00002072 }
2073
2074 NamedDecl *MemberDecl = Result;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002075
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002076 // If the decl being referenced had an error, return an error for this
2077 // sub-expr without emitting another error, in order to avoid cascading
2078 // error cases.
2079 if (MemberDecl->isInvalidDecl())
2080 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002081
Douglas Gregoraa57e862009-02-18 21:56:37 +00002082 // Check the use of this field
2083 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2084 return ExprError();
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002085
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002086 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
Douglas Gregor723d3332009-01-07 00:43:41 +00002087 // We may have found a field within an anonymous union or struct
2088 // (C++ [class.union]).
2089 if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
Sebastian Redlcd883f72009-01-18 18:53:16 +00002090 return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
Sebastian Redl8b769972009-01-19 00:08:26 +00002091 BaseExpr, OpLoc);
Douglas Gregor723d3332009-01-07 00:43:41 +00002092
Douglas Gregor82d44772008-12-20 23:49:58 +00002093 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2094 // FIXME: Handle address space modifiers
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002095 QualType MemberType = FD->getType();
Douglas Gregor82d44772008-12-20 23:49:58 +00002096 if (const ReferenceType *Ref = MemberType->getAsReferenceType())
2097 MemberType = Ref->getPointeeType();
2098 else {
2099 unsigned combinedQualifiers =
2100 MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
Douglas Gregorddfd9d52008-12-23 00:26:44 +00002101 if (FD->isMutable())
Douglas Gregor82d44772008-12-20 23:49:58 +00002102 combinedQualifiers &= ~QualType::Const;
2103 MemberType = MemberType.getQualifiedType(combinedQualifiers);
2104 }
Eli Friedman76b49832008-02-06 22:48:16 +00002105
Steve Naroff774e4152009-01-21 00:14:39 +00002106 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
2107 MemberLoc, MemberType));
Chris Lattner84ad8332009-03-31 08:18:48 +00002108 }
2109
2110 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00002111 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002112 Var, MemberLoc,
2113 Var->getType().getNonReferenceType()));
2114 if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00002115 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
Chris Lattner84ad8332009-03-31 08:18:48 +00002116 MemberFn, MemberLoc,
2117 MemberFn->getType()));
2118 if (OverloadedFunctionDecl *Ovl
2119 = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
Steve Naroff774e4152009-01-21 00:14:39 +00002120 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
Chris Lattner84ad8332009-03-31 08:18:48 +00002121 MemberLoc, Context.OverloadTy));
2122 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
Mike Stump9afab102009-02-19 03:04:26 +00002123 return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2124 Enum, MemberLoc, Enum->getType()));
Chris Lattner84ad8332009-03-31 08:18:48 +00002125 if (isa<TypeDecl>(MemberDecl))
Sebastian Redl8b769972009-01-19 00:08:26 +00002126 return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2127 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Eli Friedman76b49832008-02-06 22:48:16 +00002128
Douglas Gregor82d44772008-12-20 23:49:58 +00002129 // We found a declaration kind that we didn't expect. This is a
2130 // generic error message that tells the user that she can't refer
2131 // to this member with '.' or '->'.
Sebastian Redl8b769972009-01-19 00:08:26 +00002132 return ExprError(Diag(MemberLoc,
2133 diag::err_typecheck_member_reference_unknown)
2134 << DeclarationName(&Member) << int(OpKind == tok::arrow));
Chris Lattnera57cf472008-07-21 04:28:12 +00002135 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002136
Chris Lattnere9d71612008-07-21 04:59:05 +00002137 // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2138 // (*Obj).ivar.
Chris Lattnerb2b9da72008-07-21 04:36:39 +00002139 if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002140 ObjCInterfaceDecl *ClassDeclared;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002141 if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(Context,
2142 &Member,
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002143 ClassDeclared)) {
Chris Lattnerfd57ecc2009-02-13 22:08:30 +00002144 // If the decl being referenced had an error, return an error for this
2145 // sub-expr without emitting another error, in order to avoid cascading
2146 // error cases.
2147 if (IV->isInvalidDecl())
2148 return ExprError();
Douglas Gregoraa57e862009-02-18 21:56:37 +00002149
2150 // Check whether we can reference this field.
2151 if (DiagnoseUseOfDecl(IV, MemberLoc))
2152 return ExprError();
Steve Naroff8c56ee02009-03-26 16:01:08 +00002153 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2154 IV->getAccessControl() != ObjCIvarDecl::Package) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002155 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2156 if (ObjCMethodDecl *MD = getCurMethodDecl())
2157 ClassOfMethodDecl = MD->getClassInterface();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002158 else if (ObjCImpDecl && getCurFunctionDecl()) {
2159 // Case of a c-function declared inside an objc implementation.
2160 // FIXME: For a c-style function nested inside an objc implementation
Mike Stumpe127ae32009-05-16 07:39:55 +00002161 // class, there is no implementation context available, so we pass
2162 // down the context as argument to this routine. Ideally, this context
2163 // need be passed down in the AST node and somehow calculated from the
2164 // AST for a function decl.
Chris Lattner5261d0c2009-03-28 19:18:32 +00002165 Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002166 if (ObjCImplementationDecl *IMPD =
2167 dyn_cast<ObjCImplementationDecl>(ImplDecl))
2168 ClassOfMethodDecl = IMPD->getClassInterface();
2169 else if (ObjCCategoryImplDecl* CatImplClass =
2170 dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2171 ClassOfMethodDecl = CatImplClass->getClassInterface();
Steve Narofff9606572009-03-04 18:34:24 +00002172 }
Chris Lattner84ad8332009-03-31 08:18:48 +00002173
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002174 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002175 if (ClassDeclared != IFTy->getDecl() ||
Fariborz Jahanian0cc2ac12009-03-04 22:30:12 +00002176 ClassOfMethodDecl != ClassDeclared)
Fariborz Jahaniandd71e752009-03-03 01:21:12 +00002177 Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
2178 }
2179 // @protected
2180 else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
2181 Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
2182 }
Mike Stump9afab102009-02-19 03:04:26 +00002183
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00002184 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Steve Naroff774e4152009-01-21 00:14:39 +00002185 MemberLoc, BaseExpr,
Daniel Dunbarf5254bd2009-04-21 01:19:28 +00002186 OpKind == tok::arrow));
Fariborz Jahanian09772392008-12-13 22:20:28 +00002187 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002188 return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2189 << IFTy->getDecl()->getDeclName() << &Member
2190 << BaseExpr->getSourceRange());
Chris Lattnera57cf472008-07-21 04:28:12 +00002191 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002192
Chris Lattnere9d71612008-07-21 04:59:05 +00002193 // Handle Objective-C property access, which is "Obj.property" where Obj is a
2194 // pointer to a (potentially qualified) interface type.
2195 const PointerType *PTy;
2196 const ObjCInterfaceType *IFTy;
2197 if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
2198 (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
2199 ObjCInterfaceDecl *IFace = IFTy->getDecl();
Daniel Dunbardd851282008-08-30 05:35:15 +00002200
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002201 // Search for a declared property first.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002202 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Context,
2203 &Member)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002204 // Check whether we can reference this property.
2205 if (DiagnoseUseOfDecl(PD, MemberLoc))
2206 return ExprError();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002207 QualType ResTy = PD->getType();
2208 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2209 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Context, Sel);
Fariborz Jahanian80ccaa92009-05-08 20:20:55 +00002210 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2211 ResTy = Getter->getResultType();
Fariborz Jahaniana996bb02009-05-08 19:36:34 +00002212 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
Chris Lattner51f6fb32009-02-16 18:35:08 +00002213 MemberLoc, BaseExpr));
2214 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002215
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002216 // Check protocols on qualified interfaces.
Chris Lattnerd5f81792008-07-21 05:20:01 +00002217 for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
2218 E = IFTy->qual_end(); I != E; ++I)
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002219 if (ObjCPropertyDecl *PD = (*I)->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();
Chris Lattner51f6fb32009-02-16 18:35:08 +00002224
Steve Naroff774e4152009-01-21 00:14:39 +00002225 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002226 MemberLoc, BaseExpr));
2227 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002228
2229 // If that failed, look for an "implicit" property by seeing if the nullary
2230 // selector is implemented.
2231
2232 // FIXME: The logic for looking up nullary and unary selectors should be
2233 // shared with the code in ActOnInstanceMessage.
2234
2235 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002236 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Context, Sel);
Sebastian Redl8b769972009-01-19 00:08:26 +00002237
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002238 // If this reference is in an @implementation, check for 'private' methods.
2239 if (!Getter)
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002240 Getter = FindMethodInNestedImplementations(IFace, Sel);
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002241
Steve Naroff04151f32008-10-22 19:16:27 +00002242 // Look through local category implementations associated with the class.
2243 if (!Getter) {
2244 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
2245 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregorcd19b572009-04-23 01:02:12 +00002246 Getter = ObjCCategoryImpls[i]->getInstanceMethod(Context, Sel);
Steve Naroff04151f32008-10-22 19:16:27 +00002247 }
2248 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002249 if (Getter) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002250 // Check if we can reference this property.
2251 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2252 return ExprError();
Steve Naroffdede0c92009-03-11 13:48:17 +00002253 }
2254 // If we found a getter then this may be a valid dot-reference, we
2255 // will look for the matching setter, in case it is needed.
2256 Selector SetterSel =
2257 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2258 PP.getSelectorTable(), &Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002259 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(Context, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002260 if (!Setter) {
2261 // If this reference is in an @implementation, also check for 'private'
2262 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002263 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroffdede0c92009-03-11 13:48:17 +00002264 }
2265 // Look through local category implementations associated with the class.
2266 if (!Setter) {
2267 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2268 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregorcd19b572009-04-23 01:02:12 +00002269 Setter = ObjCCategoryImpls[i]->getInstanceMethod(Context, SetterSel);
Fariborz Jahanianc05da422008-11-22 20:25:50 +00002270 }
Daniel Dunbar60e8b162008-09-03 01:05:41 +00002271 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002272
Steve Naroffdede0c92009-03-11 13:48:17 +00002273 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2274 return ExprError();
2275
2276 if (Getter || Setter) {
2277 QualType PType;
2278
2279 if (Getter)
2280 PType = Getter->getResultType();
2281 else {
2282 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2283 E = Setter->param_end(); PI != E; ++PI)
2284 PType = (*PI)->getType();
2285 }
2286 // FIXME: we must check that the setter has property type.
2287 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2288 Setter, MemberLoc, BaseExpr));
2289 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002290 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2291 << &Member << BaseType);
Fariborz Jahanian4af72492007-11-12 22:29:28 +00002292 }
Steve Naroffd1d44402008-10-20 22:53:06 +00002293 // Handle properties on qualified "id" protocols.
2294 const ObjCQualifiedIdType *QIdTy;
2295 if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
2296 // Check protocols on qualified interfaces.
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002297 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002298 if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002299 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002300 // Check the use of this declaration
2301 if (DiagnoseUseOfDecl(PD, MemberLoc))
2302 return ExprError();
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002303
Steve Naroff774e4152009-01-21 00:14:39 +00002304 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Chris Lattner51f6fb32009-02-16 18:35:08 +00002305 MemberLoc, BaseExpr));
2306 }
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002307 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
Douglas Gregoraa57e862009-02-18 21:56:37 +00002308 // Check the use of this method.
2309 if (DiagnoseUseOfDecl(OMD, MemberLoc))
2310 return ExprError();
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002311
Mike Stump9afab102009-02-19 03:04:26 +00002312 return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
Fariborz Jahanian854f4002009-03-19 18:15:34 +00002313 OMD->getResultType(),
2314 OMD, OpLoc, MemberLoc,
2315 NULL, 0));
Fariborz Jahanian94cc8232008-12-10 00:21:50 +00002316 }
2317 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002318
2319 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2320 << &Member << BaseType);
Mike Stump9afab102009-02-19 03:04:26 +00002321 }
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002322 // Handle properties on ObjC 'Class' types.
2323 if (OpKind == tok::period && (BaseType == Context.getObjCClassType())) {
2324 // Also must look for a getter name which uses property syntax.
2325 Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2326 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002327 ObjCInterfaceDecl *IFace = MD->getClassInterface();
2328 ObjCMethodDecl *Getter;
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002329 // FIXME: need to also look locally in the implementation.
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002330 if ((Getter = IFace->lookupClassMethod(Context, Sel))) {
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002331 // Check the use of this method.
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002332 if (DiagnoseUseOfDecl(Getter, MemberLoc))
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002333 return ExprError();
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002334 }
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002335 // If we found a getter then this may be a valid dot-reference, we
2336 // will look for the matching setter, in case it is needed.
2337 Selector SetterSel =
2338 SelectorTable::constructSetterName(PP.getIdentifierTable(),
2339 PP.getSelectorTable(), &Member);
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002340 ObjCMethodDecl *Setter = IFace->lookupClassMethod(Context, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002341 if (!Setter) {
2342 // If this reference is in an @implementation, also check for 'private'
2343 // methods.
Fariborz Jahanian0119fd22009-04-07 18:28:06 +00002344 Setter = FindMethodInNestedImplementations(IFace, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002345 }
2346 // Look through local category implementations associated with the class.
2347 if (!Setter) {
2348 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
2349 if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
Douglas Gregorcd19b572009-04-23 01:02:12 +00002350 Setter = ObjCCategoryImpls[i]->getClassMethod(Context, SetterSel);
Steve Naroff6f9e59f2009-03-11 20:12:18 +00002351 }
2352 }
2353
2354 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2355 return ExprError();
2356
2357 if (Getter || Setter) {
2358 QualType PType;
2359
2360 if (Getter)
2361 PType = Getter->getResultType();
2362 else {
2363 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
2364 E = Setter->param_end(); PI != E; ++PI)
2365 PType = (*PI)->getType();
2366 }
2367 // FIXME: we must check that the setter has property type.
2368 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType,
2369 Setter, MemberLoc, BaseExpr));
2370 }
2371 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2372 << &Member << BaseType);
Steve Naroffe3aa06f2009-03-05 20:12:00 +00002373 }
2374 }
2375
Chris Lattnera57cf472008-07-21 04:28:12 +00002376 // Handle 'field access' to vectors, such as 'V.xx'.
Chris Lattner09020ee2009-02-16 21:11:58 +00002377 if (BaseType->isExtVectorType()) {
Chris Lattnera57cf472008-07-21 04:28:12 +00002378 QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2379 if (ret.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00002380 return ExprError();
Mike Stump9afab102009-02-19 03:04:26 +00002381 return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
Steve Naroff774e4152009-01-21 00:14:39 +00002382 MemberLoc));
Chris Lattnera57cf472008-07-21 04:28:12 +00002383 }
Sebastian Redl8b769972009-01-19 00:08:26 +00002384
Douglas Gregor762da552009-03-27 06:00:30 +00002385 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2386 << BaseType << BaseExpr->getSourceRange();
2387
2388 // If the user is trying to apply -> or . to a function or function
2389 // pointer, it's probably because they forgot parentheses to call
2390 // the function. Suggest the addition of those parentheses.
2391 if (BaseType == Context.OverloadTy ||
2392 BaseType->isFunctionType() ||
2393 (BaseType->isPointerType() &&
2394 BaseType->getAsPointerType()->isFunctionType())) {
2395 SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2396 Diag(Loc, diag::note_member_reference_needs_call)
2397 << CodeModificationHint::CreateInsertion(Loc, "()");
2398 }
2399
2400 return ExprError();
Chris Lattner4b009652007-07-25 00:24:17 +00002401}
2402
Douglas Gregor3257fb52008-12-22 05:46:06 +00002403/// ConvertArgumentsForCall - Converts the arguments specified in
2404/// Args/NumArgs to the parameter types of the function FDecl with
2405/// function prototype Proto. Call is the call expression itself, and
2406/// Fn is the function expression. For a C++ member function, this
2407/// routine does not attempt to convert the object argument. Returns
2408/// true if the call is ill-formed.
Mike Stump9afab102009-02-19 03:04:26 +00002409bool
2410Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002411 FunctionDecl *FDecl,
Douglas Gregor4fa58902009-02-26 23:50:07 +00002412 const FunctionProtoType *Proto,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002413 Expr **Args, unsigned NumArgs,
2414 SourceLocation RParenLoc) {
Mike Stump9afab102009-02-19 03:04:26 +00002415 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor3257fb52008-12-22 05:46:06 +00002416 // assignment, to the types of the corresponding parameter, ...
2417 unsigned NumArgsInProto = Proto->getNumArgs();
2418 unsigned NumArgsToCheck = NumArgs;
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002419 bool Invalid = false;
2420
Douglas Gregor3257fb52008-12-22 05:46:06 +00002421 // If too few arguments are available (and we don't have default
2422 // arguments for the remaining parameters), don't make the call.
2423 if (NumArgs < NumArgsInProto) {
2424 if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2425 return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2426 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2427 // Use default arguments for missing arguments
2428 NumArgsToCheck = NumArgsInProto;
Ted Kremenek0c97e042009-02-07 01:47:29 +00002429 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002430 }
2431
2432 // If too many are passed and not variadic, error on the extras and drop
2433 // them.
2434 if (NumArgs > NumArgsInProto) {
2435 if (!Proto->isVariadic()) {
2436 Diag(Args[NumArgsInProto]->getLocStart(),
2437 diag::err_typecheck_call_too_many_args)
2438 << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2439 << SourceRange(Args[NumArgsInProto]->getLocStart(),
2440 Args[NumArgs-1]->getLocEnd());
2441 // This deletes the extra arguments.
Ted Kremenek0c97e042009-02-07 01:47:29 +00002442 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002443 Invalid = true;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002444 }
2445 NumArgsToCheck = NumArgsInProto;
2446 }
Mike Stump9afab102009-02-19 03:04:26 +00002447
Douglas Gregor3257fb52008-12-22 05:46:06 +00002448 // Continue to check argument types (even if we have too few/many args).
2449 for (unsigned i = 0; i != NumArgsToCheck; i++) {
2450 QualType ProtoArgType = Proto->getArgType(i);
Mike Stump9afab102009-02-19 03:04:26 +00002451
Douglas Gregor3257fb52008-12-22 05:46:06 +00002452 Expr *Arg;
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002453 if (i < NumArgs) {
Douglas Gregor3257fb52008-12-22 05:46:06 +00002454 Arg = Args[i];
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002455
Eli Friedman83dec9e2009-03-22 22:00:50 +00002456 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2457 ProtoArgType,
2458 diag::err_call_incomplete_argument,
2459 Arg->getSourceRange()))
2460 return true;
2461
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002462 // Pass the argument.
2463 if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2464 return true;
Mike Stump9afab102009-02-19 03:04:26 +00002465 } else
Douglas Gregor62ae25a2008-12-24 00:01:03 +00002466 // We already type-checked the argument, so we know it works.
Steve Naroff774e4152009-01-21 00:14:39 +00002467 Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002468 QualType ArgType = Arg->getType();
Mike Stump9afab102009-02-19 03:04:26 +00002469
Douglas Gregor3257fb52008-12-22 05:46:06 +00002470 Call->setArg(i, Arg);
2471 }
Mike Stump9afab102009-02-19 03:04:26 +00002472
Douglas Gregor3257fb52008-12-22 05:46:06 +00002473 // If this is a variadic call, handle args passed through "...".
2474 if (Proto->isVariadic()) {
Anders Carlsson4b8e38c2009-01-16 16:48:51 +00002475 VariadicCallType CallType = VariadicFunction;
2476 if (Fn->getType()->isBlockPointerType())
2477 CallType = VariadicBlock; // Block
2478 else if (isa<MemberExpr>(Fn))
2479 CallType = VariadicMethod;
2480
Douglas Gregor3257fb52008-12-22 05:46:06 +00002481 // Promote the arguments (C99 6.5.2.2p7).
2482 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2483 Expr *Arg = Args[i];
Chris Lattner81f00ed2009-04-12 08:11:20 +00002484 Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
Douglas Gregor3257fb52008-12-22 05:46:06 +00002485 Call->setArg(i, Arg);
2486 }
2487 }
2488
Douglas Gregor4ac887b2009-01-23 21:30:56 +00002489 return Invalid;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002490}
2491
Steve Naroff87d58b42007-09-16 03:34:24 +00002492/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattner4b009652007-07-25 00:24:17 +00002493/// This provides the location of the left/right parens and a list of comma
2494/// locations.
Sebastian Redl8b769972009-01-19 00:08:26 +00002495Action::OwningExprResult
2496Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2497 MultiExprArg args,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002498 SourceLocation *CommaLocs, SourceLocation RParenLoc) {
Sebastian Redl8b769972009-01-19 00:08:26 +00002499 unsigned NumArgs = args.size();
Anders Carlssonc154a722009-05-01 19:30:39 +00002500 Expr *Fn = fn.takeAs<Expr>();
Sebastian Redl8b769972009-01-19 00:08:26 +00002501 Expr **Args = reinterpret_cast<Expr**>(args.release());
Chris Lattner4b009652007-07-25 00:24:17 +00002502 assert(Fn && "no function call expression");
Chris Lattner3e254fb2008-04-08 04:40:51 +00002503 FunctionDecl *FDecl = NULL;
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002504 NamedDecl *NDecl = NULL;
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002505 DeclarationName UnqualifiedName;
Douglas Gregor3257fb52008-12-22 05:46:06 +00002506
Douglas Gregor3257fb52008-12-22 05:46:06 +00002507 if (getLangOptions().CPlusPlus) {
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002508 // Determine whether this is a dependent call inside a C++ template,
Mike Stump9afab102009-02-19 03:04:26 +00002509 // in which case we won't do any semantic analysis now.
Mike Stumpe127ae32009-05-16 07:39:55 +00002510 // FIXME: Will need to cache the results of name lookup (including ADL) in
2511 // Fn.
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002512 bool Dependent = false;
2513 if (Fn->isTypeDependent())
2514 Dependent = true;
2515 else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2516 Dependent = true;
2517
2518 if (Dependent)
Ted Kremenek362abcd2009-02-09 20:51:47 +00002519 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002520 Context.DependentTy, RParenLoc));
2521
2522 // Determine whether this is a call to an object (C++ [over.call.object]).
2523 if (Fn->getType()->isRecordType())
2524 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2525 CommaLocs, RParenLoc));
2526
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002527 // Determine whether this is a call to a member function.
Douglas Gregor3257fb52008-12-22 05:46:06 +00002528 if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2529 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2530 isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
Sebastian Redl8b769972009-01-19 00:08:26 +00002531 return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2532 CommaLocs, RParenLoc));
Douglas Gregor3257fb52008-12-22 05:46:06 +00002533 }
2534
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002535 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregor566782a2009-01-06 05:10:23 +00002536 DeclRefExpr *DRExpr = NULL;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002537 Expr *FnExpr = Fn;
2538 bool ADL = true;
2539 while (true) {
2540 if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2541 FnExpr = IcExpr->getSubExpr();
2542 else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
Mike Stump9afab102009-02-19 03:04:26 +00002543 // Parentheses around a function disable ADL
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002544 // (C++0x [basic.lookup.argdep]p1).
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002545 ADL = false;
2546 FnExpr = PExpr->getSubExpr();
2547 } else if (isa<UnaryOperator>(FnExpr) &&
Mike Stump9afab102009-02-19 03:04:26 +00002548 cast<UnaryOperator>(FnExpr)->getOpcode()
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002549 == UnaryOperator::AddrOf) {
2550 FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002551 } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2552 // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2553 ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2554 break;
Mike Stump9afab102009-02-19 03:04:26 +00002555 } else if (UnresolvedFunctionNameExpr *DepName
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002556 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2557 UnqualifiedName = DepName->getName();
2558 break;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002559 } else {
Chris Lattnere50fb0b2009-02-14 07:22:29 +00002560 // Any kind of name that does not refer to a declaration (or
2561 // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2562 ADL = false;
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002563 break;
2564 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002565 }
Mike Stump9afab102009-02-19 03:04:26 +00002566
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002567 OverloadedFunctionDecl *Ovl = 0;
2568 if (DRExpr) {
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002569 FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002570 Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002571 NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002572 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002573
Douglas Gregorfcb19192009-02-11 23:02:49 +00002574 if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
Douglas Gregor411889e2009-02-13 23:20:09 +00002575 // We don't perform ADL for implicit declarations of builtins.
Douglas Gregorb5af7382009-02-14 18:57:46 +00002576 if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002577 ADL = false;
2578
Douglas Gregorfcb19192009-02-11 23:02:49 +00002579 // We don't perform ADL in C.
2580 if (!getLangOptions().CPlusPlus)
2581 ADL = false;
2582
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002583 if (Ovl || ADL) {
Mike Stump9afab102009-02-19 03:04:26 +00002584 FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2585 UnqualifiedName, LParenLoc, Args,
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002586 NumArgs, CommaLocs, RParenLoc, ADL);
2587 if (!FDecl)
2588 return ExprError();
2589
2590 // Update Fn to refer to the actual function selected.
2591 Expr *NewFn = 0;
Mike Stump9afab102009-02-19 03:04:26 +00002592 if (QualifiedDeclRefExpr *QDRExpr
Douglas Gregor4646f9c2009-02-04 15:01:18 +00002593 = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
Douglas Gregor1e589cc2009-03-26 23:50:42 +00002594 NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2595 QDRExpr->getLocation(),
2596 false, false,
2597 QDRExpr->getQualifierRange(),
2598 QDRExpr->getQualifier());
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002599 else
Mike Stump9afab102009-02-19 03:04:26 +00002600 NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
Douglas Gregoraa1da4a2009-02-04 00:32:51 +00002601 Fn->getSourceRange().getBegin());
2602 Fn->Destroy(Context);
2603 Fn = NewFn;
2604 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00002605 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002606
2607 // Promote the function operand.
2608 UsualUnaryConversions(Fn);
2609
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002610 // Make the call expr early, before semantic checks. This guarantees cleanup
2611 // of arguments and function on error.
Ted Kremenek362abcd2009-02-09 20:51:47 +00002612 ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2613 Args, NumArgs,
2614 Context.BoolTy,
2615 RParenLoc));
Sebastian Redl8b769972009-01-19 00:08:26 +00002616
Steve Naroffd6163f32008-09-05 22:11:13 +00002617 const FunctionType *FuncT;
2618 if (!Fn->getType()->isBlockPointerType()) {
2619 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2620 // have type pointer to function".
2621 const PointerType *PT = Fn->getType()->getAsPointerType();
2622 if (PT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002623 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2624 << Fn->getType() << Fn->getSourceRange());
Steve Naroffd6163f32008-09-05 22:11:13 +00002625 FuncT = PT->getPointeeType()->getAsFunctionType();
2626 } else { // This is a block call.
2627 FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2628 getAsFunctionType();
2629 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002630 if (FuncT == 0)
Sebastian Redl8b769972009-01-19 00:08:26 +00002631 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2632 << Fn->getType() << Fn->getSourceRange());
2633
Eli Friedman83dec9e2009-03-22 22:00:50 +00002634 // Check for a valid return type
2635 if (!FuncT->getResultType()->isVoidType() &&
2636 RequireCompleteType(Fn->getSourceRange().getBegin(),
2637 FuncT->getResultType(),
2638 diag::err_call_incomplete_return,
2639 TheCall->getSourceRange()))
2640 return ExprError();
2641
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002642 // We know the result type of the call, set it.
Douglas Gregor2aecd1f2008-10-29 02:00:59 +00002643 TheCall->setType(FuncT->getResultType().getNonReferenceType());
Sebastian Redl8b769972009-01-19 00:08:26 +00002644
Douglas Gregor4fa58902009-02-26 23:50:07 +00002645 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
Mike Stump9afab102009-02-19 03:04:26 +00002646 if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
Douglas Gregor3257fb52008-12-22 05:46:06 +00002647 RParenLoc))
Sebastian Redl8b769972009-01-19 00:08:26 +00002648 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002649 } else {
Douglas Gregor4fa58902009-02-26 23:50:07 +00002650 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redl8b769972009-01-19 00:08:26 +00002651
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002652 if (FDecl) {
2653 // Check if we have too few/too many template arguments, based
2654 // on our knowledge of the function definition.
2655 const FunctionDecl *Def = 0;
Douglas Gregore3241e92009-04-18 00:02:19 +00002656 if (FDecl->getBody(Context, Def) && NumArgs != Def->param_size())
Douglas Gregora8f2ae62009-04-02 15:37:10 +00002657 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2658 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2659 }
2660
Steve Naroffdb65e052007-08-28 23:30:39 +00002661 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002662 for (unsigned i = 0; i != NumArgs; i++) {
2663 Expr *Arg = Args[i];
2664 DefaultArgumentPromotion(Arg);
Eli Friedman83dec9e2009-03-22 22:00:50 +00002665 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2666 Arg->getType(),
2667 diag::err_call_incomplete_argument,
2668 Arg->getSourceRange()))
2669 return ExprError();
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002670 TheCall->setArg(i, Arg);
Steve Naroffdb65e052007-08-28 23:30:39 +00002671 }
Chris Lattner4b009652007-07-25 00:24:17 +00002672 }
Chris Lattner83bd5eb2007-12-28 05:29:59 +00002673
Douglas Gregor3257fb52008-12-22 05:46:06 +00002674 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2675 if (!Method->isStatic())
Sebastian Redl8b769972009-01-19 00:08:26 +00002676 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2677 << Fn->getSourceRange());
Douglas Gregor3257fb52008-12-22 05:46:06 +00002678
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002679 // Check for sentinels
2680 if (NDecl)
2681 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Chris Lattner2e64c072007-08-10 20:18:51 +00002682 // Do special checking on direct calls to functions.
Fariborz Jahanianc10357d2009-05-15 20:33:25 +00002683 if (FDecl)
Eli Friedmand0e9d092008-05-14 19:38:39 +00002684 return CheckFunctionCall(FDecl, TheCall.take());
Chris Lattner2e64c072007-08-10 20:18:51 +00002685
Sebastian Redl8b769972009-01-19 00:08:26 +00002686 return Owned(TheCall.take());
Chris Lattner4b009652007-07-25 00:24:17 +00002687}
2688
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002689Action::OwningExprResult
2690Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2691 SourceLocation RParenLoc, ExprArg InitExpr) {
Steve Naroff87d58b42007-09-16 03:34:24 +00002692 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Chris Lattner4b009652007-07-25 00:24:17 +00002693 QualType literalType = QualType::getFromOpaquePtr(Ty);
2694 // FIXME: put back this assert when initializers are worked out.
Steve Naroff87d58b42007-09-16 03:34:24 +00002695 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002696 Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
Anders Carlsson9374b852007-12-05 07:24:19 +00002697
Eli Friedman8c2173d2008-05-20 05:22:08 +00002698 if (literalType->isArrayType()) {
Chris Lattnera1923f62008-08-04 07:31:14 +00002699 if (literalType->isVariableArrayType())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002700 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2701 << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
Douglas Gregorc84d8932009-03-09 16:13:40 +00002702 } else if (RequireCompleteType(LParenLoc, literalType,
Douglas Gregor46fe06e2009-01-19 19:26:10 +00002703 diag::err_typecheck_decl_incomplete_type,
2704 SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002705 return ExprError();
Eli Friedman8c2173d2008-05-20 05:22:08 +00002706
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002707 if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
Douglas Gregor6214d8a2009-01-14 15:45:31 +00002708 DeclarationName(), /*FIXME:DirectInit=*/false))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002709 return ExprError();
Steve Naroffbe37fc02008-01-14 18:19:28 +00002710
Chris Lattnere5cb5862008-12-04 23:50:19 +00002711 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffbe37fc02008-01-14 18:19:28 +00002712 if (isFileScope) { // 6.5.2.5p3
Steve Narofff0b23542008-01-10 22:15:12 +00002713 if (CheckForConstantInitializer(literalExpr, literalType))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002714 return ExprError();
Steve Narofff0b23542008-01-10 22:15:12 +00002715 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002716 InitExpr.release();
Mike Stump9afab102009-02-19 03:04:26 +00002717 return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
Steve Naroff774e4152009-01-21 00:14:39 +00002718 literalExpr, isFileScope));
Chris Lattner4b009652007-07-25 00:24:17 +00002719}
2720
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002721Action::OwningExprResult
2722Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002723 SourceLocation RBraceLoc) {
2724 unsigned NumInit = initlist.size();
2725 Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
Anders Carlsson762b7c72007-08-31 04:56:16 +00002726
Steve Naroff0acc9c92007-09-15 18:49:24 +00002727 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump9afab102009-02-19 03:04:26 +00002728 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002729
Mike Stump9afab102009-02-19 03:04:26 +00002730 InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
Douglas Gregorf603b472009-01-28 21:54:33 +00002731 RBraceLoc);
Chris Lattner48d7f382008-04-02 04:24:33 +00002732 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002733 return Owned(E);
Chris Lattner4b009652007-07-25 00:24:17 +00002734}
2735
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002736/// CheckCastTypes - Check type constraints for casting between types.
Daniel Dunbar5ad49de2008-08-20 03:55:42 +00002737bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002738 UsualUnaryConversions(castExpr);
2739
2740 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2741 // type needs to be scalar.
2742 if (castType->isVoidType()) {
2743 // Cast to void allows any expr type.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002744 } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2745 // We can't check any more until template instantiation time.
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002746 } else if (!castType->isScalarType() && !castType->isVectorType()) {
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002747 if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2748 Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2749 (castType->isStructureType() || castType->isUnionType())) {
2750 // GCC struct/union extension: allow cast to self.
Eli Friedman2b128322009-03-23 00:24:07 +00002751 // FIXME: Check that the cast destination type is complete.
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002752 Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2753 << castType << castExpr->getSourceRange();
2754 } else if (castType->isUnionType()) {
2755 // GCC cast to union extension
2756 RecordDecl *RD = castType->getAsRecordType()->getDecl();
2757 RecordDecl::field_iterator Field, FieldEnd;
Douglas Gregorc55b0b02009-04-09 21:40:53 +00002758 for (Field = RD->field_begin(Context), FieldEnd = RD->field_end(Context);
Seo Sanghyeon27b33952009-01-15 04:51:39 +00002759 Field != FieldEnd; ++Field) {
2760 if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2761 Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2762 Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2763 << castExpr->getSourceRange();
2764 break;
2765 }
2766 }
2767 if (Field == FieldEnd)
2768 return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2769 << castExpr->getType() << castExpr->getSourceRange();
2770 } else {
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002771 // Reject any other conversions to non-scalar types.
Chris Lattner8ba580c2008-11-19 05:08:23 +00002772 return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002773 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002774 }
Mike Stump9afab102009-02-19 03:04:26 +00002775 } else if (!castExpr->getType()->isScalarType() &&
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002776 !castExpr->getType()->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +00002777 return Diag(castExpr->getLocStart(),
2778 diag::err_typecheck_expect_scalar_operand)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002779 << castExpr->getType() << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002780 } else if (castExpr->getType()->isVectorType()) {
2781 if (CheckVectorCast(TyR, castExpr->getType(), castType))
2782 return true;
2783 } else if (castType->isVectorType()) {
2784 if (CheckVectorCast(TyR, castType, castExpr->getType()))
2785 return true;
Steve Naroffff6c8022009-03-04 15:11:40 +00002786 } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
Steve Naroff49fd7ad2009-04-08 23:52:26 +00002787 return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
Eli Friedman970e56c2009-05-01 02:23:58 +00002788 } else if (!castType->isArithmeticType()) {
2789 QualType castExprType = castExpr->getType();
2790 if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2791 return Diag(castExpr->getLocStart(),
2792 diag::err_cast_pointer_from_non_pointer_int)
2793 << castExprType << castExpr->getSourceRange();
2794 } else if (!castExpr->getType()->isArithmeticType()) {
2795 if (!castType->isIntegralType() && castType->isArithmeticType())
2796 return Diag(castExpr->getLocStart(),
2797 diag::err_cast_pointer_to_non_pointer_int)
2798 << castType << castExpr->getSourceRange();
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002799 }
2800 return false;
2801}
2802
Chris Lattnerd1f26b32007-12-20 00:44:32 +00002803bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002804 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump9afab102009-02-19 03:04:26 +00002805
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002806 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002807 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002808 return Diag(R.getBegin(),
Mike Stump9afab102009-02-19 03:04:26 +00002809 Ty->isVectorType() ?
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002810 diag::err_invalid_conversion_between_vectors :
Chris Lattner8ba580c2008-11-19 05:08:23 +00002811 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002812 << VectorTy << Ty << R;
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002813 } else
2814 return Diag(R.getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00002815 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner4bfd2232008-11-24 06:25:27 +00002816 << VectorTy << Ty << R;
Mike Stump9afab102009-02-19 03:04:26 +00002817
Anders Carlssonf257b4c2007-11-27 05:51:55 +00002818 return false;
2819}
2820
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002821Action::OwningExprResult
2822Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2823 SourceLocation RParenLoc, ExprArg Op) {
2824 assert((Ty != 0) && (Op.get() != 0) &&
2825 "ActOnCastExpr(): missing type or expr");
Chris Lattner4b009652007-07-25 00:24:17 +00002826
Anders Carlssonc154a722009-05-01 19:30:39 +00002827 Expr *castExpr = Op.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00002828 QualType castType = QualType::getFromOpaquePtr(Ty);
2829
Argiris Kirtzidis95de23a2008-08-16 20:27:34 +00002830 if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
Sebastian Redl5457c5e2009-01-19 22:31:54 +00002831 return ExprError();
Steve Naroff774e4152009-01-21 00:14:39 +00002832 return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
Mike Stump9afab102009-02-19 03:04:26 +00002833 LParenLoc, RParenLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00002834}
2835
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00002836/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2837/// In that case, lhs = cond.
Chris Lattner9c039b52009-02-18 04:38:20 +00002838/// C99 6.5.15
2839QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2840 SourceLocation QuestionLoc) {
Sebastian Redlbd261962009-04-16 17:51:27 +00002841 // C++ is sufficiently different to merit its own checker.
2842 if (getLangOptions().CPlusPlus)
2843 return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
2844
Chris Lattnere2897262009-02-18 04:28:32 +00002845 UsualUnaryConversions(Cond);
2846 UsualUnaryConversions(LHS);
2847 UsualUnaryConversions(RHS);
2848 QualType CondTy = Cond->getType();
2849 QualType LHSTy = LHS->getType();
2850 QualType RHSTy = RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002851
2852 // first, check the condition.
Sebastian Redlbd261962009-04-16 17:51:27 +00002853 if (!CondTy->isScalarType()) { // C99 6.5.15p2
2854 Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2855 << CondTy;
2856 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00002857 }
Mike Stump9afab102009-02-19 03:04:26 +00002858
Chris Lattner992ae932008-01-06 22:42:25 +00002859 // Now check the two expressions.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00002860
Chris Lattner992ae932008-01-06 22:42:25 +00002861 // If both operands have arithmetic type, do the usual arithmetic conversions
2862 // to find a common type: C99 6.5.15p3,5.
Chris Lattnere2897262009-02-18 04:28:32 +00002863 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2864 UsualArithmeticConversions(LHS, RHS);
2865 return LHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002866 }
Mike Stump9afab102009-02-19 03:04:26 +00002867
Chris Lattner992ae932008-01-06 22:42:25 +00002868 // If both operands are the same structure or union type, the result is that
2869 // type.
Chris Lattnere2897262009-02-18 04:28:32 +00002870 if (const RecordType *LHSRT = LHSTy->getAsRecordType()) { // C99 6.5.15p3
2871 if (const RecordType *RHSRT = RHSTy->getAsRecordType())
Chris Lattner98a425c2007-11-26 01:40:58 +00002872 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00002873 // "If both the operands have structure or union type, the result has
Chris Lattner992ae932008-01-06 22:42:25 +00002874 // that type." This implies that CV qualifiers are dropped.
Chris Lattnere2897262009-02-18 04:28:32 +00002875 return LHSTy.getUnqualifiedType();
Eli Friedman2b128322009-03-23 00:24:07 +00002876 // FIXME: Type of conditional expression must be complete in C mode.
Chris Lattner4b009652007-07-25 00:24:17 +00002877 }
Mike Stump9afab102009-02-19 03:04:26 +00002878
Chris Lattner992ae932008-01-06 22:42:25 +00002879 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroff95cb3892008-05-12 21:44:38 +00002880 // The following || allows only one side to be void (a GCC-ism).
Chris Lattnere2897262009-02-18 04:28:32 +00002881 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2882 if (!LHSTy->isVoidType())
2883 Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2884 << RHS->getSourceRange();
2885 if (!RHSTy->isVoidType())
2886 Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2887 << LHS->getSourceRange();
2888 ImpCastExprToType(LHS, Context.VoidTy);
2889 ImpCastExprToType(RHS, Context.VoidTy);
Eli Friedmanf025aac2008-06-04 19:47:51 +00002890 return Context.VoidTy;
Steve Naroff95cb3892008-05-12 21:44:38 +00002891 }
Steve Naroff12ebf272008-01-08 01:11:38 +00002892 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2893 // the type of the other operand."
Chris Lattnere2897262009-02-18 04:28:32 +00002894 if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2895 Context.isObjCObjectPointerType(LHSTy)) &&
2896 RHS->isNullPointerConstant(Context)) {
2897 ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2898 return LHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002899 }
Chris Lattnere2897262009-02-18 04:28:32 +00002900 if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2901 Context.isObjCObjectPointerType(RHSTy)) &&
2902 LHS->isNullPointerConstant(Context)) {
2903 ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2904 return RHSTy;
Steve Naroff12ebf272008-01-08 01:11:38 +00002905 }
Mike Stump9afab102009-02-19 03:04:26 +00002906
Mike Stumpe97a8542009-05-07 03:14:14 +00002907 const PointerType *LHSPT = LHSTy->getAsPointerType();
2908 const PointerType *RHSPT = RHSTy->getAsPointerType();
2909 const BlockPointerType *LHSBPT = LHSTy->getAsBlockPointerType();
2910 const BlockPointerType *RHSBPT = RHSTy->getAsBlockPointerType();
2911
Chris Lattner0ac51632008-01-06 22:50:31 +00002912 // Handle the case where both operands are pointers before we handle null
2913 // pointer constants in case both operands are null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00002914 if ((LHSPT || LHSBPT) && (RHSPT || RHSBPT)) { // C99 6.5.15p3,6
2915 // get the "pointed to" types
Mike Stumpea3d74e2009-05-07 18:43:07 +00002916 QualType lhptee = (LHSPT ? LHSPT->getPointeeType()
2917 : LHSBPT->getPointeeType());
2918 QualType rhptee = (RHSPT ? RHSPT->getPointeeType()
2919 : RHSBPT->getPointeeType());
Chris Lattner4b009652007-07-25 00:24:17 +00002920
Mike Stumpe97a8542009-05-07 03:14:14 +00002921 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2922 if (lhptee->isVoidType()
2923 && (RHSBPT || rhptee->isIncompleteOrObjectType())) {
2924 // Figure out necessary qualifiers (C99 6.5.15p6)
2925 QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
2926 QualType destType = Context.getPointerType(destPointee);
2927 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2928 ImpCastExprToType(RHS, destType); // promote to void*
2929 return destType;
2930 }
2931 if (rhptee->isVoidType()
2932 && (LHSBPT || lhptee->isIncompleteOrObjectType())) {
2933 QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
2934 QualType destType = Context.getPointerType(destPointee);
2935 ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2936 ImpCastExprToType(RHS, destType); // promote to void*
2937 return destType;
2938 }
Chris Lattner4b009652007-07-25 00:24:17 +00002939
Mike Stumpe97a8542009-05-07 03:14:14 +00002940 bool sameKind = (LHSPT && RHSPT) || (LHSBPT && RHSBPT);
2941 if (sameKind
2942 && Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
2943 // Two identical pointer types are always compatible.
2944 return LHSTy;
2945 }
Mike Stump9afab102009-02-19 03:04:26 +00002946
Mike Stumpe97a8542009-05-07 03:14:14 +00002947 QualType compositeType = LHSTy;
Mike Stump9afab102009-02-19 03:04:26 +00002948
Mike Stumpe97a8542009-05-07 03:14:14 +00002949 // If either type is an Objective-C object type then check
2950 // compatibility according to Objective-C.
2951 if (Context.isObjCObjectPointerType(LHSTy) ||
2952 Context.isObjCObjectPointerType(RHSTy)) {
2953 // If both operands are interfaces and either operand can be
2954 // assigned to the other, use that type as the composite
2955 // type. This allows
2956 // xxx ? (A*) a : (B*) b
2957 // where B is a subclass of A.
2958 //
2959 // Additionally, as for assignment, if either type is 'id'
2960 // allow silent coercion. Finally, if the types are
2961 // incompatible then make sure to use 'id' as the composite
2962 // type so the result is acceptable for sending messages to.
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00002963
Mike Stumpe97a8542009-05-07 03:14:14 +00002964 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2965 // It could return the composite type.
2966 const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2967 const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2968 if (LHSIface && RHSIface &&
2969 Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2970 compositeType = LHSTy;
2971 } else if (LHSIface && RHSIface &&
2972 Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
2973 compositeType = RHSTy;
2974 } else if (Context.isObjCIdStructType(lhptee) ||
2975 Context.isObjCIdStructType(rhptee)) {
2976 compositeType = Context.getObjCIdType();
2977 } else if (LHSBPT || RHSBPT) {
2978 if (!sameKind
2979 || !Context.typesAreBlockCompatible(lhptee.getUnqualifiedType(),
2980 rhptee.getUnqualifiedType()))
2981 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2982 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2983 return QualType();
2984 } else {
2985 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
2986 << LHSTy << RHSTy
2987 << LHS->getSourceRange() << RHS->getSourceRange();
2988 QualType incompatTy = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00002989 ImpCastExprToType(LHS, incompatTy);
2990 ImpCastExprToType(RHS, incompatTy);
Daniel Dunbarcd23bb22008-08-26 00:41:39 +00002991 return incompatTy;
Chris Lattner71225142007-07-31 21:27:01 +00002992 }
Mike Stumpe97a8542009-05-07 03:14:14 +00002993 } else if (!sameKind
2994 || !Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2995 rhptee.getUnqualifiedType())) {
2996 Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2997 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2998 // In this situation, we assume void* type. No especially good
2999 // reason, but this is what gcc does, and we do have to pick
3000 // to get a consistent AST.
3001 QualType incompatTy = Context.getPointerType(Context.VoidTy);
3002 ImpCastExprToType(LHS, incompatTy);
3003 ImpCastExprToType(RHS, incompatTy);
3004 return incompatTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003005 }
Mike Stumpe97a8542009-05-07 03:14:14 +00003006 // The pointer types are compatible.
3007 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3008 // differently qualified versions of compatible types, the result type is
3009 // a pointer to an appropriately qualified version of the *composite*
3010 // type.
3011 // FIXME: Need to calculate the composite type.
3012 // FIXME: Need to add qualifiers
3013 ImpCastExprToType(LHS, compositeType);
3014 ImpCastExprToType(RHS, compositeType);
3015 return compositeType;
Chris Lattner4b009652007-07-25 00:24:17 +00003016 }
Mike Stump9afab102009-02-19 03:04:26 +00003017
Steve Naroff6ba22682009-04-08 17:05:15 +00003018 // GCC compatibility: soften pointer/integer mismatch.
3019 if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3020 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3021 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3022 ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3023 return RHSTy;
3024 }
3025 if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3026 Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3027 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3028 ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3029 return LHSTy;
3030 }
3031
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003032 // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
3033 // evaluates to "struct objc_object *" (and is handled above when comparing
Mike Stump9afab102009-02-19 03:04:26 +00003034 // id with statically typed objects).
3035 if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003036 // GCC allows qualified id and any Objective-C type to devolve to
3037 // id. Currently localizing to here until clear this should be
3038 // part of ObjCQualifiedIdTypesAreCompatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003039 if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
Mike Stump9afab102009-02-19 03:04:26 +00003040 (LHSTy->isObjCQualifiedIdType() &&
Chris Lattnere2897262009-02-18 04:28:32 +00003041 Context.isObjCObjectPointerType(RHSTy)) ||
3042 (RHSTy->isObjCQualifiedIdType() &&
3043 Context.isObjCObjectPointerType(LHSTy))) {
Mike Stumpe127ae32009-05-16 07:39:55 +00003044 // FIXME: This is not the correct composite type. This only happens to
3045 // work because id can more or less be used anywhere, however this may
3046 // change the type of method sends.
3047
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003048 // FIXME: gcc adds some type-checking of the arguments and emits
3049 // (confusing) incompatible comparison warnings in some
3050 // cases. Investigate.
3051 QualType compositeType = Context.getObjCIdType();
Chris Lattnere2897262009-02-18 04:28:32 +00003052 ImpCastExprToType(LHS, compositeType);
3053 ImpCastExprToType(RHS, compositeType);
Daniel Dunbara7b5fb92008-09-11 23:12:46 +00003054 return compositeType;
3055 }
3056 }
3057
Chris Lattner992ae932008-01-06 22:42:25 +00003058 // Otherwise, the operands are not compatible.
Chris Lattnere2897262009-02-18 04:28:32 +00003059 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3060 << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003061 return QualType();
3062}
3063
Steve Naroff87d58b42007-09-16 03:34:24 +00003064/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattner4b009652007-07-25 00:24:17 +00003065/// in the case of a the GNU conditional expr extension.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003066Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3067 SourceLocation ColonLoc,
3068 ExprArg Cond, ExprArg LHS,
3069 ExprArg RHS) {
3070 Expr *CondExpr = (Expr *) Cond.get();
3071 Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
Chris Lattner98a425c2007-11-26 01:40:58 +00003072
3073 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3074 // was the condition.
3075 bool isLHSNull = LHSExpr == 0;
3076 if (isLHSNull)
3077 LHSExpr = CondExpr;
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003078
3079 QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
Chris Lattner4b009652007-07-25 00:24:17 +00003080 RHSExpr, QuestionLoc);
3081 if (result.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00003082 return ExprError();
3083
3084 Cond.release();
3085 LHS.release();
3086 RHS.release();
Mike Stump9afab102009-02-19 03:04:26 +00003087 return Owned(new (Context) ConditionalOperator(CondExpr,
Steve Naroff774e4152009-01-21 00:14:39 +00003088 isLHSNull ? 0 : LHSExpr,
3089 RHSExpr, result));
Chris Lattner4b009652007-07-25 00:24:17 +00003090}
3091
Chris Lattner4b009652007-07-25 00:24:17 +00003092
3093// CheckPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump9afab102009-02-19 03:04:26 +00003094// being closely modeled after the C99 spec:-). The odd characteristic of this
Chris Lattner4b009652007-07-25 00:24:17 +00003095// routine is it effectively iqnores the qualifiers on the top level pointee.
3096// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3097// FIXME: add a couple examples in this comment.
Mike Stump9afab102009-02-19 03:04:26 +00003098Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003099Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3100 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003101
Chris Lattner4b009652007-07-25 00:24:17 +00003102 // get the "pointed to" type (ignoring qualifiers at the top level)
Chris Lattner71225142007-07-31 21:27:01 +00003103 lhptee = lhsType->getAsPointerType()->getPointeeType();
3104 rhptee = rhsType->getAsPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003105
Chris Lattner4b009652007-07-25 00:24:17 +00003106 // make sure we operate on the canonical type
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003107 lhptee = Context.getCanonicalType(lhptee);
3108 rhptee = Context.getCanonicalType(rhptee);
Chris Lattner4b009652007-07-25 00:24:17 +00003109
Chris Lattner005ed752008-01-04 18:04:52 +00003110 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003111
3112 // C99 6.5.16.1p1: This following citation is common to constraints
3113 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3114 // qualifiers of the type *pointed to* by the right;
Fariborz Jahanianb60352a2009-02-17 18:27:45 +00003115 // FIXME: Handle ExtQualType
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003116 if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
Chris Lattner005ed752008-01-04 18:04:52 +00003117 ConvTy = CompatiblePointerDiscardsQualifiers;
Chris Lattner4b009652007-07-25 00:24:17 +00003118
Mike Stump9afab102009-02-19 03:04:26 +00003119 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3120 // incomplete type and the other is a pointer to a qualified or unqualified
Chris Lattner4b009652007-07-25 00:24:17 +00003121 // version of void...
Chris Lattner4ca3d772008-01-03 22:56:36 +00003122 if (lhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003123 if (rhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003124 return ConvTy;
Mike Stump9afab102009-02-19 03:04:26 +00003125
Chris Lattner4ca3d772008-01-03 22:56:36 +00003126 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003127 assert(rhptee->isFunctionType());
3128 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003129 }
Mike Stump9afab102009-02-19 03:04:26 +00003130
Chris Lattner4ca3d772008-01-03 22:56:36 +00003131 if (rhptee->isVoidType()) {
Chris Lattner9db553e2008-04-02 06:59:01 +00003132 if (lhptee->isIncompleteOrObjectType())
Chris Lattner005ed752008-01-04 18:04:52 +00003133 return ConvTy;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003134
3135 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattner9db553e2008-04-02 06:59:01 +00003136 assert(lhptee->isFunctionType());
3137 return FunctionVoidPointer;
Chris Lattner4ca3d772008-01-03 22:56:36 +00003138 }
Mike Stump9afab102009-02-19 03:04:26 +00003139 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Chris Lattner4b009652007-07-25 00:24:17 +00003140 // unqualified versions of compatible types, ...
Eli Friedman6ca28cb2009-03-22 23:59:44 +00003141 lhptee = lhptee.getUnqualifiedType();
3142 rhptee = rhptee.getUnqualifiedType();
3143 if (!Context.typesAreCompatible(lhptee, rhptee)) {
3144 // Check if the pointee types are compatible ignoring the sign.
3145 // We explicitly check for char so that we catch "char" vs
3146 // "unsigned char" on systems where "char" is unsigned.
3147 if (lhptee->isCharType()) {
3148 lhptee = Context.UnsignedCharTy;
3149 } else if (lhptee->isSignedIntegerType()) {
3150 lhptee = Context.getCorrespondingUnsignedType(lhptee);
3151 }
3152 if (rhptee->isCharType()) {
3153 rhptee = Context.UnsignedCharTy;
3154 } else if (rhptee->isSignedIntegerType()) {
3155 rhptee = Context.getCorrespondingUnsignedType(rhptee);
3156 }
3157 if (lhptee == rhptee) {
3158 // Types are compatible ignoring the sign. Qualifier incompatibility
3159 // takes priority over sign incompatibility because the sign
3160 // warning can be disabled.
3161 if (ConvTy != Compatible)
3162 return ConvTy;
3163 return IncompatiblePointerSign;
3164 }
3165 // General pointer incompatibility takes priority over qualifiers.
3166 return IncompatiblePointer;
3167 }
Chris Lattner005ed752008-01-04 18:04:52 +00003168 return ConvTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003169}
3170
Steve Naroff3454b6c2008-09-04 15:10:53 +00003171/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3172/// block pointer types are compatible or whether a block and normal pointer
3173/// are compatible. It is more restrict than comparing two function pointer
3174// types.
Mike Stump9afab102009-02-19 03:04:26 +00003175Sema::AssignConvertType
3176Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
Steve Naroff3454b6c2008-09-04 15:10:53 +00003177 QualType rhsType) {
3178 QualType lhptee, rhptee;
Mike Stump9afab102009-02-19 03:04:26 +00003179
Steve Naroff3454b6c2008-09-04 15:10:53 +00003180 // get the "pointed to" type (ignoring qualifiers at the top level)
3181 lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003182 rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
3183
Steve Naroff3454b6c2008-09-04 15:10:53 +00003184 // make sure we operate on the canonical type
3185 lhptee = Context.getCanonicalType(lhptee);
3186 rhptee = Context.getCanonicalType(rhptee);
Mike Stump9afab102009-02-19 03:04:26 +00003187
Steve Naroff3454b6c2008-09-04 15:10:53 +00003188 AssignConvertType ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00003189
Steve Naroff3454b6c2008-09-04 15:10:53 +00003190 // For blocks we enforce that qualifiers are identical.
3191 if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3192 ConvTy = CompatiblePointerDiscardsQualifiers;
Mike Stump9afab102009-02-19 03:04:26 +00003193
Steve Naroff3454b6c2008-09-04 15:10:53 +00003194 if (!Context.typesAreBlockCompatible(lhptee, rhptee))
Mike Stump9afab102009-02-19 03:04:26 +00003195 return IncompatibleBlockPointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003196 return ConvTy;
3197}
3198
Mike Stump9afab102009-02-19 03:04:26 +00003199/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3200/// has code to accommodate several GCC extensions when type checking
Chris Lattner4b009652007-07-25 00:24:17 +00003201/// pointers. Here are some objectionable examples that GCC considers warnings:
3202///
3203/// int a, *pint;
3204/// short *pshort;
3205/// struct foo *pfoo;
3206///
3207/// pint = pshort; // warning: assignment from incompatible pointer type
3208/// a = pint; // warning: assignment makes integer from pointer without a cast
3209/// pint = a; // warning: assignment makes pointer from integer without a cast
3210/// pint = pfoo; // warning: assignment from incompatible pointer type
3211///
3212/// As a result, the code for dealing with pointers is more complex than the
Mike Stump9afab102009-02-19 03:04:26 +00003213/// C99 spec dictates.
Chris Lattner4b009652007-07-25 00:24:17 +00003214///
Chris Lattner005ed752008-01-04 18:04:52 +00003215Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003216Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
Chris Lattner1853da22008-01-04 23:18:45 +00003217 // Get canonical types. We're not formatting these types, just comparing
3218 // them.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003219 lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3220 rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
Eli Friedman48d0bb02008-05-30 18:07:22 +00003221
3222 if (lhsType == rhsType)
Chris Lattnerfdd96d72008-01-07 17:51:46 +00003223 return Compatible; // Common case: fast path an exact match.
Chris Lattner4b009652007-07-25 00:24:17 +00003224
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003225 // If the left-hand side is a reference type, then we are in a
3226 // (rare!) case where we've allowed the use of references in C,
3227 // e.g., as a parameter type in a built-in function. In this case,
3228 // just make sure that the type referenced is compatible with the
3229 // right-hand side type. The caller is responsible for adjusting
3230 // lhsType so that the resulting expression does not have reference
3231 // type.
3232 if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
3233 if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
Anders Carlssoncebb8d62007-10-12 23:56:29 +00003234 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003235 return Incompatible;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003236 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003237
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003238 if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
3239 if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003240 return Compatible;
Steve Naroff936c4362008-06-03 14:04:54 +00003241 // Relax integer conversions like we do for pointers below.
3242 if (rhsType->isIntegerType())
3243 return IntToPointer;
3244 if (lhsType->isIntegerType())
3245 return PointerToInt;
Steve Naroff19608432008-10-14 22:18:38 +00003246 return IncompatibleObjCQualifiedId;
Fariborz Jahanian957442d2007-12-19 17:45:58 +00003247 }
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003248
Nate Begemanc5f0f652008-07-14 18:02:46 +00003249 if (lhsType->isVectorType() || rhsType->isVectorType()) {
Nate Begemanaf6ed502008-04-18 23:10:10 +00003250 // For ExtVector, allow vector splats; float -> <n x float>
Nate Begemanc5f0f652008-07-14 18:02:46 +00003251 if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
3252 if (LV->getElementType() == rhsType)
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003253 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003254
Nate Begemanc5f0f652008-07-14 18:02:46 +00003255 // If we are allowing lax vector conversions, and LHS and RHS are both
Mike Stump9afab102009-02-19 03:04:26 +00003256 // vectors, the total size only needs to be the same. This is a bitcast;
Nate Begemanc5f0f652008-07-14 18:02:46 +00003257 // no bits are changed but the result type is different.
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003258 if (getLangOptions().LaxVectorConversions &&
3259 lhsType->isVectorType() && rhsType->isVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003260 if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
Anders Carlsson355ed052009-01-30 23:17:46 +00003261 return IncompatibleVectors;
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003262 }
3263 return Incompatible;
Mike Stump9afab102009-02-19 03:04:26 +00003264 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003265
Chris Lattnerdb22bf42008-01-04 23:32:24 +00003266 if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
Chris Lattner4b009652007-07-25 00:24:17 +00003267 return Compatible;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003268
Chris Lattner390564e2008-04-07 06:49:41 +00003269 if (isa<PointerType>(lhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003270 if (rhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003271 return IntToPointer;
Eli Friedman48d0bb02008-05-30 18:07:22 +00003272
Chris Lattner390564e2008-04-07 06:49:41 +00003273 if (isa<PointerType>(rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003274 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003275
Steve Naroffa982c712008-09-29 18:10:17 +00003276 if (rhsType->getAsBlockPointerType()) {
Steve Naroffd6163f32008-09-05 22:11:13 +00003277 if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003278 return Compatible;
Steve Naroffa982c712008-09-29 18:10:17 +00003279
3280 // Treat block pointers as objects.
3281 if (getLangOptions().ObjC1 &&
3282 lhsType == Context.getCanonicalType(Context.getObjCIdType()))
3283 return Compatible;
3284 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003285 return Incompatible;
3286 }
3287
3288 if (isa<BlockPointerType>(lhsType)) {
3289 if (rhsType->isIntegerType())
Eli Friedmanc5898302009-02-25 04:20:42 +00003290 return IntToBlockPointer;
Mike Stump9afab102009-02-19 03:04:26 +00003291
Steve Naroffa982c712008-09-29 18:10:17 +00003292 // Treat block pointers as objects.
3293 if (getLangOptions().ObjC1 &&
3294 rhsType == Context.getCanonicalType(Context.getObjCIdType()))
3295 return Compatible;
3296
Steve Naroff3454b6c2008-09-04 15:10:53 +00003297 if (rhsType->isBlockPointerType())
3298 return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003299
Steve Naroff3454b6c2008-09-04 15:10:53 +00003300 if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
3301 if (RHSPT->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003302 return Compatible;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003303 }
Chris Lattner1853da22008-01-04 23:18:45 +00003304 return Incompatible;
3305 }
3306
Chris Lattner390564e2008-04-07 06:49:41 +00003307 if (isa<PointerType>(rhsType)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003308 // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
Eli Friedman48d0bb02008-05-30 18:07:22 +00003309 if (lhsType == Context.BoolTy)
3310 return Compatible;
3311
3312 if (lhsType->isIntegerType())
Chris Lattnerd951b7b2008-01-04 18:22:42 +00003313 return PointerToInt;
Chris Lattner4b009652007-07-25 00:24:17 +00003314
Mike Stump9afab102009-02-19 03:04:26 +00003315 if (isa<PointerType>(lhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003316 return CheckPointerTypesForAssignment(lhsType, rhsType);
Mike Stump9afab102009-02-19 03:04:26 +00003317
3318 if (isa<BlockPointerType>(lhsType) &&
Steve Naroff3454b6c2008-09-04 15:10:53 +00003319 rhsType->getAsPointerType()->getPointeeType()->isVoidType())
Douglas Gregor7abc1432008-11-27 00:44:28 +00003320 return Compatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003321 return Incompatible;
Chris Lattner1853da22008-01-04 23:18:45 +00003322 }
Eli Friedman48d0bb02008-05-30 18:07:22 +00003323
Chris Lattner1853da22008-01-04 23:18:45 +00003324 if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
Chris Lattner390564e2008-04-07 06:49:41 +00003325 if (Context.typesAreCompatible(lhsType, rhsType))
Chris Lattner4b009652007-07-25 00:24:17 +00003326 return Compatible;
Chris Lattner4b009652007-07-25 00:24:17 +00003327 }
3328 return Incompatible;
3329}
3330
Douglas Gregor144b06c2009-04-29 22:16:16 +00003331/// \brief Constructs a transparent union from an expression that is
3332/// used to initialize the transparent union.
3333static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3334 QualType UnionType, FieldDecl *Field) {
3335 // Build an initializer list that designates the appropriate member
3336 // of the transparent union.
3337 InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3338 &E, 1,
3339 SourceLocation());
3340 Initializer->setType(UnionType);
3341 Initializer->setInitializedFieldInUnion(Field);
3342
3343 // Build a compound literal constructing a value of the transparent
3344 // union type from this initializer list.
3345 E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3346 false);
3347}
3348
3349Sema::AssignConvertType
3350Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3351 QualType FromType = rExpr->getType();
3352
3353 // If the ArgType is a Union type, we want to handle a potential
3354 // transparent_union GCC extension.
3355 const RecordType *UT = ArgType->getAsUnionType();
3356 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
3357 return Incompatible;
3358
3359 // The field to initialize within the transparent union.
3360 RecordDecl *UD = UT->getDecl();
3361 FieldDecl *InitField = 0;
3362 // It's compatible if the expression matches any of the fields.
3363 for (RecordDecl::field_iterator it = UD->field_begin(Context),
3364 itend = UD->field_end(Context);
3365 it != itend; ++it) {
3366 if (it->getType()->isPointerType()) {
3367 // If the transparent union contains a pointer type, we allow:
3368 // 1) void pointer
3369 // 2) null pointer constant
3370 if (FromType->isPointerType())
3371 if (FromType->getAsPointerType()->getPointeeType()->isVoidType()) {
3372 ImpCastExprToType(rExpr, it->getType());
3373 InitField = *it;
3374 break;
3375 }
3376
3377 if (rExpr->isNullPointerConstant(Context)) {
3378 ImpCastExprToType(rExpr, it->getType());
3379 InitField = *it;
3380 break;
3381 }
3382 }
3383
3384 if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3385 == Compatible) {
3386 InitField = *it;
3387 break;
3388 }
3389 }
3390
3391 if (!InitField)
3392 return Incompatible;
3393
3394 ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3395 return Compatible;
3396}
3397
Chris Lattner005ed752008-01-04 18:04:52 +00003398Sema::AssignConvertType
Chris Lattner4b009652007-07-25 00:24:17 +00003399Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003400 if (getLangOptions().CPlusPlus) {
3401 if (!lhsType->isRecordType()) {
3402 // C++ 5.17p3: If the left operand is not of class type, the
3403 // expression is implicitly converted (C++ 4) to the
3404 // cv-unqualified type of the left operand.
Douglas Gregor6fd35572008-12-19 17:40:08 +00003405 if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3406 "assigning"))
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003407 return Incompatible;
Chris Lattner79e9a422009-04-12 09:02:39 +00003408 return Compatible;
Douglas Gregor6573cfd2008-10-21 23:43:52 +00003409 }
3410
3411 // FIXME: Currently, we fall through and treat C++ classes like C
3412 // structures.
3413 }
3414
Steve Naroffcdee22d2007-11-27 17:58:44 +00003415 // C99 6.5.16.1p1: the left operand is a pointer and the right is
3416 // a null pointer constant.
Steve Naroffd305a862009-02-21 21:17:01 +00003417 if ((lhsType->isPointerType() ||
3418 lhsType->isObjCQualifiedIdType() ||
Mike Stump9afab102009-02-19 03:04:26 +00003419 lhsType->isBlockPointerType())
Fariborz Jahaniana13effb2008-01-03 18:46:52 +00003420 && rExpr->isNullPointerConstant(Context)) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003421 ImpCastExprToType(rExpr, lhsType);
Steve Naroffcdee22d2007-11-27 17:58:44 +00003422 return Compatible;
3423 }
Mike Stump9afab102009-02-19 03:04:26 +00003424
Chris Lattner5f505bf2007-10-16 02:55:40 +00003425 // This check seems unnatural, however it is necessary to ensure the proper
Chris Lattner4b009652007-07-25 00:24:17 +00003426 // conversion of functions/arrays. If the conversion were done for all
Steve Naroff0acc9c92007-09-15 18:49:24 +00003427 // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
Chris Lattner4b009652007-07-25 00:24:17 +00003428 // expressions that surpress this implicit conversion (&, sizeof).
Chris Lattner5f505bf2007-10-16 02:55:40 +00003429 //
Mike Stump9afab102009-02-19 03:04:26 +00003430 // Suppress this for references: C++ 8.5.3p5.
Chris Lattner5f505bf2007-10-16 02:55:40 +00003431 if (!lhsType->isReferenceType())
3432 DefaultFunctionArrayConversion(rExpr);
Steve Naroff0f32f432007-08-24 22:33:52 +00003433
Chris Lattner005ed752008-01-04 18:04:52 +00003434 Sema::AssignConvertType result =
3435 CheckAssignmentConstraints(lhsType, rExpr->getType());
Mike Stump9afab102009-02-19 03:04:26 +00003436
Steve Naroff0f32f432007-08-24 22:33:52 +00003437 // C99 6.5.16.1p2: The value of the right operand is converted to the
3438 // type of the assignment expression.
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003439 // CheckAssignmentConstraints allows the left-hand side to be a reference,
3440 // so that we can use references in built-in functions even in C.
3441 // The getNonReferenceType() call makes sure that the resulting expression
3442 // does not have reference type.
Douglas Gregor144b06c2009-04-29 22:16:16 +00003443 if (result != Incompatible && rExpr->getType() != lhsType)
Douglas Gregor0d5d89d2008-10-28 00:22:11 +00003444 ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
Steve Naroff0f32f432007-08-24 22:33:52 +00003445 return result;
Chris Lattner4b009652007-07-25 00:24:17 +00003446}
3447
Chris Lattner1eafdea2008-11-18 01:30:42 +00003448QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003449 Diag(Loc, diag::err_typecheck_invalid_operands)
Chris Lattnerda5c0872008-11-23 09:13:29 +00003450 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003451 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner2c8bff72007-12-12 05:47:28 +00003452 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00003453}
3454
Mike Stump9afab102009-02-19 03:04:26 +00003455inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
Chris Lattner4b009652007-07-25 00:24:17 +00003456 Expr *&rex) {
Mike Stump9afab102009-02-19 03:04:26 +00003457 // For conversion purposes, we ignore any qualifiers.
Nate Begeman03105572008-04-04 01:30:25 +00003458 // For example, "const float" and "float" are equivalent.
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003459 QualType lhsType =
3460 Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3461 QualType rhsType =
3462 Context.getCanonicalType(rex->getType()).getUnqualifiedType();
Mike Stump9afab102009-02-19 03:04:26 +00003463
Nate Begemanc5f0f652008-07-14 18:02:46 +00003464 // If the vector types are identical, return.
Nate Begeman03105572008-04-04 01:30:25 +00003465 if (lhsType == rhsType)
Chris Lattner4b009652007-07-25 00:24:17 +00003466 return lhsType;
Nate Begemanec2d1062007-12-30 02:59:45 +00003467
Nate Begemanc5f0f652008-07-14 18:02:46 +00003468 // Handle the case of a vector & extvector type of the same size and element
3469 // type. It would be nice if we only had one vector type someday.
Anders Carlsson355ed052009-01-30 23:17:46 +00003470 if (getLangOptions().LaxVectorConversions) {
3471 // FIXME: Should we warn here?
3472 if (const VectorType *LV = lhsType->getAsVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003473 if (const VectorType *RV = rhsType->getAsVectorType())
3474 if (LV->getElementType() == RV->getElementType() &&
Anders Carlsson355ed052009-01-30 23:17:46 +00003475 LV->getNumElements() == RV->getNumElements()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003476 return lhsType->isExtVectorType() ? lhsType : rhsType;
Anders Carlsson355ed052009-01-30 23:17:46 +00003477 }
3478 }
3479 }
Mike Stump9afab102009-02-19 03:04:26 +00003480
Nate Begemanc5f0f652008-07-14 18:02:46 +00003481 // If the lhs is an extended vector and the rhs is a scalar of the same type
3482 // or a literal, promote the rhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003483 if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003484 QualType eltType = V->getElementType();
Mike Stump9afab102009-02-19 03:04:26 +00003485
3486 if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003487 (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
3488 (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003489 ImpCastExprToType(rex, lhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003490 return lhsType;
3491 }
3492 }
3493
Nate Begemanc5f0f652008-07-14 18:02:46 +00003494 // If the rhs is an extended vector and the lhs is a scalar of the same type,
Nate Begemanec2d1062007-12-30 02:59:45 +00003495 // promote the lhs to the vector type.
Nate Begemanaf6ed502008-04-18 23:10:10 +00003496 if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
Nate Begemanc5f0f652008-07-14 18:02:46 +00003497 QualType eltType = V->getElementType();
3498
Mike Stump9afab102009-02-19 03:04:26 +00003499 if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
Nate Begemanc5f0f652008-07-14 18:02:46 +00003500 (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
3501 (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
Chris Lattnere992d6c2008-01-16 19:17:22 +00003502 ImpCastExprToType(lex, rhsType);
Nate Begemanec2d1062007-12-30 02:59:45 +00003503 return rhsType;
3504 }
3505 }
3506
Chris Lattner4b009652007-07-25 00:24:17 +00003507 // You cannot convert between vector values of different size.
Chris Lattner70b93d82008-11-18 22:52:51 +00003508 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003509 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003510 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003511 return QualType();
Sebastian Redl95216a62009-02-07 00:15:38 +00003512}
3513
Chris Lattner4b009652007-07-25 00:24:17 +00003514inline QualType Sema::CheckMultiplyDivideOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003515 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003516{
Daniel Dunbar2f08d812009-01-05 22:42:10 +00003517 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003518 return CheckVectorOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003519
Steve Naroff8f708362007-08-24 19:07:16 +00003520 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003521
Chris Lattner4b009652007-07-25 00:24:17 +00003522 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
Steve Naroff8f708362007-08-24 19:07:16 +00003523 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003524 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003525}
3526
3527inline QualType Sema::CheckRemainderOperands(
Mike Stump9afab102009-02-19 03:04:26 +00003528 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00003529{
Daniel Dunbarb27282f2009-01-05 22:55:36 +00003530 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3531 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3532 return CheckVectorOperands(Loc, lex, rex);
3533 return InvalidOperands(Loc, lex, rex);
3534 }
Chris Lattner4b009652007-07-25 00:24:17 +00003535
Steve Naroff8f708362007-08-24 19:07:16 +00003536 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00003537
Chris Lattner4b009652007-07-25 00:24:17 +00003538 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00003539 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00003540 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003541}
3542
3543inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
Eli Friedman3cd92882009-03-28 01:22:36 +00003544 Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
Chris Lattner4b009652007-07-25 00:24:17 +00003545{
Eli Friedman3cd92882009-03-28 01:22:36 +00003546 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3547 QualType compType = CheckVectorOperands(Loc, lex, rex);
3548 if (CompLHSTy) *CompLHSTy = compType;
3549 return compType;
3550 }
Chris Lattner4b009652007-07-25 00:24:17 +00003551
Eli Friedman3cd92882009-03-28 01:22:36 +00003552 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003553
Chris Lattner4b009652007-07-25 00:24:17 +00003554 // handle the common case first (both operands are arithmetic).
Eli Friedman3cd92882009-03-28 01:22:36 +00003555 if (lex->getType()->isArithmeticType() &&
3556 rex->getType()->isArithmeticType()) {
3557 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003558 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003559 }
Chris Lattner4b009652007-07-25 00:24:17 +00003560
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003561 // Put any potential pointer into PExp
3562 Expr* PExp = lex, *IExp = rex;
3563 if (IExp->getType()->isPointerType())
3564 std::swap(PExp, IExp);
3565
Chris Lattner184f92d2009-04-24 23:50:08 +00003566 if (const PointerType *PTy = PExp->getType()->getAsPointerType()) {
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003567 if (IExp->getType()->isIntegerType()) {
Chris Lattner184f92d2009-04-24 23:50:08 +00003568 QualType PointeeTy = PTy->getPointeeType();
3569 // Check for arithmetic on pointers to incomplete types.
3570 if (PointeeTy->isVoidType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003571 if (getLangOptions().CPlusPlus) {
3572 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
Chris Lattner8ba580c2008-11-19 05:08:23 +00003573 << lex->getSourceRange() << rex->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00003574 return QualType();
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003575 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003576
3577 // GNU extension: arithmetic on pointer to void
3578 Diag(Loc, diag::ext_gnu_void_ptr)
3579 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner184f92d2009-04-24 23:50:08 +00003580 } else if (PointeeTy->isFunctionType()) {
Douglas Gregor05e28f62009-03-24 19:52:54 +00003581 if (getLangOptions().CPlusPlus) {
3582 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3583 << lex->getType() << lex->getSourceRange();
3584 return QualType();
3585 }
3586
3587 // GNU extension: arithmetic on pointer to function
3588 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3589 << lex->getType() << lex->getSourceRange();
3590 } else if (!PTy->isDependentType() &&
Chris Lattner184f92d2009-04-24 23:50:08 +00003591 RequireCompleteType(Loc, PointeeTy,
Douglas Gregor05e28f62009-03-24 19:52:54 +00003592 diag::err_typecheck_arithmetic_incomplete_type,
Chris Lattner184f92d2009-04-24 23:50:08 +00003593 PExp->getSourceRange(), SourceRange(),
3594 PExp->getType()))
Douglas Gregor05e28f62009-03-24 19:52:54 +00003595 return QualType();
3596
Chris Lattner184f92d2009-04-24 23:50:08 +00003597 // Diagnose bad cases where we step over interface counts.
3598 if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3599 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3600 << PointeeTy << PExp->getSourceRange();
3601 return QualType();
3602 }
3603
Eli Friedman3cd92882009-03-28 01:22:36 +00003604 if (CompLHSTy) {
3605 QualType LHSTy = lex->getType();
3606 if (LHSTy->isPromotableIntegerType())
3607 LHSTy = Context.IntTy;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00003608 else {
3609 QualType T = isPromotableBitField(lex, Context);
3610 if (!T.isNull())
3611 LHSTy = T;
3612 }
3613
Eli Friedman3cd92882009-03-28 01:22:36 +00003614 *CompLHSTy = LHSTy;
3615 }
Eli Friedmand9b1fec2008-05-18 18:08:51 +00003616 return PExp->getType();
3617 }
3618 }
3619
Chris Lattner1eafdea2008-11-18 01:30:42 +00003620 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003621}
3622
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003623// C99 6.5.6
3624QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
Eli Friedman3cd92882009-03-28 01:22:36 +00003625 SourceLocation Loc, QualType* CompLHSTy) {
3626 if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3627 QualType compType = CheckVectorOperands(Loc, lex, rex);
3628 if (CompLHSTy) *CompLHSTy = compType;
3629 return compType;
3630 }
Mike Stump9afab102009-02-19 03:04:26 +00003631
Eli Friedman3cd92882009-03-28 01:22:36 +00003632 QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
Mike Stump9afab102009-02-19 03:04:26 +00003633
Chris Lattnerf6da2912007-12-09 21:53:25 +00003634 // Enforce type constraints: C99 6.5.6p3.
Mike Stump9afab102009-02-19 03:04:26 +00003635
Chris Lattnerf6da2912007-12-09 21:53:25 +00003636 // Handle the common case first (both operands are arithmetic).
Mike Stumpea3d74e2009-05-07 18:43:07 +00003637 if (lex->getType()->isArithmeticType()
3638 && rex->getType()->isArithmeticType()) {
Eli Friedman3cd92882009-03-28 01:22:36 +00003639 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroff8f708362007-08-24 19:07:16 +00003640 return compType;
Eli Friedman3cd92882009-03-28 01:22:36 +00003641 }
Mike Stump9afab102009-02-19 03:04:26 +00003642
Chris Lattnerf6da2912007-12-09 21:53:25 +00003643 // Either ptr - int or ptr - ptr.
3644 if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
Steve Naroff577f9722008-01-29 18:58:14 +00003645 QualType lpointee = LHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003646
Douglas Gregor05e28f62009-03-24 19:52:54 +00003647 // The LHS must be an completely-defined object type.
Douglas Gregorb3193242009-01-23 00:36:41 +00003648
Douglas Gregor05e28f62009-03-24 19:52:54 +00003649 bool ComplainAboutVoid = false;
3650 Expr *ComplainAboutFunc = 0;
3651 if (lpointee->isVoidType()) {
3652 if (getLangOptions().CPlusPlus) {
3653 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3654 << lex->getSourceRange() << rex->getSourceRange();
3655 return QualType();
3656 }
3657
3658 // GNU C extension: arithmetic on pointer to void
3659 ComplainAboutVoid = true;
3660 } else if (lpointee->isFunctionType()) {
3661 if (getLangOptions().CPlusPlus) {
3662 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003663 << lex->getType() << lex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003664 return QualType();
3665 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003666
3667 // GNU C extension: arithmetic on pointer to function
3668 ComplainAboutFunc = lex;
3669 } else if (!lpointee->isDependentType() &&
3670 RequireCompleteType(Loc, lpointee,
3671 diag::err_typecheck_sub_ptr_object,
3672 lex->getSourceRange(),
3673 SourceRange(),
3674 lex->getType()))
3675 return QualType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003676
Chris Lattner184f92d2009-04-24 23:50:08 +00003677 // Diagnose bad cases where we step over interface counts.
3678 if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3679 Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3680 << lpointee << lex->getSourceRange();
3681 return QualType();
3682 }
3683
Chris Lattnerf6da2912007-12-09 21:53:25 +00003684 // The result type of a pointer-int computation is the pointer type.
Douglas Gregor05e28f62009-03-24 19:52:54 +00003685 if (rex->getType()->isIntegerType()) {
3686 if (ComplainAboutVoid)
3687 Diag(Loc, diag::ext_gnu_void_ptr)
3688 << lex->getSourceRange() << rex->getSourceRange();
3689 if (ComplainAboutFunc)
3690 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3691 << ComplainAboutFunc->getType()
3692 << ComplainAboutFunc->getSourceRange();
3693
Eli Friedman3cd92882009-03-28 01:22:36 +00003694 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003695 return lex->getType();
Douglas Gregor05e28f62009-03-24 19:52:54 +00003696 }
Mike Stump9afab102009-02-19 03:04:26 +00003697
Chris Lattnerf6da2912007-12-09 21:53:25 +00003698 // Handle pointer-pointer subtractions.
3699 if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
Eli Friedman50727042008-02-08 01:19:44 +00003700 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003701
Douglas Gregor05e28f62009-03-24 19:52:54 +00003702 // RHS must be a completely-type object type.
3703 // Handle the GNU void* extension.
3704 if (rpointee->isVoidType()) {
3705 if (getLangOptions().CPlusPlus) {
3706 Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3707 << lex->getSourceRange() << rex->getSourceRange();
3708 return QualType();
3709 }
Mike Stump9afab102009-02-19 03:04:26 +00003710
Douglas Gregor05e28f62009-03-24 19:52:54 +00003711 ComplainAboutVoid = true;
3712 } else if (rpointee->isFunctionType()) {
3713 if (getLangOptions().CPlusPlus) {
3714 Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003715 << rex->getType() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003716 return QualType();
3717 }
Douglas Gregor05e28f62009-03-24 19:52:54 +00003718
3719 // GNU extension: arithmetic on pointer to function
3720 if (!ComplainAboutFunc)
3721 ComplainAboutFunc = rex;
3722 } else if (!rpointee->isDependentType() &&
3723 RequireCompleteType(Loc, rpointee,
3724 diag::err_typecheck_sub_ptr_object,
3725 rex->getSourceRange(),
3726 SourceRange(),
3727 rex->getType()))
3728 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00003729
Chris Lattnerf6da2912007-12-09 21:53:25 +00003730 // Pointee types must be compatible.
Eli Friedman583c31e2008-09-02 05:09:35 +00003731 if (!Context.typesAreCompatible(
Mike Stump9afab102009-02-19 03:04:26 +00003732 Context.getCanonicalType(lpointee).getUnqualifiedType(),
Eli Friedman583c31e2008-09-02 05:09:35 +00003733 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003734 Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003735 << lex->getType() << rex->getType()
Chris Lattner70b93d82008-11-18 22:52:51 +00003736 << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003737 return QualType();
3738 }
Mike Stump9afab102009-02-19 03:04:26 +00003739
Douglas Gregor05e28f62009-03-24 19:52:54 +00003740 if (ComplainAboutVoid)
3741 Diag(Loc, diag::ext_gnu_void_ptr)
3742 << lex->getSourceRange() << rex->getSourceRange();
3743 if (ComplainAboutFunc)
3744 Diag(Loc, diag::ext_gnu_ptr_func_arith)
3745 << ComplainAboutFunc->getType()
3746 << ComplainAboutFunc->getSourceRange();
Eli Friedman3cd92882009-03-28 01:22:36 +00003747
3748 if (CompLHSTy) *CompLHSTy = lex->getType();
Chris Lattnerf6da2912007-12-09 21:53:25 +00003749 return Context.getPointerDiffType();
3750 }
3751 }
Mike Stump9afab102009-02-19 03:04:26 +00003752
Chris Lattner1eafdea2008-11-18 01:30:42 +00003753 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00003754}
3755
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003756// C99 6.5.7
Chris Lattner1eafdea2008-11-18 01:30:42 +00003757QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Chris Lattnerfe1f4032008-04-07 05:30:13 +00003758 bool isCompAssign) {
Chris Lattner2c8bff72007-12-12 05:47:28 +00003759 // C99 6.5.7p2: Each of the operands shall have integer type.
3760 if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003761 return InvalidOperands(Loc, lex, rex);
Mike Stump9afab102009-02-19 03:04:26 +00003762
Chris Lattner2c8bff72007-12-12 05:47:28 +00003763 // Shifts don't perform usual arithmetic conversions, they just do integer
3764 // promotions on each operand. C99 6.5.7p3
Eli Friedman3cd92882009-03-28 01:22:36 +00003765 QualType LHSTy;
3766 if (lex->getType()->isPromotableIntegerType())
3767 LHSTy = Context.IntTy;
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00003768 else {
3769 LHSTy = isPromotableBitField(lex, Context);
3770 if (LHSTy.isNull())
3771 LHSTy = lex->getType();
3772 }
Chris Lattnerbb19bc42007-12-13 07:28:16 +00003773 if (!isCompAssign)
Eli Friedman3cd92882009-03-28 01:22:36 +00003774 ImpCastExprToType(lex, LHSTy);
3775
Chris Lattner2c8bff72007-12-12 05:47:28 +00003776 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00003777
Chris Lattner2c8bff72007-12-12 05:47:28 +00003778 // "The type of the result is that of the promoted left operand."
Eli Friedman3cd92882009-03-28 01:22:36 +00003779 return LHSTy;
Chris Lattner4b009652007-07-25 00:24:17 +00003780}
3781
Douglas Gregor30eed0f2009-05-04 06:07:12 +00003782// C99 6.5.8, C++ [expr.rel]
Chris Lattner1eafdea2008-11-18 01:30:42 +00003783QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
Douglas Gregor1f12c352009-04-06 18:45:53 +00003784 unsigned OpaqueOpc, bool isRelational) {
3785 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
3786
Nate Begemanc5f0f652008-07-14 18:02:46 +00003787 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00003788 return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
Mike Stump9afab102009-02-19 03:04:26 +00003789
Chris Lattner254f3bc2007-08-26 01:18:55 +00003790 // C99 6.5.8p3 / C99 6.5.9p4
Steve Naroffecc4fa12007-08-10 18:26:40 +00003791 if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3792 UsualArithmeticConversions(lex, rex);
3793 else {
3794 UsualUnaryConversions(lex);
3795 UsualUnaryConversions(rex);
3796 }
Chris Lattner4b009652007-07-25 00:24:17 +00003797 QualType lType = lex->getType();
3798 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00003799
Mike Stumpea3d74e2009-05-07 18:43:07 +00003800 if (!lType->isFloatingType()
3801 && !(lType->isBlockPointerType() && isRelational)) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003802 // For non-floating point types, check for self-comparisons of the form
3803 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
3804 // often indicate logic errors in the program.
Ted Kremenek264b5cb2009-03-20 19:57:37 +00003805 // NOTE: Don't warn about comparisons of enum constants. These can arise
3806 // from macro expansions, and are usually quite deliberate.
Chris Lattner4e479f92009-03-08 19:39:53 +00003807 Expr *LHSStripped = lex->IgnoreParens();
3808 Expr *RHSStripped = rex->IgnoreParens();
3809 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
3810 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
Ted Kremenekf042dc62009-03-20 18:35:45 +00003811 if (DRL->getDecl() == DRR->getDecl() &&
3812 !isa<EnumConstantDecl>(DRL->getDecl()))
Mike Stump9afab102009-02-19 03:04:26 +00003813 Diag(Loc, diag::warn_selfcomparison);
Chris Lattner4e479f92009-03-08 19:39:53 +00003814
3815 if (isa<CastExpr>(LHSStripped))
3816 LHSStripped = LHSStripped->IgnoreParenCasts();
3817 if (isa<CastExpr>(RHSStripped))
3818 RHSStripped = RHSStripped->IgnoreParenCasts();
3819
3820 // Warn about comparisons against a string constant (unless the other
3821 // operand is null), the user probably wants strcmp.
Douglas Gregor1f12c352009-04-06 18:45:53 +00003822 Expr *literalString = 0;
3823 Expr *literalStringStripped = 0;
Chris Lattner4e479f92009-03-08 19:39:53 +00003824 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00003825 !RHSStripped->isNullPointerConstant(Context)) {
3826 literalString = lex;
3827 literalStringStripped = LHSStripped;
3828 }
Chris Lattner4e479f92009-03-08 19:39:53 +00003829 else if ((isa<StringLiteral>(RHSStripped) ||
3830 isa<ObjCEncodeExpr>(RHSStripped)) &&
Douglas Gregor1f12c352009-04-06 18:45:53 +00003831 !LHSStripped->isNullPointerConstant(Context)) {
3832 literalString = rex;
3833 literalStringStripped = RHSStripped;
3834 }
3835
3836 if (literalString) {
3837 std::string resultComparison;
3838 switch (Opc) {
3839 case BinaryOperator::LT: resultComparison = ") < 0"; break;
3840 case BinaryOperator::GT: resultComparison = ") > 0"; break;
3841 case BinaryOperator::LE: resultComparison = ") <= 0"; break;
3842 case BinaryOperator::GE: resultComparison = ") >= 0"; break;
3843 case BinaryOperator::EQ: resultComparison = ") == 0"; break;
3844 case BinaryOperator::NE: resultComparison = ") != 0"; break;
3845 default: assert(false && "Invalid comparison operator");
3846 }
3847 Diag(Loc, diag::warn_stringcompare)
3848 << isa<ObjCEncodeExpr>(literalStringStripped)
3849 << literalString->getSourceRange()
Douglas Gregor3faaa812009-04-01 23:51:29 +00003850 << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
3851 << CodeModificationHint::CreateInsertion(lex->getLocStart(),
3852 "strcmp(")
3853 << CodeModificationHint::CreateInsertion(
3854 PP.getLocForEndOfToken(rex->getLocEnd()),
Douglas Gregor1f12c352009-04-06 18:45:53 +00003855 resultComparison);
3856 }
Ted Kremenekcf8b77d2007-10-29 16:58:49 +00003857 }
Mike Stump9afab102009-02-19 03:04:26 +00003858
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003859 // The result of comparisons is 'bool' in C++, 'int' in C.
Chris Lattner4e479f92009-03-08 19:39:53 +00003860 QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003861
Chris Lattner254f3bc2007-08-26 01:18:55 +00003862 if (isRelational) {
3863 if (lType->isRealType() && rType->isRealType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003864 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003865 } else {
Ted Kremenek486509e2007-10-29 17:13:39 +00003866 // Check for comparisons of floating point operands using != and ==.
Ted Kremenek486509e2007-10-29 17:13:39 +00003867 if (lType->isFloatingType()) {
Chris Lattner4e479f92009-03-08 19:39:53 +00003868 assert(rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00003869 CheckFloatComparison(Loc,lex,rex);
Ted Kremenek75439142007-10-29 16:40:01 +00003870 }
Mike Stump9afab102009-02-19 03:04:26 +00003871
Chris Lattner254f3bc2007-08-26 01:18:55 +00003872 if (lType->isArithmeticType() && rType->isArithmeticType())
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003873 return ResultTy;
Chris Lattner254f3bc2007-08-26 01:18:55 +00003874 }
Mike Stump9afab102009-02-19 03:04:26 +00003875
Chris Lattner22be8422007-08-26 01:10:14 +00003876 bool LHSIsNull = lex->isNullPointerConstant(Context);
3877 bool RHSIsNull = rex->isNullPointerConstant(Context);
Mike Stump9afab102009-02-19 03:04:26 +00003878
Chris Lattner254f3bc2007-08-26 01:18:55 +00003879 // All of the following pointer related warnings are GCC extensions, except
3880 // when handling null pointer constants. One day, we can consider making them
3881 // errors (when -pedantic-errors is enabled).
Steve Naroffc33c0602007-08-27 04:08:11 +00003882 if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003883 QualType LCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003884 Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
Chris Lattner56a5cd62008-04-03 05:07:25 +00003885 QualType RCanPointeeTy =
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00003886 Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
Mike Stump9afab102009-02-19 03:04:26 +00003887
Douglas Gregor30eed0f2009-05-04 06:07:12 +00003888 // Simple check: if the pointee types are identical, we're done.
3889 if (LCanPointeeTy == RCanPointeeTy)
3890 return ResultTy;
3891
3892 if (getLangOptions().CPlusPlus) {
3893 // C++ [expr.rel]p2:
3894 // [...] Pointer conversions (4.10) and qualification
3895 // conversions (4.4) are performed on pointer operands (or on
3896 // a pointer operand and a null pointer constant) to bring
3897 // them to their composite pointer type. [...]
3898 //
3899 // C++ [expr.eq]p2 uses the same notion for (in)equality
3900 // comparisons of pointers.
Douglas Gregorcf651d22009-05-05 04:50:50 +00003901 QualType T = FindCompositePointerType(lex, rex);
Douglas Gregor30eed0f2009-05-04 06:07:12 +00003902 if (T.isNull()) {
3903 Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
3904 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3905 return QualType();
3906 }
3907
3908 ImpCastExprToType(lex, T);
3909 ImpCastExprToType(rex, T);
3910 return ResultTy;
3911 }
3912
Steve Naroff3b435622007-11-13 14:57:38 +00003913 if (!LHSIsNull && !RHSIsNull && // C99 6.5.9p2
Chris Lattner56a5cd62008-04-03 05:07:25 +00003914 !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3915 !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
Eli Friedman0d9549b2008-08-22 00:56:42 +00003916 RCanPointeeTy.getUnqualifiedType()) &&
Steve Naroff17c03822009-02-12 17:52:19 +00003917 !Context.areComparableObjCPointerTypes(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003918 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003919 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00003920 }
Chris Lattnere992d6c2008-01-16 19:17:22 +00003921 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003922 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00003923 }
Sebastian Redl5d0ead72009-05-10 18:38:11 +00003924 // C++ allows comparison of pointers with null pointer constants.
3925 if (getLangOptions().CPlusPlus) {
3926 if (lType->isPointerType() && RHSIsNull) {
3927 ImpCastExprToType(rex, lType);
3928 return ResultTy;
3929 }
3930 if (rType->isPointerType() && LHSIsNull) {
3931 ImpCastExprToType(lex, rType);
3932 return ResultTy;
3933 }
3934 // And comparison of nullptr_t with itself.
3935 if (lType->isNullPtrType() && rType->isNullPtrType())
3936 return ResultTy;
3937 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003938 // Handle block pointer types.
Mike Stumpe97a8542009-05-07 03:14:14 +00003939 if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
Steve Naroff3454b6c2008-09-04 15:10:53 +00003940 QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3941 QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00003942
Steve Naroff3454b6c2008-09-04 15:10:53 +00003943 if (!LHSIsNull && !RHSIsNull &&
3944 !Context.typesAreBlockCompatible(lpointee, rpointee)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003945 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003946 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3454b6c2008-09-04 15:10:53 +00003947 }
3948 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003949 return ResultTy;
Steve Naroff3454b6c2008-09-04 15:10:53 +00003950 }
Steve Narofff85d66c2008-09-28 01:11:11 +00003951 // Allow block pointers to be compared with null pointer constants.
Mike Stumpe97a8542009-05-07 03:14:14 +00003952 if (!isRelational
3953 && ((lType->isBlockPointerType() && rType->isPointerType())
3954 || (lType->isPointerType() && rType->isBlockPointerType()))) {
Steve Narofff85d66c2008-09-28 01:11:11 +00003955 if (!LHSIsNull && !RHSIsNull) {
Mike Stumpe97a8542009-05-07 03:14:14 +00003956 if (!((rType->isPointerType() && rType->getAsPointerType()
3957 ->getPointeeType()->isVoidType())
3958 || (lType->isPointerType() && lType->getAsPointerType()
3959 ->getPointeeType()->isVoidType())))
3960 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
3961 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Narofff85d66c2008-09-28 01:11:11 +00003962 }
3963 ImpCastExprToType(rex, lType); // promote the pointer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003964 return ResultTy;
Steve Narofff85d66c2008-09-28 01:11:11 +00003965 }
Steve Naroff3454b6c2008-09-04 15:10:53 +00003966
Steve Naroff936c4362008-06-03 14:04:54 +00003967 if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
Steve Naroff3d081ae2008-10-27 10:33:19 +00003968 if (lType->isPointerType() || rType->isPointerType()) {
Steve Naroff030fcda2008-11-17 19:49:16 +00003969 const PointerType *LPT = lType->getAsPointerType();
3970 const PointerType *RPT = rType->getAsPointerType();
Mike Stump9afab102009-02-19 03:04:26 +00003971 bool LPtrToVoid = LPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003972 Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003973 bool RPtrToVoid = RPT ?
Steve Naroff030fcda2008-11-17 19:49:16 +00003974 Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
Mike Stump9afab102009-02-19 03:04:26 +00003975
Steve Naroff030fcda2008-11-17 19:49:16 +00003976 if (!LPtrToVoid && !RPtrToVoid &&
3977 !Context.typesAreCompatible(lType, rType)) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003978 Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
Chris Lattner4bfd2232008-11-24 06:25:27 +00003979 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Steve Naroff3d081ae2008-10-27 10:33:19 +00003980 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003981 return ResultTy;
Steve Naroff3d081ae2008-10-27 10:33:19 +00003982 }
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003983 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003984 return ResultTy;
Steve Naroff3b2ceea2008-10-20 18:19:10 +00003985 }
Steve Naroff936c4362008-06-03 14:04:54 +00003986 if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3987 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003988 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003989 } else {
3990 if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
Chris Lattner70b93d82008-11-18 22:52:51 +00003991 Diag(Loc, diag::warn_incompatible_qualified_id_operands)
Chris Lattner271d4c22008-11-24 05:29:24 +00003992 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Daniel Dunbar11c5f822008-10-23 23:30:52 +00003993 ImpCastExprToType(rex, lType);
Douglas Gregor849ea9c2008-11-19 03:25:36 +00003994 return ResultTy;
Steve Naroff19608432008-10-14 22:18:38 +00003995 }
Steve Naroff936c4362008-06-03 14:04:54 +00003996 }
Fariborz Jahanian5319d9c2007-12-20 01:06:58 +00003997 }
Mike Stump9afab102009-02-19 03:04:26 +00003998 if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
Steve Naroff936c4362008-06-03 14:04:54 +00003999 rType->isIntegerType()) {
Chris Lattner22be8422007-08-26 01:10:14 +00004000 if (!RHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00004001 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004002 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00004003 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004004 return ResultTy;
Steve Naroff4462cb02007-08-16 21:48:38 +00004005 }
Mike Stump9afab102009-02-19 03:04:26 +00004006 if (lType->isIntegerType() &&
Steve Naroff936c4362008-06-03 14:04:54 +00004007 (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
Chris Lattner22be8422007-08-26 01:10:14 +00004008 if (!LHSIsNull)
Chris Lattner70b93d82008-11-18 22:52:51 +00004009 Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004010 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
Chris Lattnere992d6c2008-01-16 19:17:22 +00004011 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004012 return ResultTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004013 }
Steve Naroff4fea7b62008-09-04 16:56:14 +00004014 // Handle block pointers.
Mike Stumpea3d74e2009-05-07 18:43:07 +00004015 if (!isRelational && RHSIsNull
4016 && lType->isBlockPointerType() && rType->isIntegerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004017 ImpCastExprToType(rex, lType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004018 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004019 }
Mike Stumpea3d74e2009-05-07 18:43:07 +00004020 if (!isRelational && LHSIsNull
4021 && lType->isIntegerType() && rType->isBlockPointerType()) {
Steve Naroff4fea7b62008-09-04 16:56:14 +00004022 ImpCastExprToType(lex, rType); // promote the integer to pointer
Douglas Gregor849ea9c2008-11-19 03:25:36 +00004023 return ResultTy;
Steve Naroff4fea7b62008-09-04 16:56:14 +00004024 }
Chris Lattner1eafdea2008-11-18 01:30:42 +00004025 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004026}
4027
Nate Begemanc5f0f652008-07-14 18:02:46 +00004028/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump9afab102009-02-19 03:04:26 +00004029/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004030/// like a scalar comparison, a vector comparison produces a vector of integer
4031/// types.
4032QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
Chris Lattner1eafdea2008-11-18 01:30:42 +00004033 SourceLocation Loc,
Nate Begemanc5f0f652008-07-14 18:02:46 +00004034 bool isRelational) {
4035 // Check to make sure we're operating on vectors of the same type and width,
4036 // Allowing one side to be a scalar of element type.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004037 QualType vType = CheckVectorOperands(Loc, lex, rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004038 if (vType.isNull())
4039 return vType;
Mike Stump9afab102009-02-19 03:04:26 +00004040
Nate Begemanc5f0f652008-07-14 18:02:46 +00004041 QualType lType = lex->getType();
4042 QualType rType = rex->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004043
Nate Begemanc5f0f652008-07-14 18:02:46 +00004044 // For non-floating point types, check for self-comparisons of the form
4045 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
4046 // often indicate logic errors in the program.
4047 if (!lType->isFloatingType()) {
4048 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4049 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4050 if (DRL->getDecl() == DRR->getDecl())
Mike Stump9afab102009-02-19 03:04:26 +00004051 Diag(Loc, diag::warn_selfcomparison);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004052 }
Mike Stump9afab102009-02-19 03:04:26 +00004053
Nate Begemanc5f0f652008-07-14 18:02:46 +00004054 // Check for comparisons of floating point operands using != and ==.
4055 if (!isRelational && lType->isFloatingType()) {
4056 assert (rType->isFloatingType());
Chris Lattner1eafdea2008-11-18 01:30:42 +00004057 CheckFloatComparison(Loc,lex,rex);
Nate Begemanc5f0f652008-07-14 18:02:46 +00004058 }
Mike Stump9afab102009-02-19 03:04:26 +00004059
Chris Lattner10687e32009-03-31 07:46:52 +00004060 // FIXME: Vector compare support in the LLVM backend is not fully reliable,
4061 // just reject all vector comparisons for now.
4062 if (1) {
4063 Diag(Loc, diag::err_typecheck_vector_comparison)
4064 << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4065 return QualType();
4066 }
4067
Nate Begemanc5f0f652008-07-14 18:02:46 +00004068 // Return the type for the comparison, which is the same as vector type for
4069 // integer vectors, or an integer type of identical size and number of
4070 // elements for floating point vectors.
4071 if (lType->isIntegerType())
4072 return lType;
Mike Stump9afab102009-02-19 03:04:26 +00004073
Nate Begemanc5f0f652008-07-14 18:02:46 +00004074 const VectorType *VTy = lType->getAsVectorType();
Nate Begemanc5f0f652008-07-14 18:02:46 +00004075 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
Nate Begemand6d2f772009-01-18 03:20:47 +00004076 if (TypeSize == Context.getTypeSize(Context.IntTy))
Nate Begemanc5f0f652008-07-14 18:02:46 +00004077 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
Chris Lattner10687e32009-03-31 07:46:52 +00004078 if (TypeSize == Context.getTypeSize(Context.LongTy))
Nate Begemand6d2f772009-01-18 03:20:47 +00004079 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4080
Mike Stump9afab102009-02-19 03:04:26 +00004081 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
Nate Begemand6d2f772009-01-18 03:20:47 +00004082 "Unhandled vector element size in vector compare");
Nate Begemanc5f0f652008-07-14 18:02:46 +00004083 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4084}
4085
Chris Lattner4b009652007-07-25 00:24:17 +00004086inline QualType Sema::CheckBitwiseOperands(
Mike Stump9afab102009-02-19 03:04:26 +00004087 Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
Chris Lattner4b009652007-07-25 00:24:17 +00004088{
4089 if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
Chris Lattner1eafdea2008-11-18 01:30:42 +00004090 return CheckVectorOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004091
Steve Naroff8f708362007-08-24 19:07:16 +00004092 QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
Mike Stump9afab102009-02-19 03:04:26 +00004093
Chris Lattner4b009652007-07-25 00:24:17 +00004094 if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
Steve Naroff8f708362007-08-24 19:07:16 +00004095 return compType;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004096 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004097}
4098
4099inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Mike Stump9afab102009-02-19 03:04:26 +00004100 Expr *&lex, Expr *&rex, SourceLocation Loc)
Chris Lattner4b009652007-07-25 00:24:17 +00004101{
4102 UsualUnaryConversions(lex);
4103 UsualUnaryConversions(rex);
Mike Stump9afab102009-02-19 03:04:26 +00004104
Eli Friedmanbea3f842008-05-13 20:16:47 +00004105 if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
Chris Lattner4b009652007-07-25 00:24:17 +00004106 return Context.IntTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004107 return InvalidOperands(Loc, lex, rex);
Chris Lattner4b009652007-07-25 00:24:17 +00004108}
4109
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004110/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4111/// is a read-only property; return true if so. A readonly property expression
4112/// depends on various declarations and thus must be treated specially.
4113///
Mike Stump9afab102009-02-19 03:04:26 +00004114static bool IsReadonlyProperty(Expr *E, Sema &S)
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004115{
4116 if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4117 const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4118 if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4119 QualType BaseType = PropExpr->getBase()->getType();
4120 if (const PointerType *PTy = BaseType->getAsPointerType())
Mike Stump9afab102009-02-19 03:04:26 +00004121 if (const ObjCInterfaceType *IFTy =
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004122 PTy->getPointeeType()->getAsObjCInterfaceType())
4123 if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
4124 if (S.isPropertyReadonly(PDecl, IFace))
4125 return true;
4126 }
4127 }
4128 return false;
4129}
4130
Chris Lattner4c2642c2008-11-18 01:22:49 +00004131/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
4132/// emit an error and return true. If so, return false.
4133static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004134 SourceLocation OrigLoc = Loc;
4135 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4136 &Loc);
Fariborz Jahanianf96ee9e2009-01-12 19:55:42 +00004137 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4138 IsLV = Expr::MLV_ReadonlyProperty;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004139 if (IsLV == Expr::MLV_Valid)
4140 return false;
Mike Stump9afab102009-02-19 03:04:26 +00004141
Chris Lattner4c2642c2008-11-18 01:22:49 +00004142 unsigned Diag = 0;
4143 bool NeedType = false;
4144 switch (IsLV) { // C99 6.5.16p2
4145 default: assert(0 && "Unknown result from isModifiableLvalue!");
4146 case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
Mike Stump9afab102009-02-19 03:04:26 +00004147 case Expr::MLV_ArrayType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004148 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4149 NeedType = true;
4150 break;
Mike Stump9afab102009-02-19 03:04:26 +00004151 case Expr::MLV_NotObjectType:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004152 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4153 NeedType = true;
4154 break;
Chris Lattner37fb9402008-11-17 19:51:54 +00004155 case Expr::MLV_LValueCast:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004156 Diag = diag::err_typecheck_lvalue_casts_not_supported;
4157 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004158 case Expr::MLV_InvalidExpression:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004159 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4160 break;
Chris Lattner005ed752008-01-04 18:04:52 +00004161 case Expr::MLV_IncompleteType:
4162 case Expr::MLV_IncompleteVoidType:
Douglas Gregorc84d8932009-03-09 16:13:40 +00004163 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004164 diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
4165 E->getSourceRange());
Chris Lattner005ed752008-01-04 18:04:52 +00004166 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004167 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4168 break;
Steve Naroff076d6cb2008-09-26 14:41:28 +00004169 case Expr::MLV_NotBlockQualified:
Chris Lattner4c2642c2008-11-18 01:22:49 +00004170 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4171 break;
Fariborz Jahanianf18d4c82008-11-22 18:39:36 +00004172 case Expr::MLV_ReadonlyProperty:
4173 Diag = diag::error_readonly_property_assignment;
4174 break;
Fariborz Jahanianc05da422008-11-22 20:25:50 +00004175 case Expr::MLV_NoSetterProperty:
4176 Diag = diag::error_nosetter_property_assignment;
4177 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004178 }
Steve Naroff7cbb1462007-07-31 12:34:36 +00004179
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004180 SourceRange Assign;
4181 if (Loc != OrigLoc)
4182 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner4c2642c2008-11-18 01:22:49 +00004183 if (NeedType)
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004184 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004185 else
Daniel Dunbarf7fa9dc2009-04-15 00:08:05 +00004186 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner4c2642c2008-11-18 01:22:49 +00004187 return true;
4188}
4189
4190
4191
4192// C99 6.5.16.1
Chris Lattner1eafdea2008-11-18 01:30:42 +00004193QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4194 SourceLocation Loc,
4195 QualType CompoundType) {
4196 // Verify that LHS is a modifiable lvalue, and emit error if not.
4197 if (CheckForModifiableLvalue(LHS, Loc, *this))
Chris Lattner4c2642c2008-11-18 01:22:49 +00004198 return QualType();
Chris Lattner1eafdea2008-11-18 01:30:42 +00004199
4200 QualType LHSType = LHS->getType();
4201 QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
Mike Stump9afab102009-02-19 03:04:26 +00004202
Chris Lattner005ed752008-01-04 18:04:52 +00004203 AssignConvertType ConvTy;
Chris Lattner1eafdea2008-11-18 01:30:42 +00004204 if (CompoundType.isNull()) {
Chris Lattner34c85082008-08-21 18:04:13 +00004205 // Simple assignment "x = y".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004206 ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
Fariborz Jahanian82f54962009-01-13 23:34:40 +00004207 // Special case of NSObject attributes on c-style pointer types.
4208 if (ConvTy == IncompatiblePointer &&
4209 ((Context.isObjCNSObjectType(LHSType) &&
4210 Context.isObjCObjectPointerType(RHSType)) ||
4211 (Context.isObjCNSObjectType(RHSType) &&
4212 Context.isObjCObjectPointerType(LHSType))))
4213 ConvTy = Compatible;
Mike Stump9afab102009-02-19 03:04:26 +00004214
Chris Lattner34c85082008-08-21 18:04:13 +00004215 // If the RHS is a unary plus or minus, check to see if they = and + are
4216 // right next to each other. If so, the user may have typo'd "x =+ 4"
4217 // instead of "x += 4".
Chris Lattner1eafdea2008-11-18 01:30:42 +00004218 Expr *RHSCheck = RHS;
Chris Lattner34c85082008-08-21 18:04:13 +00004219 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4220 RHSCheck = ICE->getSubExpr();
4221 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4222 if ((UO->getOpcode() == UnaryOperator::Plus ||
4223 UO->getOpcode() == UnaryOperator::Minus) &&
Chris Lattner1eafdea2008-11-18 01:30:42 +00004224 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattner34c85082008-08-21 18:04:13 +00004225 // Only if the two operators are exactly adjacent.
Chris Lattner55a17242009-03-08 06:51:10 +00004226 Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4227 // And there is a space or other character before the subexpr of the
4228 // unary +/-. We don't want to warn on "x=-1".
Chris Lattnerf1e5d4a2009-03-09 07:11:10 +00004229 Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4230 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004231 Diag(Loc, diag::warn_not_compound_assign)
4232 << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4233 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner55a17242009-03-08 06:51:10 +00004234 }
Chris Lattner34c85082008-08-21 18:04:13 +00004235 }
4236 } else {
4237 // Compound assignment "x += y"
Eli Friedmanb653af42009-05-16 05:56:02 +00004238 ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
Chris Lattner34c85082008-08-21 18:04:13 +00004239 }
Chris Lattner005ed752008-01-04 18:04:52 +00004240
Chris Lattner1eafdea2008-11-18 01:30:42 +00004241 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4242 RHS, "assigning"))
Chris Lattner005ed752008-01-04 18:04:52 +00004243 return QualType();
Mike Stump9afab102009-02-19 03:04:26 +00004244
Chris Lattner4b009652007-07-25 00:24:17 +00004245 // C99 6.5.16p3: The type of an assignment expression is the type of the
4246 // left operand unless the left operand has qualified type, in which case
Mike Stump9afab102009-02-19 03:04:26 +00004247 // it is the unqualified version of the type of the left operand.
Chris Lattner4b009652007-07-25 00:24:17 +00004248 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4249 // is converted to the type of the assignment expression (above).
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004250 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregor6fcf2ca2009-05-02 00:36:19 +00004251 // operand.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004252 return LHSType.getUnqualifiedType();
Chris Lattner4b009652007-07-25 00:24:17 +00004253}
4254
Chris Lattner1eafdea2008-11-18 01:30:42 +00004255// C99 6.5.17
4256QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
Chris Lattner03c430f2008-07-25 20:54:07 +00004257 // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
Chris Lattner1eafdea2008-11-18 01:30:42 +00004258 DefaultFunctionArrayConversion(RHS);
Eli Friedman2b128322009-03-23 00:24:07 +00004259
4260 // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4261 // incomplete in C++).
4262
Chris Lattner1eafdea2008-11-18 01:30:42 +00004263 return RHS->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00004264}
4265
4266/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4267/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004268QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4269 bool isInc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004270 if (Op->isTypeDependent())
4271 return Context.DependentTy;
4272
Chris Lattnere65182c2008-11-21 07:05:48 +00004273 QualType ResType = Op->getType();
4274 assert(!ResType.isNull() && "no type for increment/decrement expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004275
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004276 if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4277 // Decrement of bool is not allowed.
4278 if (!isInc) {
4279 Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4280 return QualType();
4281 }
4282 // Increment of bool sets it to true, but is deprecated.
4283 Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4284 } else if (ResType->isRealType()) {
Chris Lattnere65182c2008-11-21 07:05:48 +00004285 // OK!
4286 } else if (const PointerType *PT = ResType->getAsPointerType()) {
4287 // C99 6.5.2.4p2, 6.5.6p2
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004288 if (PT->getPointeeType()->isVoidType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004289 if (getLangOptions().CPlusPlus) {
4290 Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4291 << Op->getSourceRange();
4292 return QualType();
4293 }
4294
4295 // Pointer to void is a GNU extension in C.
Chris Lattnere65182c2008-11-21 07:05:48 +00004296 Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004297 } else if (PT->getPointeeType()->isFunctionType()) {
Douglas Gregorb3193242009-01-23 00:36:41 +00004298 if (getLangOptions().CPlusPlus) {
4299 Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4300 << Op->getType() << Op->getSourceRange();
4301 return QualType();
4302 }
4303
4304 Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004305 << ResType << Op->getSourceRange();
Douglas Gregorcde3a2d2009-03-24 20:13:58 +00004306 } else if (RequireCompleteType(OpLoc, PT->getPointeeType(),
4307 diag::err_typecheck_arithmetic_incomplete_type,
4308 Op->getSourceRange(), SourceRange(),
4309 ResType))
Douglas Gregor46fe06e2009-01-19 19:26:10 +00004310 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004311 } else if (ResType->isComplexType()) {
4312 // C99 does not support ++/-- on complex types, we allow as an extension.
4313 Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004314 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004315 } else {
4316 Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004317 << ResType << Op->getSourceRange();
Chris Lattnere65182c2008-11-21 07:05:48 +00004318 return QualType();
Chris Lattner4b009652007-07-25 00:24:17 +00004319 }
Mike Stump9afab102009-02-19 03:04:26 +00004320 // At this point, we know we have a real, complex or pointer type.
Steve Naroff6acc0f42007-08-23 21:37:33 +00004321 // Now make sure the operand is a modifiable lvalue.
Chris Lattnere65182c2008-11-21 07:05:48 +00004322 if (CheckForModifiableLvalue(Op, OpLoc, *this))
Chris Lattner4b009652007-07-25 00:24:17 +00004323 return QualType();
Chris Lattnere65182c2008-11-21 07:05:48 +00004324 return ResType;
Chris Lattner4b009652007-07-25 00:24:17 +00004325}
4326
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004327/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Chris Lattner4b009652007-07-25 00:24:17 +00004328/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004329/// where the declaration is needed for type checking. We only need to
4330/// handle cases when the expression references a function designator
4331/// or is an lvalue. Here are some examples:
4332/// - &(x) => x
4333/// - &*****f => f for f a function designator.
4334/// - &s.xx => s
4335/// - &s.zz[1].yy -> s, if zz is an array
4336/// - *(x + 1) -> x, if x is an array
4337/// - &"123"[2] -> 0
4338/// - & __real__ x -> x
Douglas Gregord2baafd2008-10-21 16:13:35 +00004339static NamedDecl *getPrimaryDecl(Expr *E) {
Chris Lattner48d7f382008-04-02 04:24:33 +00004340 switch (E->getStmtClass()) {
Chris Lattner4b009652007-07-25 00:24:17 +00004341 case Stmt::DeclRefExprClass:
Douglas Gregor566782a2009-01-06 05:10:23 +00004342 case Stmt::QualifiedDeclRefExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004343 return cast<DeclRefExpr>(E)->getDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00004344 case Stmt::MemberExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004345 // If this is an arrow operator, the address is an offset from
4346 // the base's value, so the object the base refers to is
4347 // irrelevant.
Chris Lattner48d7f382008-04-02 04:24:33 +00004348 if (cast<MemberExpr>(E)->isArrow())
Chris Lattnera3249072007-11-16 17:46:48 +00004349 return 0;
Eli Friedman93ecce22009-04-20 08:23:18 +00004350 // Otherwise, the expression refers to a part of the base
Chris Lattner48d7f382008-04-02 04:24:33 +00004351 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004352 case Stmt::ArraySubscriptExprClass: {
Mike Stumpe127ae32009-05-16 07:39:55 +00004353 // FIXME: This code shouldn't be necessary! We should catch the implicit
4354 // promotion of register arrays earlier.
Eli Friedman93ecce22009-04-20 08:23:18 +00004355 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4356 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4357 if (ICE->getSubExpr()->getType()->isArrayType())
4358 return getPrimaryDecl(ICE->getSubExpr());
4359 }
4360 return 0;
Anders Carlsson4b3db2b2008-02-01 07:15:58 +00004361 }
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004362 case Stmt::UnaryOperatorClass: {
4363 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump9afab102009-02-19 03:04:26 +00004364
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004365 switch(UO->getOpcode()) {
Daniel Dunbarb45f75c2008-08-04 20:02:37 +00004366 case UnaryOperator::Real:
4367 case UnaryOperator::Imag:
4368 case UnaryOperator::Extension:
4369 return getPrimaryDecl(UO->getSubExpr());
4370 default:
4371 return 0;
4372 }
4373 }
Chris Lattner4b009652007-07-25 00:24:17 +00004374 case Stmt::ParenExprClass:
Chris Lattner48d7f382008-04-02 04:24:33 +00004375 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnera3249072007-11-16 17:46:48 +00004376 case Stmt::ImplicitCastExprClass:
Eli Friedman93ecce22009-04-20 08:23:18 +00004377 // If the result of an implicit cast is an l-value, we care about
4378 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner48d7f382008-04-02 04:24:33 +00004379 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +00004380 default:
4381 return 0;
4382 }
4383}
4384
4385/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump9afab102009-02-19 03:04:26 +00004386/// designator or an lvalue designating an object. If it is an lvalue, the
Chris Lattner4b009652007-07-25 00:24:17 +00004387/// object cannot be declared with storage class register or be a bit field.
Mike Stump9afab102009-02-19 03:04:26 +00004388/// Note: The usual conversions are *not* applied to the operand of the &
Chris Lattner4b009652007-07-25 00:24:17 +00004389/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump9afab102009-02-19 03:04:26 +00004390/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregor45014fd2008-11-10 20:40:00 +00004391/// we allow the '&' but retain the overloaded-function type.
Chris Lattner4b009652007-07-25 00:24:17 +00004392QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
Eli Friedman93ecce22009-04-20 08:23:18 +00004393 // Make sure to ignore parentheses in subsequent checks
4394 op = op->IgnoreParens();
4395
Douglas Gregore6be68a2008-12-17 22:52:20 +00004396 if (op->isTypeDependent())
4397 return Context.DependentTy;
4398
Steve Naroff9c6c3592008-01-13 17:10:08 +00004399 if (getLangOptions().C99) {
4400 // Implement C99-only parts of addressof rules.
4401 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4402 if (uOp->getOpcode() == UnaryOperator::Deref)
4403 // Per C99 6.5.3.2, the address of a deref always returns a valid result
4404 // (assuming the deref expression is valid).
4405 return uOp->getSubExpr()->getType();
4406 }
4407 // Technically, there should be a check for array subscript
4408 // expressions here, but the result of one is always an lvalue anyway.
4409 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00004410 NamedDecl *dcl = getPrimaryDecl(op);
Chris Lattner25168a52008-07-26 21:30:36 +00004411 Expr::isLvalueResult lval = op->isLvalue(Context);
Nuno Lopes1a68ecf2008-12-16 22:59:47 +00004412
Chris Lattner4b009652007-07-25 00:24:17 +00004413 if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004414 // The operand must be either an l-value or a function designator
Eli Friedmane7e4dac2009-05-03 22:36:05 +00004415 if (op->getType()->isFunctionType()) {
4416 // Function designator is valid
4417 } else if (lval == Expr::LV_IncompleteVoidType) {
4418 Diag(OpLoc, diag::ext_typecheck_addrof_void)
4419 << op->getSourceRange();
4420 } else {
Chris Lattnera3249072007-11-16 17:46:48 +00004421 // FIXME: emit more specific diag...
Chris Lattner9d2cf082008-11-19 05:27:50 +00004422 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4423 << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004424 return QualType();
4425 }
Douglas Gregor531434b2009-05-02 02:18:30 +00004426 } else if (op->getBitField()) { // C99 6.5.3.2p1
Eli Friedman93ecce22009-04-20 08:23:18 +00004427 // The operand cannot be a bit-field
4428 Diag(OpLoc, diag::err_typecheck_address_of)
4429 << "bit-field" << op->getSourceRange();
Douglas Gregor82d44772008-12-20 23:49:58 +00004430 return QualType();
Nate Begemana9187ab2009-02-15 22:45:20 +00004431 } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4432 cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
Eli Friedman93ecce22009-04-20 08:23:18 +00004433 // The operand cannot be an element of a vector
Chris Lattner77d52da2008-11-20 06:06:08 +00004434 Diag(OpLoc, diag::err_typecheck_address_of)
Nate Begemana9187ab2009-02-15 22:45:20 +00004435 << "vector element" << op->getSourceRange();
Steve Naroff73cf87e2008-02-29 23:30:25 +00004436 return QualType();
4437 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump9afab102009-02-19 03:04:26 +00004438 // We have an lvalue with a decl. Make sure the decl is not declared
Chris Lattner4b009652007-07-25 00:24:17 +00004439 // with the register storage-class specifier.
4440 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4441 if (vd->getStorageClass() == VarDecl::Register) {
Chris Lattner77d52da2008-11-20 06:06:08 +00004442 Diag(OpLoc, diag::err_typecheck_address_of)
4443 << "register variable" << op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004444 return QualType();
4445 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00004446 } else if (isa<OverloadedFunctionDecl>(dcl)) {
Douglas Gregor45014fd2008-11-10 20:40:00 +00004447 return Context.OverloadTy;
Douglas Gregor5b82d612008-12-10 21:26:49 +00004448 } else if (isa<FieldDecl>(dcl)) {
4449 // Okay: we can take the address of a field.
Sebastian Redl0c9da212009-02-03 20:19:35 +00004450 // Could be a pointer to member, though, if there is an explicit
4451 // scope qualifier for the class.
4452 if (isa<QualifiedDeclRefExpr>(op)) {
4453 DeclContext *Ctx = dcl->getDeclContext();
4454 if (Ctx && Ctx->isRecord())
4455 return Context.getMemberPointerType(op->getType(),
4456 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4457 }
Nuno Lopesdf239522008-12-16 22:58:26 +00004458 } else if (isa<FunctionDecl>(dcl)) {
4459 // Okay: we can take the address of a function.
Sebastian Redl7434fc32009-02-04 21:23:32 +00004460 // As above.
4461 if (isa<QualifiedDeclRefExpr>(op)) {
4462 DeclContext *Ctx = dcl->getDeclContext();
4463 if (Ctx && Ctx->isRecord())
4464 return Context.getMemberPointerType(op->getType(),
4465 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4466 }
Douglas Gregor5b82d612008-12-10 21:26:49 +00004467 }
Nuno Lopesdf239522008-12-16 22:58:26 +00004468 else
Chris Lattner4b009652007-07-25 00:24:17 +00004469 assert(0 && "Unknown/unexpected decl type");
Chris Lattner4b009652007-07-25 00:24:17 +00004470 }
Sebastian Redl7434fc32009-02-04 21:23:32 +00004471
Chris Lattner4b009652007-07-25 00:24:17 +00004472 // If the operand has type "type", the result has type "pointer to type".
4473 return Context.getPointerType(op->getType());
4474}
4475
Chris Lattnerda5c0872008-11-23 09:13:29 +00004476QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004477 if (Op->isTypeDependent())
4478 return Context.DependentTy;
4479
Chris Lattnerda5c0872008-11-23 09:13:29 +00004480 UsualUnaryConversions(Op);
4481 QualType Ty = Op->getType();
Mike Stump9afab102009-02-19 03:04:26 +00004482
Chris Lattnerda5c0872008-11-23 09:13:29 +00004483 // Note that per both C89 and C99, this is always legal, even if ptype is an
4484 // incomplete type or void. It would be possible to warn about dereferencing
4485 // a void pointer, but it's completely well-defined, and such a warning is
4486 // unlikely to catch any mistakes.
4487 if (const PointerType *PT = Ty->getAsPointerType())
Steve Naroff9c6c3592008-01-13 17:10:08 +00004488 return PT->getPointeeType();
Mike Stump9afab102009-02-19 03:04:26 +00004489
Chris Lattner77d52da2008-11-20 06:06:08 +00004490 Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattnerda5c0872008-11-23 09:13:29 +00004491 << Ty << Op->getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00004492 return QualType();
4493}
4494
4495static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4496 tok::TokenKind Kind) {
4497 BinaryOperator::Opcode Opc;
4498 switch (Kind) {
4499 default: assert(0 && "Unknown binop!");
Sebastian Redl95216a62009-02-07 00:15:38 +00004500 case tok::periodstar: Opc = BinaryOperator::PtrMemD; break;
4501 case tok::arrowstar: Opc = BinaryOperator::PtrMemI; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004502 case tok::star: Opc = BinaryOperator::Mul; break;
4503 case tok::slash: Opc = BinaryOperator::Div; break;
4504 case tok::percent: Opc = BinaryOperator::Rem; break;
4505 case tok::plus: Opc = BinaryOperator::Add; break;
4506 case tok::minus: Opc = BinaryOperator::Sub; break;
4507 case tok::lessless: Opc = BinaryOperator::Shl; break;
4508 case tok::greatergreater: Opc = BinaryOperator::Shr; break;
4509 case tok::lessequal: Opc = BinaryOperator::LE; break;
4510 case tok::less: Opc = BinaryOperator::LT; break;
4511 case tok::greaterequal: Opc = BinaryOperator::GE; break;
4512 case tok::greater: Opc = BinaryOperator::GT; break;
4513 case tok::exclaimequal: Opc = BinaryOperator::NE; break;
4514 case tok::equalequal: Opc = BinaryOperator::EQ; break;
4515 case tok::amp: Opc = BinaryOperator::And; break;
4516 case tok::caret: Opc = BinaryOperator::Xor; break;
4517 case tok::pipe: Opc = BinaryOperator::Or; break;
4518 case tok::ampamp: Opc = BinaryOperator::LAnd; break;
4519 case tok::pipepipe: Opc = BinaryOperator::LOr; break;
4520 case tok::equal: Opc = BinaryOperator::Assign; break;
4521 case tok::starequal: Opc = BinaryOperator::MulAssign; break;
4522 case tok::slashequal: Opc = BinaryOperator::DivAssign; break;
4523 case tok::percentequal: Opc = BinaryOperator::RemAssign; break;
4524 case tok::plusequal: Opc = BinaryOperator::AddAssign; break;
4525 case tok::minusequal: Opc = BinaryOperator::SubAssign; break;
4526 case tok::lesslessequal: Opc = BinaryOperator::ShlAssign; break;
4527 case tok::greatergreaterequal: Opc = BinaryOperator::ShrAssign; break;
4528 case tok::ampequal: Opc = BinaryOperator::AndAssign; break;
4529 case tok::caretequal: Opc = BinaryOperator::XorAssign; break;
4530 case tok::pipeequal: Opc = BinaryOperator::OrAssign; break;
4531 case tok::comma: Opc = BinaryOperator::Comma; break;
4532 }
4533 return Opc;
4534}
4535
4536static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
4537 tok::TokenKind Kind) {
4538 UnaryOperator::Opcode Opc;
4539 switch (Kind) {
4540 default: assert(0 && "Unknown unary op!");
4541 case tok::plusplus: Opc = UnaryOperator::PreInc; break;
4542 case tok::minusminus: Opc = UnaryOperator::PreDec; break;
4543 case tok::amp: Opc = UnaryOperator::AddrOf; break;
4544 case tok::star: Opc = UnaryOperator::Deref; break;
4545 case tok::plus: Opc = UnaryOperator::Plus; break;
4546 case tok::minus: Opc = UnaryOperator::Minus; break;
4547 case tok::tilde: Opc = UnaryOperator::Not; break;
4548 case tok::exclaim: Opc = UnaryOperator::LNot; break;
Chris Lattner4b009652007-07-25 00:24:17 +00004549 case tok::kw___real: Opc = UnaryOperator::Real; break;
4550 case tok::kw___imag: Opc = UnaryOperator::Imag; break;
4551 case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
4552 }
4553 return Opc;
4554}
4555
Douglas Gregord7f915e2008-11-06 23:29:22 +00004556/// CreateBuiltinBinOp - Creates a new built-in binary operation with
4557/// operator @p Opc at location @c TokLoc. This routine only supports
4558/// built-in operations; ActOnBinOp handles overloaded operators.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004559Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
4560 unsigned Op,
4561 Expr *lhs, Expr *rhs) {
Eli Friedman3cd92882009-03-28 01:22:36 +00004562 QualType ResultTy; // Result type of the binary operator.
Douglas Gregord7f915e2008-11-06 23:29:22 +00004563 BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
Eli Friedman3cd92882009-03-28 01:22:36 +00004564 // The following two variables are used for compound assignment operators
4565 QualType CompLHSTy; // Type of LHS after promotions for computation
4566 QualType CompResultTy; // Type of computation result
Douglas Gregord7f915e2008-11-06 23:29:22 +00004567
4568 switch (Opc) {
Douglas Gregord7f915e2008-11-06 23:29:22 +00004569 case BinaryOperator::Assign:
4570 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
4571 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004572 case BinaryOperator::PtrMemD:
4573 case BinaryOperator::PtrMemI:
4574 ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
4575 Opc == BinaryOperator::PtrMemI);
4576 break;
4577 case BinaryOperator::Mul:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004578 case BinaryOperator::Div:
4579 ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
4580 break;
4581 case BinaryOperator::Rem:
4582 ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
4583 break;
4584 case BinaryOperator::Add:
4585 ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
4586 break;
4587 case BinaryOperator::Sub:
4588 ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4589 break;
Sebastian Redl95216a62009-02-07 00:15:38 +00004590 case BinaryOperator::Shl:
Douglas Gregord7f915e2008-11-06 23:29:22 +00004591 case BinaryOperator::Shr:
4592 ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4593 break;
4594 case BinaryOperator::LE:
4595 case BinaryOperator::LT:
4596 case BinaryOperator::GE:
4597 case BinaryOperator::GT:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004598 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004599 break;
4600 case BinaryOperator::EQ:
4601 case BinaryOperator::NE:
Douglas Gregor1f12c352009-04-06 18:45:53 +00004602 ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004603 break;
4604 case BinaryOperator::And:
4605 case BinaryOperator::Xor:
4606 case BinaryOperator::Or:
4607 ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
4608 break;
4609 case BinaryOperator::LAnd:
4610 case BinaryOperator::LOr:
4611 ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
4612 break;
4613 case BinaryOperator::MulAssign:
4614 case BinaryOperator::DivAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004615 CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
4616 CompLHSTy = CompResultTy;
4617 if (!CompResultTy.isNull())
4618 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004619 break;
4620 case BinaryOperator::RemAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004621 CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
4622 CompLHSTy = CompResultTy;
4623 if (!CompResultTy.isNull())
4624 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004625 break;
4626 case BinaryOperator::AddAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004627 CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4628 if (!CompResultTy.isNull())
4629 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004630 break;
4631 case BinaryOperator::SubAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004632 CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
4633 if (!CompResultTy.isNull())
4634 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004635 break;
4636 case BinaryOperator::ShlAssign:
4637 case BinaryOperator::ShrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004638 CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
4639 CompLHSTy = CompResultTy;
4640 if (!CompResultTy.isNull())
4641 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004642 break;
4643 case BinaryOperator::AndAssign:
4644 case BinaryOperator::XorAssign:
4645 case BinaryOperator::OrAssign:
Eli Friedman3cd92882009-03-28 01:22:36 +00004646 CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
4647 CompLHSTy = CompResultTy;
4648 if (!CompResultTy.isNull())
4649 ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
Douglas Gregord7f915e2008-11-06 23:29:22 +00004650 break;
4651 case BinaryOperator::Comma:
4652 ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
4653 break;
4654 }
4655 if (ResultTy.isNull())
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004656 return ExprError();
Eli Friedman3cd92882009-03-28 01:22:36 +00004657 if (CompResultTy.isNull())
Steve Naroff774e4152009-01-21 00:14:39 +00004658 return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
4659 else
4660 return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
Eli Friedman3cd92882009-03-28 01:22:36 +00004661 CompLHSTy, CompResultTy,
4662 OpLoc));
Douglas Gregord7f915e2008-11-06 23:29:22 +00004663}
4664
Chris Lattner4b009652007-07-25 00:24:17 +00004665// Binary Operators. 'Tok' is the token for the operator.
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004666Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
4667 tok::TokenKind Kind,
4668 ExprArg LHS, ExprArg RHS) {
Chris Lattner4b009652007-07-25 00:24:17 +00004669 BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00004670 Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
Chris Lattner4b009652007-07-25 00:24:17 +00004671
Steve Naroff87d58b42007-09-16 03:34:24 +00004672 assert((lhs != 0) && "ActOnBinOp(): missing left expression");
4673 assert((rhs != 0) && "ActOnBinOp(): missing right expression");
Chris Lattner4b009652007-07-25 00:24:17 +00004674
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004675 if (getLangOptions().CPlusPlus &&
4676 (lhs->getType()->isOverloadableType() ||
4677 rhs->getType()->isOverloadableType())) {
4678 // Find all of the overloaded operators visible from this
4679 // point. We perform both an operator-name lookup from the local
4680 // scope and an argument-dependent lookup based on the types of
4681 // the arguments.
Douglas Gregor3fc092f2009-03-13 00:33:25 +00004682 FunctionSet Functions;
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004683 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
4684 if (OverOp != OO_None) {
4685 LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
4686 Functions);
4687 Expr *Args[2] = { lhs, rhs };
4688 DeclarationName OpName
4689 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4690 ArgumentDependentLookup(OpName, Args, 2, Functions);
Douglas Gregor70d26122008-11-12 17:17:38 +00004691 }
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004692
Douglas Gregor00fe3f62009-03-13 18:40:31 +00004693 // Build the (potentially-overloaded, potentially-dependent)
4694 // binary operation.
4695 return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
Sebastian Redl5457c5e2009-01-19 22:31:54 +00004696 }
4697
Douglas Gregord7f915e2008-11-06 23:29:22 +00004698 // Build a built-in binary operation.
4699 return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
Chris Lattner4b009652007-07-25 00:24:17 +00004700}
4701
Douglas Gregorc78182d2009-03-13 23:49:33 +00004702Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
4703 unsigned OpcIn,
4704 ExprArg InputArg) {
4705 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004706
Mike Stumpe127ae32009-05-16 07:39:55 +00004707 // FIXME: Input is modified below, but InputArg is not updated appropriately.
Douglas Gregorc78182d2009-03-13 23:49:33 +00004708 Expr *Input = (Expr *)InputArg.get();
Chris Lattner4b009652007-07-25 00:24:17 +00004709 QualType resultType;
4710 switch (Opc) {
Douglas Gregorc78182d2009-03-13 23:49:33 +00004711 case UnaryOperator::PostInc:
4712 case UnaryOperator::PostDec:
4713 case UnaryOperator::OffsetOf:
4714 assert(false && "Invalid unary operator");
4715 break;
4716
Chris Lattner4b009652007-07-25 00:24:17 +00004717 case UnaryOperator::PreInc:
4718 case UnaryOperator::PreDec:
Sebastian Redl0440c8c2008-12-20 09:35:34 +00004719 resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4720 Opc == UnaryOperator::PreInc);
Chris Lattner4b009652007-07-25 00:24:17 +00004721 break;
Mike Stump9afab102009-02-19 03:04:26 +00004722 case UnaryOperator::AddrOf:
Chris Lattner4b009652007-07-25 00:24:17 +00004723 resultType = CheckAddressOfOperand(Input, OpLoc);
4724 break;
Mike Stump9afab102009-02-19 03:04:26 +00004725 case UnaryOperator::Deref:
Steve Naroffccc26a72007-12-18 04:06:57 +00004726 DefaultFunctionArrayConversion(Input);
Chris Lattner4b009652007-07-25 00:24:17 +00004727 resultType = CheckIndirectionOperand(Input, OpLoc);
4728 break;
4729 case UnaryOperator::Plus:
4730 case UnaryOperator::Minus:
4731 UsualUnaryConversions(Input);
4732 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004733 if (resultType->isDependentType())
4734 break;
Douglas Gregor4f6904d2008-11-19 15:42:04 +00004735 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4736 break;
4737 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4738 resultType->isEnumeralType())
4739 break;
4740 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4741 Opc == UnaryOperator::Plus &&
4742 resultType->isPointerType())
4743 break;
4744
Sebastian Redl8b769972009-01-19 00:08:26 +00004745 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4746 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004747 case UnaryOperator::Not: // bitwise complement
4748 UsualUnaryConversions(Input);
4749 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004750 if (resultType->isDependentType())
4751 break;
Chris Lattnerbd695022008-07-25 23:52:49 +00004752 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4753 if (resultType->isComplexType() || resultType->isComplexIntegerType())
4754 // C99 does not support '~' for complex conjugation.
Chris Lattner77d52da2008-11-20 06:06:08 +00004755 Diag(OpLoc, diag::ext_integer_complement_complex)
Chris Lattner4bfd2232008-11-24 06:25:27 +00004756 << resultType << Input->getSourceRange();
Chris Lattnerbd695022008-07-25 23:52:49 +00004757 else if (!resultType->isIntegerType())
Sebastian Redl8b769972009-01-19 00:08:26 +00004758 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4759 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004760 break;
4761 case UnaryOperator::LNot: // logical negation
4762 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4763 DefaultFunctionArrayConversion(Input);
4764 resultType = Input->getType();
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004765 if (resultType->isDependentType())
4766 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004767 if (!resultType->isScalarType()) // C99 6.5.3.3p1
Sebastian Redl8b769972009-01-19 00:08:26 +00004768 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4769 << resultType << Input->getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +00004770 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redl8b769972009-01-19 00:08:26 +00004771 // In C++, it's bool. C++ 5.3.1p8
4772 resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
Chris Lattner4b009652007-07-25 00:24:17 +00004773 break;
Chris Lattner03931a72007-08-24 21:16:53 +00004774 case UnaryOperator::Real:
Chris Lattner03931a72007-08-24 21:16:53 +00004775 case UnaryOperator::Imag:
Chris Lattner57e5f7e2009-02-17 08:12:06 +00004776 resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
Chris Lattner03931a72007-08-24 21:16:53 +00004777 break;
Chris Lattner4b009652007-07-25 00:24:17 +00004778 case UnaryOperator::Extension:
Chris Lattner4b009652007-07-25 00:24:17 +00004779 resultType = Input->getType();
4780 break;
4781 }
4782 if (resultType.isNull())
Sebastian Redl8b769972009-01-19 00:08:26 +00004783 return ExprError();
Douglas Gregorc78182d2009-03-13 23:49:33 +00004784
4785 InputArg.release();
Steve Naroff774e4152009-01-21 00:14:39 +00004786 return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004787}
4788
Douglas Gregorc78182d2009-03-13 23:49:33 +00004789// Unary Operators. 'Tok' is the token for the operator.
4790Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4791 tok::TokenKind Op, ExprArg input) {
4792 Expr *Input = (Expr*)input.get();
4793 UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4794
4795 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
4796 // Find all of the overloaded operators visible from this
4797 // point. We perform both an operator-name lookup from the local
4798 // scope and an argument-dependent lookup based on the types of
4799 // the arguments.
4800 FunctionSet Functions;
4801 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
4802 if (OverOp != OO_None) {
4803 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
4804 Functions);
4805 DeclarationName OpName
4806 = Context.DeclarationNames.getCXXOperatorName(OverOp);
4807 ArgumentDependentLookup(OpName, &Input, 1, Functions);
4808 }
4809
4810 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
4811 }
4812
4813 return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
4814}
4815
Steve Naroff5cbb02f2007-09-16 14:56:35 +00004816/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004817Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4818 SourceLocation LabLoc,
4819 IdentifierInfo *LabelII) {
Chris Lattner4b009652007-07-25 00:24:17 +00004820 // Look up the record for this label identifier.
Chris Lattner2616d8c2009-04-18 20:01:55 +00004821 LabelStmt *&LabelDecl = getLabelMap()[LabelII];
Mike Stump9afab102009-02-19 03:04:26 +00004822
Daniel Dunbar879788d2008-08-04 16:51:22 +00004823 // If we haven't seen this label yet, create a forward reference. It
4824 // will be validated and/or cleaned up in ActOnFinishFunctionBody.
Steve Naroffb88d81c2009-03-13 15:38:40 +00004825 if (LabelDecl == 0)
Steve Naroff774e4152009-01-21 00:14:39 +00004826 LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
Mike Stump9afab102009-02-19 03:04:26 +00004827
Chris Lattner4b009652007-07-25 00:24:17 +00004828 // Create the AST node. The address of a label always has type 'void*'.
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004829 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4830 Context.getPointerType(Context.VoidTy)));
Chris Lattner4b009652007-07-25 00:24:17 +00004831}
4832
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004833Sema::OwningExprResult
4834Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
4835 SourceLocation RPLoc) { // "({..})"
4836 Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
Chris Lattner4b009652007-07-25 00:24:17 +00004837 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4838 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4839
Eli Friedmanbc941e12009-01-24 23:09:00 +00004840 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Chris Lattneraa257592009-04-25 19:11:05 +00004841 if (isFileScope)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004842 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedmanbc941e12009-01-24 23:09:00 +00004843
Chris Lattner4b009652007-07-25 00:24:17 +00004844 // FIXME: there are a variety of strange constraints to enforce here, for
4845 // example, it is not possible to goto into a stmt expression apparently.
4846 // More semantic analysis is needed.
Mike Stump9afab102009-02-19 03:04:26 +00004847
Chris Lattner4b009652007-07-25 00:24:17 +00004848 // If there are sub stmts in the compound stmt, take the type of the last one
4849 // as the type of the stmtexpr.
4850 QualType Ty = Context.VoidTy;
Mike Stump9afab102009-02-19 03:04:26 +00004851
Chris Lattner200964f2008-07-26 19:51:01 +00004852 if (!Compound->body_empty()) {
4853 Stmt *LastStmt = Compound->body_back();
4854 // If LastStmt is a label, skip down through into the body.
4855 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4856 LastStmt = Label->getSubStmt();
Mike Stump9afab102009-02-19 03:04:26 +00004857
Chris Lattner200964f2008-07-26 19:51:01 +00004858 if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
Chris Lattner4b009652007-07-25 00:24:17 +00004859 Ty = LastExpr->getType();
Chris Lattner200964f2008-07-26 19:51:01 +00004860 }
Mike Stump9afab102009-02-19 03:04:26 +00004861
Eli Friedman2b128322009-03-23 00:24:07 +00004862 // FIXME: Check that expression type is complete/non-abstract; statement
4863 // expressions are not lvalues.
4864
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004865 substmt.release();
4866 return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
Chris Lattner4b009652007-07-25 00:24:17 +00004867}
Steve Naroff63bad2d2007-08-01 22:05:33 +00004868
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004869Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4870 SourceLocation BuiltinLoc,
4871 SourceLocation TypeLoc,
4872 TypeTy *argty,
4873 OffsetOfComponent *CompPtr,
4874 unsigned NumComponents,
4875 SourceLocation RPLoc) {
4876 // FIXME: This function leaks all expressions in the offset components on
4877 // error.
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004878 QualType ArgTy = QualType::getFromOpaquePtr(argty);
4879 assert(!ArgTy.isNull() && "Missing type argument!");
Mike Stump9afab102009-02-19 03:04:26 +00004880
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004881 bool Dependent = ArgTy->isDependentType();
4882
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004883 // We must have at least one component that refers to the type, and the first
4884 // one is known to be a field designator. Verify that the ArgTy represents
4885 // a struct/union/class.
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004886 if (!Dependent && !ArgTy->isRecordType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004887 return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
Mike Stump9afab102009-02-19 03:04:26 +00004888
Eli Friedman2b128322009-03-23 00:24:07 +00004889 // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
4890 // with an incomplete type would be illegal.
Douglas Gregor6e7c27c2009-03-11 16:48:53 +00004891
Eli Friedman342d9432009-02-27 06:44:11 +00004892 // Otherwise, create a null pointer as the base, and iteratively process
4893 // the offsetof designators.
4894 QualType ArgTyPtr = Context.getPointerType(ArgTy);
4895 Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004896 Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
Eli Friedman342d9432009-02-27 06:44:11 +00004897 ArgTy, SourceLocation());
Eli Friedmanc67f86a2009-01-26 01:33:06 +00004898
Chris Lattnerb37522e2007-08-31 21:49:13 +00004899 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4900 // GCC extension, diagnose them.
Eli Friedman342d9432009-02-27 06:44:11 +00004901 // FIXME: This diagnostic isn't actually visible because the location is in
4902 // a system header!
Chris Lattnerb37522e2007-08-31 21:49:13 +00004903 if (NumComponents != 1)
Chris Lattner9d2cf082008-11-19 05:27:50 +00004904 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4905 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Mike Stump9afab102009-02-19 03:04:26 +00004906
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004907 if (!Dependent) {
Eli Friedmanc24ae002009-05-03 21:22:18 +00004908 bool DidWarnAboutNonPOD = false;
Anders Carlsson68c926c2009-05-02 18:36:10 +00004909
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004910 // FIXME: Dependent case loses a lot of information here. And probably
4911 // leaks like a sieve.
4912 for (unsigned i = 0; i != NumComponents; ++i) {
4913 const OffsetOfComponent &OC = CompPtr[i];
4914 if (OC.isBrackets) {
4915 // Offset of an array sub-field. TODO: Should we allow vector elements?
4916 const ArrayType *AT = Context.getAsArrayType(Res->getType());
4917 if (!AT) {
4918 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004919 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
4920 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004921 }
4922
4923 // FIXME: C++: Verify that operator[] isn't overloaded.
4924
Eli Friedman342d9432009-02-27 06:44:11 +00004925 // Promote the array so it looks more like a normal array subscript
4926 // expression.
4927 DefaultFunctionArrayConversion(Res);
4928
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004929 // C99 6.5.2.1p1
4930 Expr *Idx = static_cast<Expr*>(OC.U.E);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004931 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004932 if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004933 return ExprError(Diag(Idx->getLocStart(),
Chris Lattner7264d212009-04-25 22:50:55 +00004934 diag::err_typecheck_subscript_not_integer)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004935 << Idx->getSourceRange());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004936
4937 Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4938 OC.LocEnd);
4939 continue;
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004940 }
Mike Stump9afab102009-02-19 03:04:26 +00004941
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004942 const RecordType *RC = Res->getType()->getAsRecordType();
4943 if (!RC) {
4944 Res->Destroy(Context);
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004945 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
4946 << Res->getType());
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004947 }
Chris Lattner2af6a802007-08-30 17:59:59 +00004948
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004949 // Get the decl corresponding to this.
4950 RecordDecl *RD = RC->getDecl();
Anders Carlsson356946e2009-05-01 23:20:30 +00004951 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Anders Carlsson68c926c2009-05-02 18:36:10 +00004952 if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
Anders Carlssonbbceaea2009-05-02 17:45:47 +00004953 ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
4954 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
4955 << Res->getType());
Anders Carlsson68c926c2009-05-02 18:36:10 +00004956 DidWarnAboutNonPOD = true;
4957 }
Anders Carlsson356946e2009-05-01 23:20:30 +00004958 }
4959
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004960 FieldDecl *MemberDecl
4961 = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4962 LookupMemberName)
4963 .getAsDecl());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004964 // FIXME: Leaks Res
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004965 if (!MemberDecl)
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004966 return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
4967 << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
Mike Stump9afab102009-02-19 03:04:26 +00004968
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004969 // FIXME: C++: Verify that MemberDecl isn't a static field.
4970 // FIXME: Verify that MemberDecl isn't a bitfield.
Eli Friedman35719da2009-04-26 20:50:44 +00004971 if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
Anders Carlssonc154a722009-05-01 19:30:39 +00004972 Res = BuildAnonymousStructUnionMemberReference(
4973 SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
Eli Friedman35719da2009-04-26 20:50:44 +00004974 } else {
4975 // MemberDecl->getType() doesn't get the right qualifiers, but it
4976 // doesn't matter here.
4977 Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4978 MemberDecl->getType().getNonReferenceType());
4979 }
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00004980 }
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004981 }
Mike Stump9afab102009-02-19 03:04:26 +00004982
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004983 return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4984 Context.getSizeType(), BuiltinLoc));
Chris Lattner0d9bcea2007-08-30 17:45:32 +00004985}
4986
4987
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004988Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4989 TypeTy *arg1,TypeTy *arg2,
4990 SourceLocation RPLoc) {
Steve Naroff63bad2d2007-08-01 22:05:33 +00004991 QualType argT1 = QualType::getFromOpaquePtr(arg1);
4992 QualType argT2 = QualType::getFromOpaquePtr(arg2);
Mike Stump9afab102009-02-19 03:04:26 +00004993
Steve Naroff63bad2d2007-08-01 22:05:33 +00004994 assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
Mike Stump9afab102009-02-19 03:04:26 +00004995
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00004996 return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
4997 argT1, argT2, RPLoc));
Steve Naroff63bad2d2007-08-01 22:05:33 +00004998}
4999
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005000Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5001 ExprArg cond,
5002 ExprArg expr1, ExprArg expr2,
5003 SourceLocation RPLoc) {
5004 Expr *CondExpr = static_cast<Expr*>(cond.get());
5005 Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5006 Expr *RHSExpr = static_cast<Expr*>(expr2.get());
Mike Stump9afab102009-02-19 03:04:26 +00005007
Steve Naroff93c53012007-08-03 21:21:27 +00005008 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5009
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005010 QualType resType;
5011 if (CondExpr->isValueDependent()) {
5012 resType = Context.DependentTy;
5013 } else {
5014 // The conditional expression is required to be a constant expression.
5015 llvm::APSInt condEval(32);
5016 SourceLocation ExpLoc;
5017 if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005018 return ExprError(Diag(ExpLoc,
5019 diag::err_typecheck_choose_expr_requires_constant)
5020 << CondExpr->getSourceRange());
Steve Naroff93c53012007-08-03 21:21:27 +00005021
Sebastian Redl6fdb28d2009-02-26 14:39:58 +00005022 // If the condition is > zero, then the AST type is the same as the LSHExpr.
5023 resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5024 }
5025
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005026 cond.release(); expr1.release(); expr2.release();
5027 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5028 resType, RPLoc));
Steve Naroff93c53012007-08-03 21:21:27 +00005029}
5030
Steve Naroff52a81c02008-09-03 18:15:37 +00005031//===----------------------------------------------------------------------===//
5032// Clang Extensions.
5033//===----------------------------------------------------------------------===//
5034
5035/// ActOnBlockStart - This callback is invoked when a block literal is started.
Steve Naroff52059382008-10-10 01:28:17 +00005036void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005037 // Analyze block parameters.
5038 BlockSemaInfo *BSI = new BlockSemaInfo();
Mike Stump9afab102009-02-19 03:04:26 +00005039
Steve Naroff52a81c02008-09-03 18:15:37 +00005040 // Add BSI to CurBlock.
5041 BSI->PrevBlockInfo = CurBlock;
5042 CurBlock = BSI;
Mike Stump9afab102009-02-19 03:04:26 +00005043
Steve Naroff52a81c02008-09-03 18:15:37 +00005044 BSI->ReturnType = 0;
5045 BSI->TheScope = BlockScope;
Mike Stumpae93d652009-02-19 22:01:56 +00005046 BSI->hasBlockDeclRefExprs = false;
Chris Lattnere7765e12009-04-19 05:28:12 +00005047 BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5048 CurFunctionNeedsScopeChecking = false;
Mike Stump9afab102009-02-19 03:04:26 +00005049
Steve Naroff52059382008-10-10 01:28:17 +00005050 BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
Douglas Gregor8acb7272008-12-11 16:49:14 +00005051 PushDeclContext(BlockScope, BSI->TheDecl);
Steve Naroff52059382008-10-10 01:28:17 +00005052}
5053
Mike Stumpc1fddff2009-02-04 22:31:32 +00005054void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpea3d74e2009-05-07 18:43:07 +00005055 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
Mike Stumpc1fddff2009-02-04 22:31:32 +00005056
Mike Stump9e439c92009-04-29 21:40:37 +00005057 ProcessDeclAttributes(CurBlock->TheDecl, ParamInfo);
5058
Mike Stumpc1fddff2009-02-04 22:31:32 +00005059 if (ParamInfo.getNumTypeObjects() == 0
5060 || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
5061 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5062
Mike Stump458287d2009-04-28 01:10:27 +00005063 if (T->isArrayType()) {
5064 Diag(ParamInfo.getSourceRange().getBegin(),
5065 diag::err_block_returns_array);
5066 return;
5067 }
5068
Mike Stumpc1fddff2009-02-04 22:31:32 +00005069 // The parameter list is optional, if there was none, assume ().
5070 if (!T->isFunctionType())
5071 T = Context.getFunctionType(T, NULL, 0, 0, 0);
5072
5073 CurBlock->hasPrototype = true;
5074 CurBlock->isVariadic = false;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005075 // Check for a valid sentinel attribute on this block.
5076 if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5077 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005078 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005079 // FIXME: remove the attribute.
5080 }
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005081 QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5082
5083 // Do not allow returning a objc interface by-value.
5084 if (RetTy->isObjCInterfaceType()) {
5085 Diag(ParamInfo.getSourceRange().getBegin(),
5086 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5087 return;
5088 }
Mike Stumpc1fddff2009-02-04 22:31:32 +00005089 return;
5090 }
5091
Steve Naroff52a81c02008-09-03 18:15:37 +00005092 // Analyze arguments to block.
5093 assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5094 "Not a function declarator!");
5095 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
Mike Stump9afab102009-02-19 03:04:26 +00005096
Steve Naroff52059382008-10-10 01:28:17 +00005097 CurBlock->hasPrototype = FTI.hasPrototype;
5098 CurBlock->isVariadic = true;
Mike Stump9afab102009-02-19 03:04:26 +00005099
Steve Naroff52a81c02008-09-03 18:15:37 +00005100 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5101 // no arguments, not a function that takes a single void argument.
5102 if (FTI.hasPrototype &&
5103 FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
Chris Lattner5261d0c2009-03-28 19:18:32 +00005104 (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5105 FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
Steve Naroff52a81c02008-09-03 18:15:37 +00005106 // empty arg list, don't push any params.
Steve Naroff52059382008-10-10 01:28:17 +00005107 CurBlock->isVariadic = false;
Steve Naroff52a81c02008-09-03 18:15:37 +00005108 } else if (FTI.hasPrototype) {
5109 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
Chris Lattner5261d0c2009-03-28 19:18:32 +00005110 CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
Steve Naroff52059382008-10-10 01:28:17 +00005111 CurBlock->isVariadic = FTI.isVariadic;
Steve Naroff52a81c02008-09-03 18:15:37 +00005112 }
Steve Naroff494cb0f2009-03-13 16:56:44 +00005113 CurBlock->TheDecl->setParams(Context, &CurBlock->Params[0],
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005114 CurBlock->Params.size());
Mike Stump9afab102009-02-19 03:04:26 +00005115
Steve Naroff52059382008-10-10 01:28:17 +00005116 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5117 E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5118 // If this has an identifier, add it to the scope stack.
5119 if ((*AI)->getIdentifier())
5120 PushOnScopeChains(*AI, CurBlock->TheScope);
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005121
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005122 // Check for a valid sentinel attribute on this block.
5123 if (!CurBlock->isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5124 Diag(ParamInfo.getAttributes()->getLoc(),
Fariborz Jahanian6dac16d2009-05-15 21:18:04 +00005125 diag::warn_attribute_sentinel_not_variadic) << 1;
Fariborz Jahanian157c4262009-05-14 20:53:39 +00005126 // FIXME: remove the attribute.
5127 }
5128
Chris Lattnerc65b8bb2009-04-11 19:27:54 +00005129 // Analyze the return type.
5130 QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5131 QualType RetTy = T->getAsFunctionType()->getResultType();
5132
5133 // Do not allow returning a objc interface by-value.
5134 if (RetTy->isObjCInterfaceType()) {
5135 Diag(ParamInfo.getSourceRange().getBegin(),
5136 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5137 } else if (!RetTy->isDependentType())
5138 CurBlock->ReturnType = RetTy.getTypePtr();
Steve Naroff52a81c02008-09-03 18:15:37 +00005139}
5140
5141/// ActOnBlockError - If there is an error parsing a block, this callback
5142/// is invoked to pop the information about the block from the action impl.
5143void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5144 // Ensure that CurBlock is deleted.
5145 llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
Mike Stump9afab102009-02-19 03:04:26 +00005146
Chris Lattnere7765e12009-04-19 05:28:12 +00005147 CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5148
Steve Naroff52a81c02008-09-03 18:15:37 +00005149 // Pop off CurBlock, handle nested blocks.
Chris Lattnereb4d4a52009-04-21 22:38:46 +00005150 PopDeclContext();
Steve Naroff52a81c02008-09-03 18:15:37 +00005151 CurBlock = CurBlock->PrevBlockInfo;
Steve Naroff52a81c02008-09-03 18:15:37 +00005152 // FIXME: Delete the ParmVarDecl objects as well???
Steve Naroff52a81c02008-09-03 18:15:37 +00005153}
5154
5155/// ActOnBlockStmtExpr - This is called when the body of a block statement
5156/// literal was successfully completed. ^(int x){...}
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005157Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5158 StmtArg body, Scope *CurScope) {
Chris Lattnerc14c7f02009-03-27 04:18:06 +00005159 // If blocks are disabled, emit an error.
5160 if (!LangOpts.Blocks)
5161 Diag(CaretLoc, diag::err_blocks_disable);
5162
Steve Naroff52a81c02008-09-03 18:15:37 +00005163 // Ensure that CurBlock is deleted.
5164 llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
Steve Naroff52a81c02008-09-03 18:15:37 +00005165
Steve Naroff52059382008-10-10 01:28:17 +00005166 PopDeclContext();
5167
Steve Naroff52a81c02008-09-03 18:15:37 +00005168 // Pop off CurBlock, handle nested blocks.
5169 CurBlock = CurBlock->PrevBlockInfo;
Mike Stump9afab102009-02-19 03:04:26 +00005170
Steve Naroff52a81c02008-09-03 18:15:37 +00005171 QualType RetTy = Context.VoidTy;
5172 if (BSI->ReturnType)
5173 RetTy = QualType(BSI->ReturnType, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005174
Steve Naroff52a81c02008-09-03 18:15:37 +00005175 llvm::SmallVector<QualType, 8> ArgTypes;
5176 for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5177 ArgTypes.push_back(BSI->Params[i]->getType());
Mike Stump9afab102009-02-19 03:04:26 +00005178
Steve Naroff52a81c02008-09-03 18:15:37 +00005179 QualType BlockTy;
5180 if (!BSI->hasPrototype)
Douglas Gregor4fa58902009-02-26 23:50:07 +00005181 BlockTy = Context.getFunctionNoProtoType(RetTy);
Steve Naroff52a81c02008-09-03 18:15:37 +00005182 else
5183 BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
Argiris Kirtzidis65b99642008-10-26 16:43:14 +00005184 BSI->isVariadic, 0);
Mike Stump9afab102009-02-19 03:04:26 +00005185
Eli Friedman2b128322009-03-23 00:24:07 +00005186 // FIXME: Check that return/parameter types are complete/non-abstract
5187
Steve Naroff52a81c02008-09-03 18:15:37 +00005188 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump9afab102009-02-19 03:04:26 +00005189
Chris Lattnere7765e12009-04-19 05:28:12 +00005190 // If needed, diagnose invalid gotos and switches in the block.
5191 if (CurFunctionNeedsScopeChecking)
5192 DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5193 CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5194
Anders Carlsson39ecdcf2009-05-01 19:49:17 +00005195 BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005196 return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5197 BSI->hasBlockDeclRefExprs));
Steve Naroff52a81c02008-09-03 18:15:37 +00005198}
5199
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005200Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5201 ExprArg expr, TypeTy *type,
5202 SourceLocation RPLoc) {
Anders Carlsson36760332007-10-15 20:28:48 +00005203 QualType T = QualType::getFromOpaquePtr(type);
Chris Lattnerda139482009-04-05 15:49:53 +00005204 Expr *E = static_cast<Expr*>(expr.get());
5205 Expr *OrigExpr = E;
5206
Anders Carlsson36760332007-10-15 20:28:48 +00005207 InitBuiltinVaListType();
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005208
5209 // Get the va_list type
5210 QualType VaListType = Context.getBuiltinVaListType();
5211 // Deal with implicit array decay; for example, on x86-64,
5212 // va_list is an array, but it's supposed to decay to
5213 // a pointer for va_arg.
5214 if (VaListType->isArrayType())
5215 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedman8754e5b2008-08-20 22:17:17 +00005216 // Make sure the input expression also decays appropriately.
5217 UsualUnaryConversions(E);
Eli Friedmandd2b9af2008-08-09 23:32:40 +00005218
Chris Lattnercb9469d2009-04-06 17:07:34 +00005219 if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible) {
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005220 return ExprError(Diag(E->getLocStart(),
5221 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattnerda139482009-04-05 15:49:53 +00005222 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner89a72c52009-04-05 00:59:53 +00005223 }
Mike Stump9afab102009-02-19 03:04:26 +00005224
Eli Friedman2b128322009-03-23 00:24:07 +00005225 // FIXME: Check that type is complete/non-abstract
Anders Carlsson36760332007-10-15 20:28:48 +00005226 // FIXME: Warn if a non-POD type is passed in.
Mike Stump9afab102009-02-19 03:04:26 +00005227
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005228 expr.release();
5229 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5230 RPLoc));
Anders Carlsson36760332007-10-15 20:28:48 +00005231}
5232
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005233Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregorad4b3792008-11-29 04:51:27 +00005234 // The type of __null will be int or long, depending on the size of
5235 // pointers on the target.
5236 QualType Ty;
5237 if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5238 Ty = Context.IntTy;
5239 else
5240 Ty = Context.LongTy;
5241
Sebastian Redl76bb8ec2009-03-15 17:47:39 +00005242 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregorad4b3792008-11-29 04:51:27 +00005243}
5244
Chris Lattner005ed752008-01-04 18:04:52 +00005245bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5246 SourceLocation Loc,
5247 QualType DstType, QualType SrcType,
5248 Expr *SrcExpr, const char *Flavor) {
5249 // Decode the result (notice that AST's are still created for extensions).
5250 bool isInvalid = false;
5251 unsigned DiagKind;
5252 switch (ConvTy) {
5253 default: assert(0 && "Unknown conversion type");
5254 case Compatible: return false;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005255 case PointerToInt:
Chris Lattner005ed752008-01-04 18:04:52 +00005256 DiagKind = diag::ext_typecheck_convert_pointer_int;
5257 break;
Chris Lattnerd951b7b2008-01-04 18:22:42 +00005258 case IntToPointer:
5259 DiagKind = diag::ext_typecheck_convert_int_pointer;
5260 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005261 case IncompatiblePointer:
5262 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5263 break;
Eli Friedman6ca28cb2009-03-22 23:59:44 +00005264 case IncompatiblePointerSign:
5265 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5266 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005267 case FunctionVoidPointer:
5268 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5269 break;
5270 case CompatiblePointerDiscardsQualifiers:
Douglas Gregor1815b3b2008-09-12 00:47:35 +00005271 // If the qualifiers lost were because we were applying the
5272 // (deprecated) C++ conversion from a string literal to a char*
5273 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
5274 // Ideally, this check would be performed in
5275 // CheckPointerTypesForAssignment. However, that would require a
5276 // bit of refactoring (so that the second argument is an
5277 // expression, rather than a type), which should be done as part
5278 // of a larger effort to fix CheckPointerTypesForAssignment for
5279 // C++ semantics.
5280 if (getLangOptions().CPlusPlus &&
5281 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5282 return false;
Chris Lattner005ed752008-01-04 18:04:52 +00005283 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5284 break;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005285 case IntToBlockPointer:
5286 DiagKind = diag::err_int_to_block_pointer;
5287 break;
5288 case IncompatibleBlockPointer:
Mike Stumpd331e752009-04-21 22:51:42 +00005289 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff3454b6c2008-09-04 15:10:53 +00005290 break;
Steve Naroff19608432008-10-14 22:18:38 +00005291 case IncompatibleObjCQualifiedId:
Mike Stump9afab102009-02-19 03:04:26 +00005292 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff19608432008-10-14 22:18:38 +00005293 // it can give a more specific diagnostic.
5294 DiagKind = diag::warn_incompatible_qualified_id;
5295 break;
Anders Carlsson355ed052009-01-30 23:17:46 +00005296 case IncompatibleVectors:
5297 DiagKind = diag::warn_incompatible_vectors;
5298 break;
Chris Lattner005ed752008-01-04 18:04:52 +00005299 case Incompatible:
5300 DiagKind = diag::err_typecheck_convert_incompatible;
5301 isInvalid = true;
5302 break;
5303 }
Mike Stump9afab102009-02-19 03:04:26 +00005304
Chris Lattner271d4c22008-11-24 05:29:24 +00005305 Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5306 << SrcExpr->getSourceRange();
Chris Lattner005ed752008-01-04 18:04:52 +00005307 return isInvalid;
5308}
Anders Carlssond5201b92008-11-30 19:50:32 +00005309
Chris Lattnereec8ae22009-04-25 21:59:05 +00005310bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
Eli Friedmance329412009-04-25 22:26:58 +00005311 llvm::APSInt ICEResult;
5312 if (E->isIntegerConstantExpr(ICEResult, Context)) {
5313 if (Result)
5314 *Result = ICEResult;
5315 return false;
5316 }
5317
Anders Carlssond5201b92008-11-30 19:50:32 +00005318 Expr::EvalResult EvalResult;
5319
Mike Stump9afab102009-02-19 03:04:26 +00005320 if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
Anders Carlssond5201b92008-11-30 19:50:32 +00005321 EvalResult.HasSideEffects) {
5322 Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5323
5324 if (EvalResult.Diag) {
5325 // We only show the note if it's not the usual "invalid subexpression"
5326 // or if it's actually in a subexpression.
5327 if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5328 E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5329 Diag(EvalResult.DiagLoc, EvalResult.Diag);
5330 }
Mike Stump9afab102009-02-19 03:04:26 +00005331
Anders Carlssond5201b92008-11-30 19:50:32 +00005332 return true;
5333 }
5334
Eli Friedmance329412009-04-25 22:26:58 +00005335 Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5336 E->getSourceRange();
Anders Carlssond5201b92008-11-30 19:50:32 +00005337
Eli Friedmance329412009-04-25 22:26:58 +00005338 if (EvalResult.Diag &&
5339 Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5340 Diag(EvalResult.DiagLoc, EvalResult.Diag);
Mike Stump9afab102009-02-19 03:04:26 +00005341
Anders Carlssond5201b92008-11-30 19:50:32 +00005342 if (Result)
5343 *Result = EvalResult.Val.getInt();
5344 return false;
5345}